JPanel重绘问题

时间:2010-11-05 19:53:23

标签: java swing

我有JFrame,我使用JPanel方法添加了paintComponent()课程。例如我绘制了红色矩形,经过一些动作后我想绘制绿色椭圆形。我试图在repaint()中调用JPanel方法,但没有任何反应。请帮帮我!

更新:这只是示例代码

public class Test extends JFrame implements ActionListener{
private Container content;
private MyPanel em; 
private JButton btn;
    Test() {
        super("test");
        content = getContentPane();
        em = new MyPanel();
        conent.add(em);
        btn = new JButton("Draw");  
        btn.addActionListener(this);
        content.add(btn);   
    }

    public void actionPerformed(ActionEvent e) {
                em.setShape("oval");
    }           

public class MyPanel extends JPanel {
private String shape = "rectangle";
    MyPanel()
    {
    }
    setShape(String shape){
        this.shape = shape;
        repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(shape == "rectanle")
          g.drawRectangle(100,25,100,200);


        }
        else if(shape == "oval"){
           g.drawOval(100, 25, 175, 175);
        }
}

2 个答案:

答案 0 :(得分:2)

尝试在markCompletelyDirty(myComponent)上致电javax.swing.RepaintManager

答案 1 :(得分:1)

尝试将shape == "oval"替换为"oval".equals(shape)。在Java中,equals()根据==相等的字符串不一定等于class Whatever { private final static String OVAL = "oval"; public void process(String arg) { if (OVAL.equals(arg)) { // Do something } } }

另外,我建议你用常量替换字符串文字:

actionPerformed

避免拼写错误的问题(就像你使用“矩形”和“矩形”一样)。

您可以添加调试语句来检查实际调用paintComponent方法,并查看执行{{1}}的时间并跟踪代码所用的路径。

顺便说一下,发布的代码不应该编译:你的大括号不匹配。