Sergey
Sergey

Reputation: 963

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

Upvotes: 0

Views: 384

Answers (2)

Cameron Skinner
Cameron Skinner

Reputation: 54296

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.

Upvotes: 1

Barend
Barend

Reputation: 17444

Try calling markCompletelyDirty(myComponent) on javax.swing.RepaintManager.

Upvotes: 2

Related Questions