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);
So this is what you do:
history.setText("Hide History");
And make history final.
Related
I am creating a simple text editor similiar to Notepad.
It would insert the time and date to the file if the user presses F5.
I browsed about mnemonics and accelerators but they are used in combination with Alt and Ctrl respectively.
Should I use an EventListener or is there any other solution?
You could simply use:
JMenuItem menuItem = new JMenuItem("Refresh");
KeyStroke f5 = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0);
menuItem.setAccelerator(f5);
with KeyStroke having 0 specifying no modifiers as described in the docs.
An ActionListener is the appropriate listener for menu item events.
As partly already mentioned in some comments, the recommended approach is
use an action to configure a menuItem
configure the action with an accelerator
add the action to the menu
Some code:
Action doLog = new AbstractAction("Dummny log!") {
#Override
public void actionPerformed(ActionEvent e) {
LOG.info("doing: " + getValue(Action.NAME));
}
};
doLog.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F5"));
JMenu menu = new JMenu("dummy");
menu.add(doLog);
frame.getJMenuBar().add(menu);
You can add a KeyBinding to your JMenuItem like this:
Action sayHello = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,"Hello World, From JMenuItem :)");
}
};
jMenuItem.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F5"),"sayHello");//4.The WHEN_IN_FOCUSED_WINDOW input maps of all the enabled components in the focused window are searched.
jMenuItem.getActionMap().put("sayHello",sayHello);
References:
http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#getInputMap(int)
http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html#howto
I created a menu in the menu bar in which I'd like to create a JCheckBoxMenuItem to set a condition for highlighting remaining menu items.
Something like the following pseudo-code:
if login(true)
then highlight remaining menuitems
else
un-highlight the menuitems
I think for highlighting you mean enable/disable a JMenuItem. That's possible.
Use setEnabled:
JMenuItem item;
item.setEnabled(false); //to disable
Like suggested by kleopatra, the best way of doing that is to implement your own action for each JMenuItem, and let your action to enable/disable the button accordingly to the state:
For example:
public class AMenuAction extends AbstractAction {
#override
public void actionPerformed(ActionEvent e) {
//implement your action behavior here
}
}
Then construct your JMenuItem with such action:
AMenuAction afterLoginAction = new AMenuAction();
JMenuItem item = new JMenuItem(afterLoginAction );
When the user logged in/out call setEnabled method on the desired actions.
void Login()
{
afterLoginAction.setEnabled(true);
}
Enabling and disabling menu items is done in the same way as for any other JComponent by using the setEnabled( boolean ) method
Create a JCheckBoxMenuItem as userlogin menu item
JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem();
then
add action listener to it
//unhighlite other menu items before login
jMenuFileOpen.setEnabled(false);
//...
jCheckBoxMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (login(true)){
jCheckBoxMenuItem.setSelected(true);
//highlite other menu items
jMenuFileOpen.setEnabled(true);
//...
} else {
jCheckBoxMenuItem.setSelected(false);
//unhighlite other menu items
jMenuFileOpen.setEnabled(false);
//...
}
}
});
once login(true) is successful the checkbox is checked on menu and other menu items are enabled.
Let's say I have a JMenuItem with a text inside "Exit", and a JButton with the text "Exit",
the command which JButton will use is System.exit(0), of course using Action Listener, Ok i Know, I can put the same codes when clicking on the JMenuItem, but isn't there a way, that when I click on the JMenuItem, the JButton is clicked so then the following commands are executed (JButton commands)?
What you can do is create an Action object, and use that for both your JButton and your JMenuItem.
Action exit = new AbstractAction() {
private static final long serialVersionUID = -2581717261367873054L;
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
exit.putValue(Action.NAME, "Exit");
exit.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_X);
JButton exitButton = new JButton(exit);
JMenuItem exitItem = new JMenuItem(exit);
A good way to do this is to set the same ActionListener to both components. Like this:
JButton button = new JButton ("Exit");
JMenuItem item = new JMenuItem ("Exit");
ActionListener exitaction = new ActionListener ()
{
public void actionPerformed (ActionEvent e)
{
System.exit (0);
}
};
button.addActionListener (exitaction);
item.addActionListener (exitaction);
However, I would recommend against using System.exit (0). The better way of closing the program (which I assume is basically a JFrame) is by setting
frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE)
(where frame is the window of the program)
and calling frame.dispose () in the ActionListener.
I consider the best way to do this is to register the same ActionListener instance in the event listeners of both JMenuItem and JButton, it's like using the old Command design pattern.
I would not recommend trying to trick the events 'engine' like making the JMenuItem fire the event related to the pressing of the JButton, since that is not what's happening but what you seem to want is to reuse both actions to 2 distinct events.
You can try to save the button as a class field
private JButton button;
and insert in the click event handler of the menu item the code
button.doClick();
but the solution of SoboLAN is more elegant.
I have got a JRadioButton and set a ComponentPopupMenu to it.
JRadioButton rdbtnTest = new JRadioButton();
rdbtnTest.setComponentPopupMenu(popupMenu);
The popupMenu is a JPopupMenu with one JPopupMenuItem. The JPopupMenuItem has a MouseListener, so that on a mouse click, a webpage is opened.
JPopupMenu popupMenu = new JPopupMenu("GO");
PopupMenuListener popupMenuListener = new MyPopupMenuListener();
popupMenu.addPopupMenuListener(popupMenuListener);
MenuItem openMenuItem = new JMenuItem("Open Webpage");
openMenuItem.addMouseListener(new MouseListener() {
#Override
public void mousePressed(MouseEvent arg0) {
Component comp = arg0.getComponent(); // will only return the JPopupMenuItem
// Determine the right-clicked radio button and open webpage
}
popupMenu.add(openMenuItem);
My question is: if I have another JRadioButton rdbtnTest2 with the same popupMenu, can I determine which of the two radio buttons triggered the JPopupMenu? When opening the webpage, I need to pass a specific parameter according to which radio button was right-clicked.
Whn you show popup menu in a MouseListener just get event source and store it somewhere (radiobutton which calls the menu). In your code just check the popup invoker.
menuBar = new JMenuBar();
// File Menu
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// File->New
JMenuItem newMenuItem = new JMenuItem("New");
frame.setJMenuBar(menuBar);
newMenuItem.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
btnExample.setText("Clicked");
btnExample.doClick();
//---------->SOME HOW TO EXECUTE btnExample<---------//
}
});
fileMenu.add(newMenuItem);
final JButton btnExample = new JButton("SD");
frame.getContentPane().add(btnExample, "cell 4 0,growx,aligny top");
btnExample.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
spinnerForVar.setValue(4);//default value for spinner
spinnerForFunc.setValue(4);//default value for spinner
...
}
});
Hello! I hope someone can help me. Here it is the problem: I have Menu item "New" and have button btnExample. I want the following: When i click on "File->New" it executes btnExample. My code is able only to change the button title and show visual affect of clicking. But how can I actually execute it?
I have only one advice - don't do that. Don't bind GUI components in this way.
If you want two components to execute the same operation, simply pack this operation in a method and call the method from both components.
Also, use ActionListener - are you sure the user is going to press it using mouse and not keyboard? what if you add shortcuts to those buttons/components?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//My button to click on it
jButton1ActionPerformed(evt);//this is the call for the other button to execut it
}
You should not be using a MouseListener for this.
You should be using Actions. Then you can add the Action to both the JButton and the JMemuItem.
Read the section from the Swing tutorial on How to Use Actions.
Amazing, I found my solution in your codes!
btnExample.doClick();
This did the job for me