I have a panel-class:
public class MyPanel extends JPanel {
Color myColor = Color.BLUE;
String string = "Hello";
public void update(String newString) {
myColor = Color.GREEN;
string = newString;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(myColor);
g2.drawString(string, 200, 100);
}
}
I want the panel to be repainted after I call the update()-method. But everything in update() works fine but not the repaint()-method which should repaint the panel. The panel is always the same with the old values. How can I update the values and show them in panel? In my frame-class I am calling the update() method. I checked if I get into that method and it works. So to mention: the calling of the update()-method cant be the problem. I also tried executing update() after some time, but repaint() never works.
public class MyFrame extends JFrame {
public MyFrame() {
setTitle("Task");
setLayout(new BorderLayout());
add(new MyPanel(), BorderLayout.CENTER);
}
public static void main(String [] args) {
MyFrame frame = new MyFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
MyPanel myPanel = new MyPanel();
myPanel.update("new Hello");
}
}