0
我是新来的Java GUI,我试图让这个程序显示一个正方形,当一个按钮被点击。没有反应,因为repaint()在paintComponent上不起作用(Graphics g)。我已经搜索过,有人说使用Event调度线程,但我仍然很困惑什么是调用paintComponent的正确方法?
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);
}
}
我很后悔花时间来回答这个问题。我只注意到你在论坛上提出了10个问题,而没有必要花时间接受你问题的答案。我想你不明白我们给你的帮助。 – camickr
对不起,我**只是**发现你可以这样做, – TheEyesHaveIt
确实感谢帮助。 – TheEyesHaveIt