私はこのコードをJavaで使用しようとしました.JFrameを独自のActionListenerとして使用しました。現在、理論的には可能です。Java では、クラスは多数のインターフェースを実装することも、別のクラスを拡張することもできるからです。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
/*
* This is an example of the strangeness of the syntax of Java. In this example, I am using the JFrame itself as the listener for its component, namely a JButton which, on clicking, ends the program.
* Warning : This is just an example, and I would never recommend this syntax, for I do not know the full consequences yet.
*/
@SuppressWarnings("serial") public class ListenerTest extends JFrame implements ActionListener{
private final JPanel contentPane;
private final JLabel message;
private final JButton button;
/**
* Launch the application.
*/
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
@Override public void run(){
try{
ListenerTest frame = new ListenerTest();
frame.setVisible(true);
} catch(Exception e){
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ListenerTest(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 200, 150);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
message = new JLabel("Hello World");
message.setFont(new Font("Times New Roman", Font.PLAIN, 16));
message.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(message, BorderLayout.CENTER);
button = new JButton("Click Me!");
button.addActionListener(this);
contentPane.add(button, BorderLayout.SOUTH);
}
@Override public void actionPerformed(ActionEvent arg0){
JOptionPane.showMessageDialog(null, "Well, I listened for myself!");
System.exit(0);
}
}
私の質問は次のとおりです。コンポーネントを独自のリスナーとして使用することに問題はありますか?