我正在开发一个使用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);
}
}
}
// close.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方法指向action类,以便程序以正确的方式终止?
答案 0 :(得分:0)
您可以像Action类一样扩展ActionListener并退出Action.java中处理事物的方式
//from your code
else if(b1.getText().equalsIgnoreCase("exit"))
{
System.exit(0);
}
答案 1 :(得分:0)
您需要JFrame在您自己的动作侦听器中执行此操作
public class MyListener extends WindowAdapter implements ActionListener
{
JFrame frame ;
public MyListener(JFrame component) {
this.frame = component;
}
@Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Exit")) {
//When the last displayable window within the Java virtual
// machine (VM) is disposed of, the VM may terminate
frame.dispose();
}
}
@Override
public void windowClosing(WindowEvent e) {
// perfrom operation after window closed
Component component = e.getComponent();
String name = component.getName();
System.out.println("Component " + name + " is closing");
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("window is closed");
}
}
将侦听器添加到框架和按钮
JFrame frame = new JFrame("Test Frame");
buttonExit = new JButton("Exit");
listener = new MyListener(this);
frame.addWindowListener(listener);
buttonExit.addActionListener(listener);