简体   繁体   English

JPanel重绘问题

[英]JPanel redraw problem

I have JFrame , and I added my JPanel class with paintComponent() method. 我有JFrame ,并用paintComponent()方法添加了JPanel类。 For example I drawed red rectangle, and after some action I want to draw green oval. 例如,我绘制了红色矩形,而在执行一些操作后,我想绘制绿色椭圆形。 I tried to call repaint() method in JPanel but nothing happens. 我试图在JPanel调用repaint()方法,但没有任何反应。 Help me please! 请帮帮我!

UPDATE: It's just example code 更新:这只是示例代码

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);
        }
}

尝试在javax.swing.RepaintManager上调用markCompletelyDirty(myComponent)

Try replacing shape == "oval" with "oval".equals(shape) . 尝试将shape == "oval"替换为"oval".equals(shape) In Java, Strings that are equal according to equals() are not necessarily equal according to == . 在Java中,根据equals()相等的字符串不一定根据==相等。

Also, I'd suggest you replace the string literals with constants: 另外,我建议您将字符串文字替换为常量:

class Whatever {
    private final static String OVAL = "oval";

    public void process(String arg) {
        if (OVAL.equals(arg)) {
            // Do something
        }
    }
}

to avoid problems with spelling mistakes (like you have with "rectangle" and "rectanle"). 避免出现拼写错误的问题(例如您遇到“矩形”和“矩形”)。

You could add debugging statements to check that the actionPerformed method is actually being called, and to see when paintComponent is executed and trace what path it takes through your code. 您可以添加调试语句,以检查actionPerformed方法是否真正被调用,并查看何时执行paintComponent并跟踪代码中采用的路径。

By the way, the code as posted shouldn't compile: you have mismatched braces. 顺便说一句,发布的代码不应编译:括号不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM