简体   繁体   中英

JPanel redraw problem

I have JFrame , and I added my JPanel class with paintComponent() method. 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. 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) . In Java, Strings that are equal according to equals() are not necessarily equal according to == .

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.

By the way, the code as posted shouldn't compile: you have mismatched braces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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