我有一个由两个组成的框架 JPanels
Panel1
包含一个按钮,当单击该按钮时,我希望 panel2 更改颜色并变为红色,但这并没有发生
因此,有关如何从另一个面板更改面板颜色的任何帮助和解释
public class MyForm extends JFrame {
public MyForm() {
// TODO Auto-generated constructor stub
super();
// setLayout(new FlowLayout());
Panel1 panel1 = new Panel1();
add(panel1, BorderLayout.NORTH);
Panel2 panel2 = new Panel2();
add(panel2, BorderLayout.CENTER);
}
class Panel1 extends JPanel {
public Panel1() {
// TODO Auto-generated constructor stub
JButton btn = new JButton("Change Color");
add(btn);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("Sqsq");
Panel2 panel2 = new Panel2();
panel2.setBackground(Color.red);
panel2.repaint();
}
});
}
}
class Panel2 extends JPanel {
public Panel2() {
// TODO Auto-generated constructor stub
super();
setBackground(Color.black);
}
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
}
}
public static void main(String[] args) {
MyForm form = new MyForm();
// form.setLocationRelativeTo(null);
form.setSize(500, 500);
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form.setVisible(true);
}
}