How to link a JMenuItem to a JButton - java

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.

Related

Java GUI button, dialog window and input

I am trying to make a sort of phonebook and my skills in Java's GUI are rusty as I haven't made one in years. So let's assume for now that I have a single button on my window. When I click it I want it to pop up with a dialog window with three sections to input text (First Name, Last Name, and Phone number) and then when the user clicks the ok button at the bottom it will add these to a list of names and phonenumbers. What code will I need to make the button perform this action? I already know how to make the button so I'm mainly wondering about the action it performs and how to make the dialog window I need.
and how to make the dialog window I need.
You make a JDialog window the same way you make a JFrame window, somethink like:
JPanel panel = new JPanel();
panel.add( someComponent );
panel.add( anotherComponent );
JDialog dialgo = new JDialog();
dialog.add(panel);
dialog.pack();
dialog.setVisible( true );
Normally this code would be contains in a separate class and you just create an instance of the class in your ActionListener.
Ok so example your button is called button1. You will have to add an ActionListner to that button and an ActionPerformed (Which will encapasulate what happens when the button is clicked.) When the button is clicked you can create a new panel adding textboxs' in the panel.You can then add another button to proceed, which will have its ActionListner/ActionPerfromed duet storing the string inputed into the textbox into a defined String. Sample code below:
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a) {
JPanel panel1 = new JPanel();
JTextField textbox = new JTextField(50);
JTextField textbox1 = new JTextField(50);
JTextField textbox3 = new JTextField(50);
label.setText("Please enter Something below on the textbox: ");
panel1.add(label);
panel1.add(textbox);
panel1.add(textbox1);
panel1.add(textbox2);
JButton button3 = new JButton();
button3.setText("CLICK TO PROCEED");
panel1.add(button3, BorderLayout.NORTH);
frame.setContentPane(panel1);
frame.invalidate();
frame.validate();
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String s1 = textbox.getText();
String s2 = textbox1.getText();
String s3 = textbox2.getText();}}
Hope this helps. However, Please note that the variables defined under the actionPerformed are local. s1,s2,s3 cannot be used outside. Better to create private static variables outside the ActionListner/ActionPerformed method.

ActionListener on a JButton does not perform any action

I have a slight issue with my Actionlistener, when i click button nothing happens ?? I do not see where the problem is, so another pair of eyes could help me out :)
public class GameOptions extends JPanel implements ActionListener{
public GameOptions(){
System.out.println("GameOptions Class test blabla");
easyButton().addActionListener(this);
mediumButton().addActionListener(this);
hardButton().addActionListener(this);
JPanel center = new JPanel(new GridLayout(4,1,10,10));
center.add(new JLabel("Chose Difficulty Level"));
center.add(easyButton());
center.add(mediumButton());
center.add(hardButton());
this.add(center, BorderLayout.CENTER);
this.setPreferredSize(this.getPreferredSize());
this.setFocusable(true);
this.requestFocusInWindow();
}
private JButton easyButton(){
JButton levelEasy = new JButton("Easy");
return levelEasy;
}
private JButton mediumButton(){
JButton levelMedium = new JButton("Medium");
return levelMedium;
}
private JButton hardButton(){
JButton levelHard = new JButton("Hard");
return levelHard;
}
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if(src == easyButton()){
System.out.println("Easy");
}
else if(src == mediumButton()){
System.out.println("Medium");
}
else if(src == hardButton()){
System.out.println("Hard");
}
else{
}
}
}
Your xxxButton() methods create new JButtons each time, and so you add the ActionListener to a newly created JButton and then discard the button, and then add a completely different JButton, one without the ActionListener to the GUI.
Suggestion: create your JButtons, set a variable to them, add your ActionListener, and add the same button to the GUI.
So instead of this:
easyButton().addActionListener(this); // creates one JButton
center.add(easyButton()); // creates a completey different JButton
do this:
JButton easyButton = easyButton();
easyButton.addActionListener(this);
center.add(easyButton);
Note, if this were my code, I'm not sure that I'd use JButtons at all. Instead perhaps I'd use either JRadioButtons or a JComboBox.
You're creating each JButton with a function. And later you try to add it like center.add(easyButton()); but the one you added a ActionListener isn't the same button as this one. You're creating each one with new, so the reference isn't the same.
You should do it like this:
JButton buttonEasy = easyButton();
buttonEasy.addActionListener(this);
center.add(buttonEasy);

ActionListener in InternalFrame that opens another InternalFrame

I'm currently writing a Desktop-Application with Swing that consists of a MainFrame in which several InternalFrames will be running. I want to write the InternalFrames in separate classes for each to avoid having one huge MainFrame-class.
Now my problem is that I want to add an ActionListener to a MenuItem in a PopupMenu in the MenuInternalFrame that opens another InternalFrame in the MainFrame. The MenuInternalFrame appears, however when I click on the MenuItem nothing happens. When I put the code outside of the ActionListener the InternalFrame appears.
The problem must be something with the ActionListener. Could it be my workaround with the local class and a final instance to access the InternalFrame from within the mouseClicked-Method?
Here are the relevant parts of the code from the MainFrame-Constructor:
class InternalFrames {
TestInternalFrame test = new TestInternalFrame();
JDesktopPane desktopPane = new JDesktopPane();
}
final InternalFrames internalFrames = new InternalFrames();
internalFrames.desktopPane.setBackground(Color.WHITE);
Menu menu = new Menu();
menu.getMntmTestMenuItem().addMouseListener( new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
internalFrames.desktopPane.add(internalFrames.test);
internalFrames.test.setVisible(true);
}
});
internalFrames.desktopPane.add(menu);
menu.setVisible(true);
Any ideas what could be the problem? Thanks in advance.
Dont use MouseAdapter on a JMenuItem, use ActionListener and add it via JMenuItem#addActionListener(...) instead:
Menu menu = new Menu();
menu.getMntmTestMenuItem().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
internalFrames.desktopPane.add(internalFrames.test);
internalFrames.test.setVisible(true);
}
});

JRadioButton in JPopupMenu does not close the menu after selecting

With the above code i want to close the popup right after click on one of the radio buttons but the popup stays open.
Is there something build-in in swing or must i call actionPeformed and close the popup explicity ?
public class NewClass extends JFrame {
NewClass() {
setSize(100,100);
JPopupMenu pop = new JPopupMenu();
JRadioButton log1 = new JRadioButton("Level 1");
pop.add(log1);
JRadioButton log2 = new JRadioButton("Level 2");
pop.add(log2);
JPanel p = new JPanel();
add(p);
p.setComponentPopupMenu(pop);
}
public static void main(String[] args) {
new NewClass().setVisible(true);
}
}
look at JRadioButton#addItemListener() and check if ButtonGroup is usefull in your case
EDIT:
Is there something build-in in swing or must i call actionPeformed and
close the popup explicity ?
I don't know..., good question, but if you adds JRadioButton to the JMenuItem then is build-in look here
I would have added actionlisteners on the buttons so when you press a button you then use:
public void actionPerformed(ActionEvent e){
pop.setVisible(false);
pop.dispose();
}

How to execute button by clicking on another button java?

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

Categories