【发布时间】:2015-11-13 10:03:36
【问题描述】:
我是一个早期的初学者,正在尝试创建一个 GUI。我有 4 个基本课程(见下文):
- GuiApp.java - 使用 main 方法,调用 MainFrame 类
- MainFrame.Java - 扩展 JFrame - 添加 MainPpanel
- MainPanel.Java - 扩展 JPanel - 添加面板
- InnerPanel.Java - 扩展 JPanel - 显示 JLabel
我找到了以下代码来添加渐变背景:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
TestPanel panel = new TestPanel();
frame.add(panel);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
这在添加到 InnerPanel.java 时有效,但在添加到 MainPanel.Java 时无效
没有错误,我只是得到默认的灰色,注意:InnerPanel.Java 设置为透明。
那么如何解决这个问题呢?当然我可以将渐变背景添加到主面板并在其上添加透明面板?
我的 4 节课:
public class GuiApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame();
}
});
}
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class MainFrame extends JFrame {
private MainPanel mainPanel;
public MainFrame() {
super("GuiApp");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(300, 500);
// setBackground(new Color(95, 158, 160));
setLayout(new BorderLayout());
mainPanel = new MainPanel();
add(mainPanel, BorderLayout.CENTER);
}
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
public class MainPanel extends JPanel {
private InnerPanel panel;
public MainPanel() {
setLayout(new BorderLayout());
panel = new InnerPanel();
add(panel, BorderLayout.CENTER);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
int w = getWidth();
int h = getHeight();
Color color1 = Color.RED;
Color color2 = Color.GREEN;
GradientPaint gp = new GradientPaint(0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
public class InnerPanel extends JPanel {
public InnerPanel() {
setBackground(new Color(0, 0, 0, 0));
JLabel label = new JLabel("testing");
add(label);
}
}
【问题讨论】:
-
This works when added to InnerPanel.java, but not when added to MainPanel.Java,- 没有意义(对我来说)我不知道您要向任一面板添加什么。您不会在内部面板中添加任何内容。你在 innerPanel 中添加了什么?你在 mainPanel 中添加了什么。InnerPanel.Java is set to transparent.- 不要使用透明背景,否则会出现绘画问题。只需使用setOpaqaue(false)。 -
setBackground(new Color(0, 0, 0, 0));不是你在 Swing 中如何使组件透明的,Swing 只知道如何绘制完全不透明或完全透明的组件,这是由opaque属性定义的,如 camickr 所示
标签: java swing jframe jpanel gradient