我正在尝试使用2个面板制作程序,当单击第一个面板时会显示另一种颜色,而在第二个面板中,该单词会更改为当前显示的颜色 问题是repaint()没有再次调用paintComponent()
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();
}
}
}
答案 0 :(得分:1)
在mouseClicked
,您在go()
上呼叫new B
。但是新B从未添加到另一个组件中。您可能想要使用被定义为成员变量的B来说b.repaint()
。