jframe actionperformed jframe - java

I currently have a button that, when clicked, performs a method that creates a jframe with a panel that loads multiple images. If this button is clicked multiple times, the images keep adding onto the prexisting images loaded onto the jframe. What code should I use so that if the button is clicked after the jframe and elements have been loaded, after clicking once, nothing else will be added.
Many thanks

What about:
public void actionPerformed(ActionEvent evt) {
button.setEnabled(false);
// the other code that creates imgFrame
imgFrame.addWindowListener(new WindowAdapter() {
#Override public void windowClosing(WindowEvent evt) {
button.setEnabled(true);
}});
imgFrame.setVisible(true);
}

don't create lots of JFrames on the runtime, because these Object never gone from Used JVM Memory untill current JVM instance exist
you have look at CardLayout that very confortly to solve your issues with multiple of views (in this case in one JFrame)
put Images as Icon/ImageIcon to the JLabel

Disable the button when frame show up, and when the frame close, enable the button.
public void actionPerformed(ActionEvent evt) {
final JButton finalButton = button;
button.setEnabled(false);
JFrame frame = new JFrame()
{
protected void processWindowEvent(WindowEvent e)
{
if (e.getID() == WindowEvent.WINDOW_CLOSING)
{
finalButton.setEnabled(true);
}
super.processWindowEvent(e);
}
};
frame.setVisible(true);
}

I suggest a boolean that is false when the program starts, and then when the button is clicked, it tests if the boolean is false. If it is false, then create the stuff that you want, and then make it true. If it is true, do nothing, or alert the user not to click the button more that once, or something of that matter

boolean isAlreadyCreated = false;
yourButton.addActionListener(new ActionListener()
{
if(!isAlreadyCreated)
{
//CREATE YOUR NEW FRAME
isAlreadyCreated = true;
}
});

Related

How to transfer an answer to another jframe? [duplicate]

I have two Jframes where frame1 has some text fields and when a button on frame1 is clicked, I open another JFrame which contains a search box and a JTable containing search results.
When I click on a result row on JTable, I want that particular values to be reflected in the frame1 text fields.
I tried passing the JFrame1's object as a parameter but I have no clear idea on how to achieve this.
Any help would be highly appreciated.
Thanks
First of all, your program design seems a bit off, as if you are using a JFrame for one of your windows where you should in fact be using a JDialog since it sounds as if one window should be dependent upon the other.
But regardless, you pass references of GUI objects the same as you would standard non-GUI Java code. If one window opens the other (the second often being the dialog), then the first window usually already holds a reference to the second window and can call methods off of it. The key often is when to have the first window call the second's methods to get its state. If the second is a modal dialog, then the when is easy -- immediately after the dialog returns which will be in the code immediately after you set the second dialog visible. If it is not a modal dialog, then you probably want to use a listener of some sort to know when to extract the information.
Having said this, the details will all depend on your program structure, and you'll need to tell us more about this if you want more specific help.
For a simple example that has one window open another, allows the user to enter text into the dialog windows JTextField, and then places the text in the first window's JTextField, please have a look at this:
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WindowCommunication {
private static void createAndShowUI() {
JFrame frame = new JFrame("WindowCommunication");
frame.getContentPane().add(new MyFramePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// let's be sure to start Swing on the Swing event thread
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyFramePanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton openDialogeBtn = new JButton("Open Dialog");
// here my main gui has a reference to the JDialog and to the
// MyDialogPanel which is displayed in the JDialog
private MyDialogPanel dialogPanel = new MyDialogPanel();
private JDialog dialog;
public MyFramePanel() {
openDialogeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openTableAction();
}
});
field.setEditable(false);
field.setFocusable(false);
add(field);
add(openDialogeBtn);
}
private void openTableAction() {
// lazy creation of the JDialog
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
dialog = new JDialog(win, "My Dialog",
ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over
// this line starts *after* the modal dialog has been disposed
// **** here's the key where I get the String from JTextField in the GUI held
// by the JDialog and put it into this GUI's JTextField.
field.setText(dialogPanel.getFieldText());
}
}
class MyDialogPanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton okButton = new JButton("OK");
public MyDialogPanel() {
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonAction();
}
});
add(field);
add(okButton);
}
// to allow outside classes to get the text held by the JTextField
public String getFieldText() {
return field.getText();
}
// This button's action is simply to dispose of the JDialog.
private void okButtonAction() {
// win is here the JDialog that holds this JPanel, but it could be a JFrame or
// any other top-level container that is holding this JPanel
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
win.dispose();
}
}
}
You'd do a very similar technique to get information out of a JTable.
And again, if this information doesn't help you, then please tell us more about your program including showing us some of your code. The best code to show is a small compilable example, an SSCCE similar to what I've posted above.

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.

jInternalFrame not brought to the front

I have a JDesktopPane which contains a number of JInternalFrames. The first time I press one button to visible jinternalframe1 and second button to visible jinternalframe2, it appear above the main window without problems. However, if I press one of the buttons to Reopen jinternalframe1 or jinternalframe2, they are not brought in front of the main window... EDIT: actually, i can't do anything with jinternalframe on a button click...i can only click once on the button and then no operation can be perform on the jinternalframe through the button..why it doesn't work!!
this is the coding of button1...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
jinternalframe1 frame1 = new jinternalframe1();
try {
if(Allow.flag == false) {
desktopPane.add(frame1);
frame1.setVisible(true);
Allow.flag = true;
} else if(Allow.flag == true) {
frame1.setSelected(true);
}
} catch(PropertyVetoException e) {
System.out.println(e);
}
}
Allow.java
public class Allow {
static boolean flag = false;
}
Every time you click on the button you create a new JInternalFrame object, but you only ever add the first internal frame that you create to the desktop pane.
Don't keep creating new internal frame objects. I would guess you should only create the internal frame if your "frame1" variable is null.
If you need more help then post a proper SSCCE that demonstrates the problem.

How to tell if a JFrame window has already been opened?

I have a JFrame with a Button that opens a different JFrame. But I want the button to only open the second frame once. Problem is, every time I click it I get a new instance of the frame. This must be a very common problem, since I'm following a book on how to create this GUI. I find it odd that the author didn't mention this "feature".
So how do I keep my button from opening multiple copies of the new frame?
Instead of letting the button create a new JFrame every time, make the second JFrame a member of the first JFrame, and only let the button call jframe2.setVisible(true);:
class JFrame1 {
JFrame2 jframe2=...;
JButton button=...;
JFrame1() {
...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jframe2.setVisible(true);
}
});
...
}
}
UPDATED!
try this:
JFrame frame2 = new JFrame(); // instance variable
...
//when button is clicked
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!frame2.isVisible())
frame2.setVisible(true);
}
});
make sure you are handling the closing of all of the JFrames manually like this:
frame2.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// handle closing the window
frame2.setVisible(false);
frame2.dispose();
}
});
instead of using the JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hope this helps.
You should keep a reference to the sub frame you open for first time. At second time you first check if you have a reference or not and then decide to create a new frame or to put the focus onto the existing open frame.
Example as answer to comment of OP (similar to other answer of #AlexanderTorstling, but not immediately creating the sub frame):
class MainFrame extends JFrame {
private JFrame subFrame = null;
MainFrame() {
...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (subFrame == null) {
subFrame = new JFrame();
...
}
subFrame.setVisible(true);
}
});
}
}
This example has also the advantage to give you the possibility to close the subframe via a registered WindowAdapter if the main frame is closed.
please try this one
JFrame frame2 = new JFrame(); // instance variable
boolean secondWindowIsOpne = false;
...
//when button is clicked
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(secondWindowIsOpne == false){
frame2.setVisible(true);
secondWindowIsOpne = true;
}
else{
System.out.println("This Window is already running");
}
});
make sure you are handling the closing of all of the JFrames manually like this:
frame2.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// handle closing the window
secondWindowIsOpne = false;
frame2.setVisible(false);
frame2.dispose();
}
});

How to wait for radio button to get selected in lost focus event

I have a Swing program that does a search based on the contents of some text fields and settings of a pair of radio buttons (in a button group). The program will automatically search when certain of the text fields lose focus. The problem comes in when the lose focus event is triggered by a click on one of the radio buttons. The lost focus event on the text field is getting processed before the radio button isSelected() values have changed, so the search is done with the "wrong" (i.e. old) parameters, instead of the parameters based on the new setting of the radio buttons.
I tried invoking the search using my own invokeWhenIdle method (shown below) to run the search after the event queue had settled down, but it still is using the old setting of the radio buttons.
My only working solution is to delay for 250 milliseconds in the lost focus event before running the search, so that the radio buttons have time to change. This works, but it makes the UI seem sluggish.
Any better ideas?
public static void invokeWhenIdle(final int a_max_retry, final Runnable a_runnable) {
if (a_max_retry <= 0) {
throw new IllegalStateException("invokeWhenIdle: Could not run " + a_runnable);
}
// get the next event on the queue
EventQueue l_queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
AWTEvent l_evt = l_queue.peekEvent();
if (l_evt == null) {
// nothing left on the queue (but us), we can do it
SwingUtilities.invokeLater(a_runnable);
} else {
// still something in the queue, try again
SwingUtilities.invokeLater(new Runnable() {
public void run() {
invokeWhenIdle(a_max_retry - 1, a_runnable);
}
});
}
}
Not an answer, but an explanation about what is happening. Maybe it will spark an idea...
The problem is that a mousePressed arms the button model and the mouseReleased actually changes the selected value of the model.
When you execute the FocusListener code the radio button the model is in an undefined state. Even if you add the FocusListener code to the end of the EDT by using invokeLater the code will still execute before the mouseReleased event is generated.
The following shows how you might code the listener to handle this. It assumes the state of the button is about to change:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FocusSSCCE extends JPanel
{
public FocusSSCCE()
{
final JRadioButton radio = new JRadioButton("Radio");
add( radio );
radio.setMnemonic('R');
JTextField textField = new JTextField(10);
add( textField );
JButton button = new JButton("Button");
add( button );
textField.addFocusListener( new FocusAdapter()
{
public void focusLost(FocusEvent e)
{
boolean isSelected = radio.isSelected();
// Assumes selected state will change
if (radio.getModel().isArmed())
isSelected = !isSelected;
System.out.println( isSelected );
}
});
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("FocusSSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new FocusSSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
However, even this approach can't be guaranteed to work. If for some reason the user generates the mousePressed event on the radio button and them moves the mouse away from the radio button before releasing the mouse, then the selected state of the radio button is not changed.
Similiarly, even your original implementation to sleep for 250ms can not be guaranteed to work because the user could theoretically hold down the mouse for more than 250ms which would also generate the wrong value.
My workaround for this was to make the radio buttons non focusable
I can't think of any better approach.
Edit:
I just thought of a wild solution.
textField.addFocusListener( new FocusAdapter()
{
public void focusLost(FocusEvent e)
{
if (e.getOppositeComponent() instanceof JRadioButton)
{
final JRadioButton radio = (JRadioButton)e.getOppositeComponent();
MouseListener ml = new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
System.out.println( radio.isSelected() );
radio.removeMouseListener(this);
}
};
radio.addMouseListener( ml );
}
else
System.out.println( radio.isSelected() );
}
});
Basically your processing code won't execute until the mouse has been released when you click on the radio button.

Categories