不要在paintComponent中添加组件。此方法仅用于绘制,不适用于程序逻辑或构建GUI。知道这个方法被多次调用,通常由JVM调用,并且大部分时间都不受你的控制,并且知道当你要求通过repaint()方法调用它时,这只是一个建议,油漆经理有时可能会选择忽略您的请求。 paintComponent方法必须精简且快速,因为任何减慢它的速度都会降低应用程序的感知响应速度。
在你当前的代码中,我甚至没有看到需要覆盖paintComponent方法,所以除非你需要它(如果做组件的自定义绘制),我建议你摆脱这个方法(和调用重绘和重新验证)。相反,在类的构造函数中添加组件,并确保在添加组件之后和调用setVisible(true)之前打包顶级容器。最重要的 - 阅读Swing教程,因为这些都包含在内。
例如。,
Main.java
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Askhsh 3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorJPanel application = new ColorJPanel();
frame.add(application);
frame.pack();
frame.setVisible(true);
}
}ColorJPanel.Java
import java.awt.*;
import javax.swing.*;
public class ColorJPanel extends JPanel{
public static final int CJP_WIDTH = 500;
public static final int CJP_HEIGHT = 500;
public ColorJPanel() {
this.setBackground(Color.WHITE);
JButton arxikopoihsh = new JButton("Αρχικοποίκηση");
JButton klhrwsh = new JButton("Κλήρωση");
add(arxikopoihsh);
add(klhrwsh);
}
// let the component size itself
public Dimension getPreferredSize() {
return new Dimension(CJP_WIDTH, CJP_HEIGHT);
}
}