我在从另一个类更改 JPanels 颜色时遇到问题。我正在尝试通过单击按钮来更改它。我正在创建一个应用程序,用户可以在其中选择他想要的颜色主题。
第一课:
public class First extends JFrame {
public JPanel contentPane = new JPanel();
public JPanel panel = new JPanel();
public First() {
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Second s = new Second();
s.startSecond();
}
});
}
}
第二类:
public class Second extends JFrame {
First f;
private JPanel contentPane;
public static void startSecond() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Second sframe = new faijaso();
sframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Second() {
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.panel.setBackground(Color.red);
f.panel.repaint();
f.panel.revalidate();
}
});
}
}
这段代码有几个问题,但最重要的是,你的First f
变量从未被初始化为空,因此如果你试图调用它的方法,程序将抛出 NullPointerException。您当然不想创建 anew First()
并将其分配给,f
因为该实例将与已经存在的可视化 First 不同。而是将 Second 的构造函数更改为接受 First 参数,然后在调用 Second 的构造函数时传入当前实例。
public Second(First f) {
this.f = f;
// ....
并在第一:
public First() {
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Second s = new Second();
s.startSecond(First.this); // pass in the First instance
}
});
}
其他问题——
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句