[英]JButton only appears after mouse rolls over it
I have this GUI class: 我有这个GUI类:
import java.awt.*;
import javax.swing.*;
public class Exp2 extends JFrame {
public Exp2 () {
setLayout(new FlowLayout());
setSize(360, 360);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
add(panel2);
add(panel1);
panel1.paint(null);
JButton button1 = new JButton("Run");
panel2.add(button1, BorderLayout.PAGE_END);
}
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(50, 50, 20, 20);
}
}
along with this main class: 与此主要类别:
import javax.swing.JFrame;
class Exp1 extends JFrame {
public static void main(String[] args) {
Exp2 box = new Exp2();
}
}
But the JButton button1
only appears after I roll my mouse over where it should be. 但是JButton
button1
只会在我将鼠标移到应该放置的位置后才会出现。 What am I doing wrong? 我究竟做错了什么?
You never call 你永远不会打电话
super.paint(g);
which paints the containers child components. 绘制容器的子组件。
Don't do custom painting in a top level container such as JFrame
. 不要在诸如
JFrame
的顶级容器中进行自定义绘制。 Rather move the paint functionality to a subclass of JComponent
. 而是将绘画功能移动到
JComponent
的子类。 There override paintComponent
rather than paint
and invoke super.paintComponent(g)
. 在这里重写
paintComponent
而不是paint
并调用super.paintComponent(g)
。 This takes advantage of the improved performance of Swing double buffering mechanism. 这利用了Swing双缓冲机制的改进性能。
See: Performing Custom Painting 请参阅: 执行自定义绘画
Call a repaint
on the JFrame
after you've added everything. 添加所有内容后,请在
JFrame
上调用repaint
。 Additionally, you need to call super.paint(g)
from your paint
method. 此外,您需要从
paint
方法中调用super.paint(g)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.