我有这些类:一个 JPanel 扩展、一个接口和 3 个 JmenuItem 类。
public class RedFrame extends javax.swing.JFrame implements ActionListener {
private JMenuBar jMenuBar1;
private JPanel jPanel1;
private fileExitCommand jMenuItem3;
private fileOpenCommand jMenuItem2;
private btnRedCommand jMenuItem1;
private JMenu jMenu1;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
RedFrame inst = new RedFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public RedFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
jPanel1 = new JPanel();
getContentPane().add(jPanel1, BorderLayout.CENTER);
}
{
jMenuBar1 = new JMenuBar();
setJMenuBar(jMenuBar1);
{
jMenu1 = new JMenu();
jMenuBar1.add(jMenu1);
jMenu1.setText("Meniu");
{
jMenuItem1 = new btnRedCommand(jPanel1, "RED");
jMenu1.add(jMenuItem1);
}
{
jMenuItem2 = new fileOpenCommand("Open");
jMenu1.add(jMenuItem2);
}
{
jMenuItem3 = new fileExitCommand("Exit");
jMenu1.add(jMenuItem3);
}
}
}
jMenuItem1.addActionListener(this);
jMenuItem2.addActionListener(this);
jMenuItem3.addActionListener(this);
pack();
setSize(300 * 16 / 9, 300);
} catch (Exception e) {
// add your error handling code here
e.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent event) {
Execute();
}
}
和
public class btnRedCommand extends JMenuItem implements Command {
protected JPanel p;
protected String text;
public btnRedCommand(JPanel p, String text) {
p.setBackground(Color.cyan);
this.setText(text);
}
public void Execute() {
// TODO Auto-generated method stub
p.setBackground(Color.red);
}
}
和
public interface Command {
public void Execute();
}
我希望根据选择了 Menu 中的哪个 jMenuItem 来调用在 3 个 JMenuItems 中实现的 Execute 方法。我怎样才能正确地做到这一点?我需要 3 个 jMenuItems 的包装类吗?