ActionListener非正统内联帧Java
所以当我点击按钮时,我试图让我的ActionListener工作。但是,每当我创建一个框架时,(错误似乎发生在createComponents()方法中,我不明白为什么),JVM就会不断生成MyCustomFrame对象的无限实例ActionListener非正统内联帧Java,java,swing,jframe,jbutton,actionlistener,Java,Swing,Jframe,Jbutton,Actionlistener,所以当我点击按钮时,我试图让我的ActionListener工作。但是,每当我创建一个框架时,(错误似乎发生在createComponents()方法中,我不明白为什么),JVM就会不断生成MyCustomFrame对象的无限实例 import java.awt.*; import javax.swing.*; import java.awt.event.*; public class MyCustomFrame extends JFrame { private JButton button;
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.");
}
}
}
我认为你应该这样做
button.addActionListener(this)
然后在同一个类中创建一个如下所示的方法
public void actionPerformed(ActionEvent e) {
label.setText("Button was clicked.");
}
至少这对我有用我认为你应该这样做
button.addActionListener(this)
class ClickListener extends MyCustomFrame implements ActionListener
然后在同一个类中创建一个如下所示的方法
public void actionPerformed(ActionEvent e) {
label.setText("Button was clicked.");
}
至少这对我有用
class ClickListener extends MyCustomFrame implements ActionListener
鼠标侦听器没有理由延伸框架。显示每次创建侦听器时都创建了另一个帧,这将创建另一个侦听器,依此类推
代码应该是:
class ClickListener implements ActionListener
鼠标侦听器没有理由延伸框架。显示每次创建侦听器时都创建了另一个帧,这将创建另一个侦听器,依此类推
代码应该是:
class ClickListener implements ActionListener