我正在开发一个使用 actionListener 和 WindowListener 事件的简单应用程序。目的是根据添加到面板的单击按钮使 default_close_operation 工作。这可以使用内部类轻松完成,但是我想为每个侦听器事件使用不同的类。这是代码:
//test.java
import java.awt.event.WindowEvent;
import javax.swing.*;
public class test extends JFrame
{
public static void main(String args[])
{
new test();
}
private JButton button, exit;
action a1 = new action();
close c1 = new close();
public test()
{
this.setSize(200,200);
this.setTitle("test ");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
button = new JButton("Button");
exit = new JButton("Exit");
exit.addActionListener(c1);
button.addActionListener(a1);
JPanel p1 = new JPanel();
p1.add(button);
p1.add(exit);
this.add(p1);
}
}
//action.java
import javax.swing.*;
import java.awt.event.*;
public class action extends WindowAdapter implements ActionListener
{
JButton b1;
public void actionPerformed(ActionEvent e)
{
b1 = (JButton)e.getSource();
if(b1.getText().equalsIgnoreCase("button"))
{
b1.setText("Clicked");
}
else if(b1.getText().equalsIgnoreCase("exit"))
{
System.exit(0);
}
}
}
//关闭.java
import javax.swing.*;
import java.awt.event.*;
public class close extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
exit.doClick(); //WRONG as no variable exists with exit name.
}
}
一切都很好,除了 close.java 类。如何将 WindowClosing 方法指向操作类,以便程序以正确的方式终止?