所以当我点击按钮时,我正试图让ActionListener工作。每当我创建一个框架时(错误似乎发生在createComponents()方法中,我看不出原因)JVM一直在生成MyCustomFrame对象的无限实例。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyCustomFrame extends JFrame
{
private JButton button;
private JLabel label;
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HEIGHT = 800;
public static void main(String[] args)
{
MyCustomFrame frame = new MyCustomFrame();
frame.setTitle("My first frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public MyCustomFrame()
{
setTitle("My Custom Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setVisible(true);
createComponents();
}
private void createComponents()
{
button = new JButton("Click me!");
ClickListener listener = new ClickListener();
button.addActionListener(listener);
label = new JLabel("Hello, World!");
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
add(panel);
}
class ClickListener extends MyCustomFrame implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
label.setText("Button was clicked.");
}
}
}
答案 0 :(得分:3)
class ClickListener extends MyCustomFrame implements ActionListener
MouseListener没有理由扩展Frame。每次创建监听器时都会显示另一个框架,这会创建另一个监听器,依此类推。
代码应该是:
class ClickListener implements ActionListener
答案 1 :(得分:0)
我认为你应该这样做
button.addActionListener(this)
然后在类似
的同一个类中创建一个方法public void actionPerformed(ActionEvent e) {
label.setText("Button was clicked.");
}
至少这对我有用