我是 Java GUI 新手,我试图让这个程序在单击按钮时显示一个正方形。什么也没有发生,因为 repaint() 不适用于 PaintComponent(Graphics g)。我已经搜索过,有人说使用事件调度线程,但我仍然很困惑
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Ham extends JFrame implements ActionListener
{
JPanel p1;
JButton b1;
public Ham(){
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1 = new JPanel();
b1 = new JButton("Check");
b1.addActionListener(this);
p1.add(b1);
add(p1, BorderLayout.NORTH);
setVisible(true);
}
public void actionPerformed (ActionEvent e){
if(e.getSource() == b1){
repaint();
}
}
public void paintComponent(Graphics g){
g.setColor(Color.BLUE);
g.fillRect(100,100,50,50);
}
}
最佳答案
JFrame 没有 PaintComponent() 方法。
自定义绘制是通过重写 JPanel
(或 JComponent)的 paintComponent()
方法来完成的。您还应该重写面板的 getPreferredSize() 方法以返回合理的值。然后将面板添加到框架中。
然后您可以在面板上调用repaint()
,并且将调用paintComponent()方法。
阅读 Swing 教程中关于 Custom Painting 的部分了解更多信息和示例。
关于java - 调用paintComponent的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20135639/