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);
}
}
Try replacing
shape == "oval"with"oval".equals(shape). In Java, Strings that are equal according toequals()are not necessarily equal according to==.Also, I’d suggest you replace the string literals with constants:
to avoid problems with spelling mistakes (like you have with “rectangle” and “rectanle”).
You could add debugging statements to check that the
actionPerformedmethod is actually being called, and to see whenpaintComponentis executed and trace what path it takes through your code.By the way, the code as posted shouldn’t compile: you have mismatched braces.