2

我有一个由两个组成的框架 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);

}
 }
4

1 回答 1

6

首先,在您的btn actionPerformed方法中,您正在创建一个 Panel2的引用,它与添加到框架中的引用不同,因此,什么都不会改变......

您需要传递Panel1并引用要更新的组件...

class Panel1 extends JPanel {

    private JComponent changeMe;

    public Panel1(JComponent changeMe) {
        this.changeMe = changeMe;
        // 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");
                if (changeMe != null) {
                    changeMe.setBackground(Color.red);
                    changeMe.repaint();
                }

            }
        });
    }
}

您可能需要请求重新绘制父容器,但看看这是怎么回事......

于 2012-10-14T08:31:45.463 回答