一个很好的方法是使用 Callback
机制。
遵循的步骤:
创建一个回调接口
interface Callback {void execute(Object result);}
GUI
类将实现Callback
接口,但不提供任何实现制作
GUI
类abstract
abstract class GUI extends Jframe implements Callback
现在创建一个
GUI
类的对象,提供Callback
接口的实际实现在这里你可以使用匿名类
GUI gui = new GUI() {@Overridepublic void execute(Object result) { System.out.println("You have selected " + result);}};
您可以通过的
execute()
方法传递任何内容Callback
。comboBox.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) { setVisible(false); dispose(); // Share the selected item with Main.class // Callback execute(comboBox.getSelectedItem());}});
在这里,Main
类负责捕获Callback
由GUI
类指示的响应。
这是代码:
import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JComboBox;import javax.swing.Jframe;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;public class Main { public static void main(String[] args) { // Show GUI java.awt.EventQueue.invokeLater(new Runnable() { public void run() { GUI gui = new GUI() { @Override public void execute(Object result) { System.out.println("You have selected " + result); } }; gui.setVisible(true); } }); // Kick off a process based on the user's selection }}interface Callback { void execute(Object result);}abstract class GUI extends Jframe implements Callback { private static final long serialVersionUID = 1L; public GUI() { setTitle("GUI"); setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); setBounds(100, 100, 350, 100); setLocationRelativeTo(null); JPanel cp = new JPanel(); cp.setBorder(new EmptyBorder(10, 10, 10, 10)); setContentPane(cp); JLabel lbl = new JLabel("Selection:"); cp.add(lbl); final JComboBox comboBox = new JComboBox(new String[] { "One", "Two", "Three" }); comboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); dispose(); // Share the selected item with Main.class execute(comboBox.getSelectedItem()); } }); cp.add(comboBox); }}


