Dynamically adding buttons during runtime in Swing - java

I have this strange problem when I add buttons to the toolbar. I added action listener to one button added before the frame is shown and it works fine:
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
toolbar.add(new JButton("new button"));
}
});
I also added a piece of code that is supposed to add a new button after some plugins are loaded, and for some reason that piece of code does not work.
#Override
public void handle() {
System.out.println("Button added");
MainFrame frame = Application.getInstance().getMainFrame();
frame.getToolbar().add(new JButton("Plugin button"));
frame.getToolbar().revalidate();
frame.getToolbar().repaint();
System.out.println(frame.getToolbar().getComponents().length); // It is definitely being added, just not shown
}
The button is definitely being added, just not shown.
I would really appreciate any help since this thing is blocking me from progressing any further.

I found out what the problem was. The problem was that I instantiated MainFrame twice, first by calling Application constructor in main and then when calling Application.getInstance(), so all components added to the MainFrame were removed.

Related

JButton without function

I got the problem that my buttons are not working. I have used JButtons before and hadn't had a problem with them before. Visually, the program looks as intended.
Can someone tell me why the button is not working? The class uses JDialog.
JButton cancel;
public CodeExample() {
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(cancel = new JButton ("Cancel"));
setAlwaysOnTop(true);
setModal(true);
setVisible(true);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("test");
}
});
}
As Roddy of the Frozen Peas already pointed out, the last thing you should do is to make the dialog visible.
The problem here are those two lines:
this.setModal(true);
this.setVisible(true);
If a dialog is modal, then setVisible will block until the dialog is not longer visible or disposed.
This means that everything after setVisible is executed after the user clicks on the red X to close the window. But at this point the dialog is not longer visible and you don't show the dialog again.

JPopupMenu gets closed as soon as the mouse enters in an embedded JCheckboxMenuItem

I wrote the following code to have a JPopupMenu that allows multiple selection of different items.
The problem is that, as soon as the mouse enters one of the displayed JCheckboxMenuItems, the JPopupMenu gets closed. This issue doesn't occur if I replace JCheckboxMenuItem with, for example, JLabel but, for sure, JLabel doesn't work for my purpose.
Any idea of what could trigger this issue? Any idea of how this problem can be resolved in a better way? I apologize for the newbie question but I'm not a java developer. Thanks in advance for any help.
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedborder(),"Select Layers");
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
for (MyAction layer : layers) {
JCheckBoxMenuItem box = new JCheckBoxMenuItem(layer);
box.setIcon(new SquareIcon(myColor));
panel.add(box);
}
JPopup popup = new JidePopup();
popup.add(panel)
JButton button = new JButton("Layers");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
popup.show(button,0,button.getHeight())
}
});
Thats in the nature of JPopupMenus. They disappear when the invoker component loses the focus. But I found a little trick here.
Create your own class and extend it from JPopupMenu. Then override the setVisible method that it will only forward true to the super class and create an own method that will setVisible of the super class to false.
public class StayOpenPopup extends JPopupMenu{
public void setVisible(boolean visible){
if(visible == true)
super.setVisible(visible);
}
public void disappear() {
super.setVisible(false);
}
}
Then use it like this in your code
[...]
StayOpenPopup popup = new StayOpenPopup();
popup.add(panel);
[...]
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(popup.isVisible())
popup.disappear();
else popup.show(button,0,button.getHeight());
}
});
Now one click on button will show it. And it will stay visible until next click on Button.

Key bindings not working for JFrame

I've read several topics showing how to create a KeyBinding, however, none of them fully worked for me. My JFrame has a JMenuBar and for the items of the menu NetBeans is correctly generating code such as:
mniExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
mniExit.setText(bundle.getString("Menu.File.Exit")); // NOI18N
mniExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniExitActionPerformed(evt);
}
});
mnuFile.add(mniExit);
However, only this binding is not visible when the menu is hidden. I've tried something like:
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(mniExit.getAccelerator(), "exit");
getRootPane().getActionMap().put("exit", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
mniExit.doClick();
}
});
But it simply does not work. What am I doing wrong?
Thanks in advance!
You state that
However, only this binding is not visible when the menu is hidden. I've tried something like:
I'm guessing here, but I'm not sure that a button or menu can be clicked if its not visible. To simplify, I would create an ExitAction class, a class that extends from AbstractAction, that is assigned as an Action to any JMenuItems, JButtons, or Key Bindings that need it. If they all share the same ExitAction object, then the Action (and the corresponding menu items and buttons) can be disabled all at once if need be.
If this does not help, again create and post a minimal example program where you create the smallest program that runs, compiles, requires no outside dependencies (images, database) and that demonstrates your problem for us.

How to restart a Java Application launching a specific class of my application?

I have the following situatation:
I have a Java Swing application.
In the class that implement my GUI I have a button named Log Out tath is binding to an event listener that handle the click event, something like it:
JButton logOutButton = new JButton("LogOut");
header.add(logOutButton);
Then in the same class that implement my GUI I have declared the ActionListener that handle this event using an inner class:
logOutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("logOutButton clicked !!!");
System.exit(0);
}
});
In this moment when I click the logOutButton button the program end. I would that instead exit it is restarted by running a specific class called LoginForm (the class that implement the login form GUI)
What can I do to do this thing?
Tnx
Andrea
You don't really need to close/open window junky approach at all. Just use Card Layout:
set Frame's content pane's layout to card layout.
getContentPane().setLayout(new CardLayout());
Put your different Form's content code inside different panel and
add them to the content pane with their corresponding name, for example:
getContetnPane().add(logInFormPanel, "logIn Form");
Now you can simulate the card to appear whenever necessary by calling CardLayout.show(Container parent, String name). For example:
logOutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("logOutButton clicked !!!");
CardLayout cl = (CardLayout)(getContentPane().getLayout());
cl.show(getContentPane(), "logIn Form");
}
});
Check out a CardLayout demo from my another answer.

How to stop JButton being enabled when mouse hovers over it?

I created a frame using NetBeans. The frame has two buttons A and B. Button A is initially disabled. It is to be enabled only when button B is clicked.
public newFrame() { //newFrame is the name of the frame that has buttons A&B
initComponents();
btn_A.disable();
}
private void btn_BActionPerformed(java.awt.event.ActionEvent evt)
{
btn_A.enable();
}
The problem is that button A becomes active/enabled when the mouse is moved over it ie inspite of whether button B is clicked or not. How can i fix this?
I want button A to be enabled only after button B is clicked and not as a result of any other event.
Use btn_A.setEnabled(false) instead of btn_A.disable()
btn_A.enable() is a deprecated method.
To do this task, you could replace it by btn_A.setEnabled(false); to disable the button and btn_A.setEnabled(true); to enable the button.
Also, one more suggestion is, add statements like the following in your method if you feel something wrong happening:
System.out.println("Some statement relevant to the method");
The main aim of those extra statements being you know when the method was actually executed.
Try the following code:
button. addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
button.setEnable(true);
}
public void mouseExited(MouseEvent me) {
button.setEnable(false);
}
});

Categories