Question

I am trying to make a program with 2 panels, and when the first panel is clicked it displays another color, and in the second panel the word changes to the color that is currently displayed The problem is repaint() doesn't call paintComponent() again

class Fun extends JPanel{
public int i = 0;
A a = new A();
B b = new B();
public Fun(){
    setLayout(new GridLayout(2, 2, 10, 10));
    add(a);
    add(b);
}
public void paintComponent(Graphics g){
    setBackground(Color.WHITE);
    super.paintComponent(g);
}
class A extends JPanel implements MouseListener{
    public Color c = Color.BLUE;
    CardLayout cl = new CardLayout();
    JPanel c1 = new JPanel();
    JPanel c2 = new JPanel();
    JPanel c3 = new JPanel();
    Color[] colors = {Color.BLUE, Color.GREEN, Color.RED};
    public A(){
        addMouseListener(this);
        setLayout(cl);
        c1.setBackground(Color.BLUE);
        c2.setBackground(Color.GREEN);
        c3.setBackground(Color.RED);
        add(c1);
        add(c2);
        add(c3);
    }
    public void mouseClicked(MouseEvent e){
        cl.next(this);
        if (i==2){
            i = 0;
        }
        else{
            i++;
        }
        c = colors[i];
        new B().go();
    }
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
}
class B extends JPanel{
    JLabel l = new JLabel("Play Baby!");
    public B(){
        add(l);
    }
    public void paintComponent(Graphics g){
        System.out.println("repainted");
        A apple = new A();
        g.setColor(apple.colors[i]);
        super.paintComponent(g);
    }
    public void go(){
        repaint();
    }
}   

}

Was it helpful?

Solution

In your mouseClicked, you are calling go() on a new B. But the new B is never added to another component. You probably want to say, b.repaint(), using the B that was defined as a member variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top