我知道这个问题已经被问了很多,但我已经阅读了大约10篇不同的文章,所有文章都推荐给不同的东西,比如“frame = this”nad frame.add(d)“我不知道为什么,但没有这些一直在工作。我键入了一些东西,程序工作正常,除了Jbuttons不会出现,直到我点击JFrame几次。经过一些调整后的代码,我回到开始。现在我只是得到一个错误:
Exception in thread "main" java.lang.NullPointerException
at Guis.Dynamic_JFrame.<init>(Dynamic_JFrame.java:37)
at Guis.Dynamic_JFrame.main(Dynamic_JFrame.java:46)
继承我的代码:
public class Dynamic_JFrame extends JFrame{
static JFrame frame;
Graphics g;
Handler handler = new Handler();
JButton red = new JButton();
JButton green = new JButton();
JButton orange = new JButton();
public Dynamic_JFrame(){
red.setText("RED");
green.setText("GREEN");
orange.setText("orange");
add(green);
add(red);
add(orange);
red.addActionListener(handler);
green.addActionListener(handler);
orange.addActionListener(handler);
frame.setVisible(true);
}
public static void main(String[] args){
Dynamic_JFrame d = new Dynamic_JFrame();
frame = new JFrame("Changing colors");
frame.setPreferredSize(new Dimension(500,500));
frame.setMaximumSize(new Dimension(500,500));
frame.setMinimumSize(new Dimension(500,500));
frame.setLayout(new FlowLayout());
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class Handler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()==red){
getContentPane().setBackground(Color.RED);
}
if(e.getSource()==green){
getContentPane().setBackground(Color.GREEN);
}
if(e.getSource()==orange){
getContentPane().setBackground(Color.ORANGE);
}
}
}
}
新代码,次要更改。程序按预期工作,除非按钮不更新,直到我点击它们应该是:
JFrame frame;
public Dynamic_JFrame(){
frame = new JFrame();
frame = this;
red.setText("RED");
green.setText("GREEN");
frame.add(green);
frame.add(red);
frame.setVisible(true);
}
public static void main(String[] args){
Dynamic_JFrame d = new Dynamic_JFrame();
d.frame.setPreferredSize(new Dimension(500,500));
d.frame.setMaximumSize(new Dimension(500,500));
d.frame.setMinimumSize(new Dimension(500,500));
d.frame.setLocationRelativeTo(null);
d.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.frame.setLayout(new FlowLayout());
}
答案 0 :(得分:1)
很多事情......
首先,Dynamic_JFrame
从JFrame
延伸,所以我不知道你为什么离开并创建另一个框架......
其次,当Dynamic_JFrame
在构造函数中调用frame.setVisible
时,frame
为null
,因为它尚未初始化。
从我的角度来看,最简单的解决方案是将Dynamic_JFrame
扩展为JPanel
,而只是将其添加到JFrame
例如......
public class Dynamic_JFrame extends JPanel {
static JFrame frame;
// Not sure that this is a good idea...
Graphics g;
//...
public Dynamic_JFrame(){
// Don't use this...
//frame.setVisible(true);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {
public void run() {
Dynamic_JFrame d = new Dynamic_JFrame();
frame = new JFrame("Changing colors");
frame.setLayout(new FlowLayout());
frame.add(d);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}