Change the title text of JMenuItem upon click?

2019-07-24 00:23发布

问题:

I am adding a JMenuItem (Show History) that will toggle the appearance of a JPanel upon click. But after doing so, I want to change the title of that menu item to state the opposite action (Hide History). Is there a way to change just the text for that menu item, or must I remove the old JMenuItem and add a new one?

JMenuItem history = new JMenuItem("Show History");
history.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
        //code here to show the history
        //history.changeText("Hide History") OR viewMenu.remove(history) and create/add new one
    }
});
viewMenu.add(history);

回答1:

So this is what you do:

history.setText("Hide History");

And make history final.