当我尝试绘制 JPanel 的扩展版本时,我不断遇到这个问题。每一次,我最终都会找到一种方法让它发挥作用。但我想确切地知道为什么以这种方式绘制 JPanel 不起作用?
public class MyPanel extends JPanel {
public MyPanel(){
init();
}
public void init(){
JFrame frame = new JFrame("");
frame.add(this);
this.setPreferredSize(new Dimension(100,100));
this.setBackground(Color.RED);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
Graphics g = this.getGraphics();
g.setColor(Color.BLUE);
g.fillRect(0, 0, 50, 50);
}
public static void main(String[] args) {
new MyPanel();
}
}
当我运行此代码时,我看到了 setBackground(Color.RED) 所期望的红色背景,但我没有看到使用 Graphics 对象绘制的蓝色矩形。即使我在 init() 的最后一行调用 repaint(),它也不会显示。
这段代码有什么问题,我以后可以避免它吗?
最佳答案
Why can't I paint onto my JPanel using Graphics?
因为这不是正确的做法。您应该重写 paintComponent
方法:
public class MyPanel extends JPanel {
public MyPanel(){
init();
}
public void init(){
JFrame frame = new JFrame("");
frame.add(this);
this.setPreferredSize(new Dimension(100,100));
this.setBackground(Color.RED);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new MyPanel();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, 50, 50);
}
}
如果您不这样做,您的绘图将只显示一会儿,然后就会消失。这样,每当您调用 repaint
方法(或每当应用程序本身重新绘制)时,都会调用该方法并填充您的矩形。
关于java - 为什么我不能使用 Graphics 在 JPanel 上绘画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19778407/