简体   繁体   English

如何在Java中更改“ JMenuItem”及其操作

[英]How to change “JMenuItem” and its' Action in java

in my application i used jmenuitem to perform some action to connecting specific port by socket programming. 在我的应用程序中,我使用jmenuitem进行了一些操作,以通过套接字编程来连接特定的端口。 now, i want when clicked on "Connect" menu item, change it name and action to "disconnect". 现在,我想在单击“连接”菜单项时,将其名称和操作更改为“断开连接”。 my "connect" menu item code is this: 我的“连接”菜单项代码是这样的:

connect = new JMenuItem("Connect");
    connect.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            loginForm login = new loginForm();
            login.setVisible(true);

        }
    });
 jpopupMenu.insert(connect, 0); 

and "disconnect" code is this: 和“断开连接”代码是这样的:

disconnect = new JMenuItem("Disonnect");
    disconnect.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                client.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(systemTray.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
jpopupMenu.insert(disconnect, 0);

but this code cause for duplicate item adding to Menu. 但是此代码会导致重复的项目添加到菜单。 I can't find any help for how to detect menu item is exists or replacing menu items! 对于如何检测菜单项是否存在或如何替换菜单项,我找不到任何帮助!

Your question title says it all (ie Action , but you are using ActionListener/JMenuItem ). 您的问题标题说明了一切(即Action ,但是您正在使用ActionListener/JMenuItem )。 With Action (which we can use instead of JMenuItem ), we can simply override the NAME value, which is what appears in the menu item name. 使用Action (我们可以使用它代替JMenuItem ),我们可以简单地覆盖NAME值,该值出现在菜单项名称中。 Here's an example. 这是一个例子。

Notice menu.add(Action) instead of menu.add(JMenuItem) 注意menu.add(Action)而不是menu.add(JMenuItem)

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.*;

public class TestMenu {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setSize(300, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);

        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("Menu");

        Action menuAction = new AbstractAction("Connect") {
            private boolean connected = false;
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!connected) {
                    JOptionPane.showMessageDialog(null, "Connected");
                    putValue(NAME, "Disonnect");
                    connected = true;
                } else {
                    JOptionPane.showMessageDialog(null, "Disconnected");
                    putValue(NAME, "Connect");
                    connected = false;
                }     
            }  
        };

        menuBar.add(menu);
        menu.add(menuAction);
        f.setJMenuBar(menuBar);
        f.setVisible(true);
    }
}

I guess you could do something like this, which would allow you to use single menu item for both actions and change its action/text depending on whether the client is connected or not. 我猜您可以执行类似的操作,这将允许您将单个菜单项用于两种操作,并根据客户端是否已连接来更改其操作/文本。

private JMenuItem connect = new JMenuItem("Connect");

// ...

connect.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (client.isConnected()) {
            disconnect();
        } else {
            connect();
        }
    }
});

// ...

private void connect() {
    loginForm login = new loginForm();
    login.setVisible(true);
    // TODO: You should change the label only if connection actually succeeds
    connect.setText("Disconnect");
}

private void disconnect() {
    try {
        client.disconnect();
        connect.setText("Connect");
    } catch (IOException ex) {
        Logger.getLogger(systemTray.class.getName()).log(Level.SEVERE, null, ex);
    }
}

maybe this also will help you. 也许这也会对您有帮助。
I've put it all together on a jpopupmenu 我把它们放到一个jpopupmenu上

public class Test {

    JPopupMenu popmenu;
    public boolean isConnected = false;

    public Test() {
        JFrame frame = new JFrame();
        frame.setSize(200, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        popmenu = new JPopupMenu();
        final JMenuItem connect = new JMenuItem("connect");
        connect.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if (!isConnected) {
                            System.out.println("connect action");

                            connect();

                            isConnected = true;
                        } else {
                            System.out.println("disconnect action");

                            disconnect();

                            isConnected = false;
                        }
                    }
                });

            }
        });

        popmenu.insert(connect, 0);

        frame.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    popmenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });
        frame.setVisible(true);
    }

    private void connect() {
        loginForm login = new loginForm();
        login.setVisible(true);
        // TODO: You should change the label only if connection actually
        // succeeds
        connect.setText("Disconnect");
    }

    private void disconnect() {
        try {
            client.disconnect();
            connect.setText("Connect");
        } catch (IOException ex) {
            Logger.getLogger(systemTray.class.getName()).log(Level.SEVERE,
                    null, ex);
        }
    }

    public static void main(String[] args) {
        new Test();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM