2013-11-22 53 views
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);   
    } 
} 
+0

我很后悔花时间来回答这个问题。我只注意到你在论坛上提出了10个问题,而没有必要花时间接受你问题的答案。我想你不明白我们给你的帮助。 – camickr

+0

对不起,我**只是**发现你可以这样做, – TheEyesHaveIt

+0

确实感谢帮助。 – TheEyesHaveIt

回答

6

JFrame没有paintComponent()方法。

自定义绘画是通过覆盖JPanel(或JComponent)的paintComponent()方法完成的。您还应该覆盖面板的getPreferredSize()方法以返回合理的值。然后将面板添加到框架。

然后可以调用所述面板和所述的paintComponent()方法将被调用上repaint()

阅读从Custom Painting Swing的教程详细信息和示例部分。

相关问题