我有这个GUI设置。 tl; dr是:它是一个gui,一个MenuItem调用myActionListener。
此课程中还有一个Object o。 我希望myActionListener以及myActionListener2等可以访问这个对象。 但我甚至无法调用任何Object方法。
public class MenuDemo implements ActionListener,ItemListener{
// My Object
Object o = new Object();
o.addParam();// wont work
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
menu = new JMenu("A Menu");
menuBar.add(menu);
menuItem = new JMenuItem("Title");
menuItem.addActionListener(new myListener());
menu.add(menuItem);
return menuBar;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
Database db = new Database();
final int test = 5;
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
我一直试图弄清楚这一段时间,但似乎我无法找到任何帮助,或者我可能会以错误的方式去做它?
答案 0 :(得分:1)
正如我在评论中所说,您可以将Object
的引用传递给ActionListener
的不同类型/子类型的对象:
主要课程:
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame
{
private JButton btn;
Object o;
public Main()
{
setLayout(new FlowLayout());
o = new String("Hello Beautiful!");
btn = new JButton("Click!");
//Passing the reference `o` to the constructor
btn.addActionListener(new JButtonListener(o));
add(btn);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run()
{
new Test1();
}
});
}
}
实施ActionListener
的类:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class JButtonListener implements ActionListener
{
private Object _obj;
public JButtonListener(Object obj)
{
_obj = obj;
}
@Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, _obj.toString());
}
}