Removing a button during actionperformed of that button - java

I was trying to figure out why my program freezes and I was able to replicate it with a small script so I can put it here. Basically, in this script When you clicked on button Test1, it is supposed to remove it and added new button Test2. The program freezes. Why? How can I over come this?
final JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(800, 600));
final JPanel panel = new JPanel();
final JButton bTest1 = new JButton("test1");
bTest1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
panel.remove(bTest1);
panel.add(new JButton("test2"));
}
});
panel.add(bTest1);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
Offcourse in the real program, on the button click, remove all the contents of the panel and re add a new set of components.
Looking for your help!

Offcourse in the real program, on the button click, remove all the contents of the panel and re add a new set of components.
Then you should probably be using a CardLayout. A CardLayout is designed to allow you to swap panels.
Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
The program freezes. Why? How can I over come this?
It doesn't freeze, its just that the panel isn't smart enough to repaint itself. It you resize the frame you will see the new button.
The problem is you remove the button and add a new button but the panel never repaints itself because the panel is not aware of the changes. You need to invoke the layout manager so the new button can be given a proper size.
The basic code for add/removing components on a visible GUI is:
panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint(); // sometimes needed

Action performed method of the JButton will be executed in AWT thread. When you remove the button from the container, that will launch events that should be executed as well in the same thread. So one is waiting for the other , and so the program freezes. For solving that situation use
SwingUtilities.invokeLater
method to execute the removing action of your button

Related

JLabel doesn't show up until you maximize my frame

I was looking for this situation, but apparently there is no other question about this, so, here I go.
I'm making a school project which requires that I make a JFrame and even though I had a horrible time with ActionEvents, I finally could make it work, so after I got some info in my JFrame which I need that shows in a JLabel an answer and, well, it does, the only thing is that nothing happens after I click my button, but it happens when I maximize or resize the window itself.
button1= new JButton("Add user");
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
user= input1.getText();
if(user.isEmpty()){
JOptionPane.showMessageDialog(null, "you have an error there!");
}
else {
output2 = new JLabel("thx for registering, "+user);
output2.setBounds(10,40,150,20);
panel.add(output2);
}
}
});
button1.setBounds(310,10,140,20);
panel.add(button1);
Don't use setBounds(). Swing was designed to be used with layout managers, so let the layout manger determine the size/location of a component. Read the Swing tutorial on Layout Managers for working examples to get you started.
When you add a component to a visible GUI the basic code should be:
panel.add(...);
panel.revalidate();
panel.repaint();
The revalidate() will invoke the layout manger to give the component a size/location. The repaint() makes sure all the components get painted.

JFrame doesn't update its content

I've been struggling to get my JFrame to repaint its content. I've tried using both the revaluate() and repaint() methods together after I add the new components into the JFrame but I'm not seeing the frame change.
Here's the simple GUI of a minesweeper game I'm trying to make.
When a user clicks on either of the top 3 buttons, they enter the following code block
private void drawGrid()
{
removeAll();
setLayout(new GridLayout(2,1));
add(new JButton("button"));
setVisible(true);
revalidate();
repaint();
setVisible(false);
setVisible(true);
}
When clicking a button, the whole application turns white, but I can't see the new button I added. When I remove the two setVisible() method lines, then clicking a button definitely removes the components since I can't click on any of them now, but the 4 initial buttons are still visible. Removing the revalidate or repaint methods has no effect on the application.
What else can I try to get the application to refresh and display its new content.
Calling removeAll on a JFrame is dangerous and can produce unexpected results, another reason why it's discouraged to extend from or manage UI's directly on top level containers.
Start by using a JPanel as you base UI component, then use a CardLayout to manage switching between the views.
Separate each view into it's own class (extending from JPanel or something simular) for easier management
Maybe it would work better if you used this
easyBtn.setVisible( false );
medBtn.setVisible( false );
hardBtn.setVisible( false );
customBtn.setVisible( false );
newBtn.setVisible( true );
If that does not work, try putting it into a SwingWorker.

Remove Focus from JTextfields

I have a JDialog with some JTextfields, and I want to remove the focus from the first textfield when I open the Dialog.
I tried .removeFocus(), but then I can't use focus anymore. I just want to remove it, so when I open the dialog no textfield is selected.
From How to use the focus subsystem we get the following:
If you want to ensure that a particular component gains the focus the first time a window is activated, you can call the requestFocusInWindow method on the component after the component has been realized, but before the frame is displayed. The following sample code shows how this operation can be done:
//...Where initialization occurs...
JFrame frame = new JFrame("Test");
JPanel panel = new JPanel(new BorderLayout());
//...Create a variety of components here...
//Create the component that will have the initial focus.
JButton button = new JButton("I am first");
panel.add(button);
frame.getContentPane().add(panel); //Add it to the panel
frame.pack(); //Realize the components.
//This button will have the initial focus.
button.requestFocusInWindow();
frame.setVisible(true); //Display the window.
Call requestFocus() on the control you want the focus. You could for example focus the default button of the dialog or something similar. From the How to Use the Focus Subsystem:
If you want to ensure that a particular component gains the focus the first time a window is activated, you can call the requestFocusInWindow method on the component after the component has been realized, but before the frame is displayed. The following sample code shows how this operation can be done:

Adding JButton dynamically to the JPanel not working with Netbeans

I created a JFrame Class with Netbeans 7.3 and added two panels from the palette.
I have added a button in the first panel on the click of which I want to add a new button in the second panel(topoPane).
Below is the button click event that I have written for the same. But, the button is not getting added to the panel even when the event is getting called.
Please tell me what's wrong in it.
private void jButton1MouseClicked(java.awt.event.MouseEvent evt)
{
// TODO add your handling code here:
System.out.println("Creating the Button");
JButton but = new JButton();
but.setBackground(Color.red);
but.setText("New Button");
but.setBounds(500, 500, 500, 500);
topoPane.add(but);
topoPane.revalidate();
}
From your use of setBounds, it is obvious that you are using a null layout. Because of this you need to call repaint() as containers with no layout do not automatically repaint added components on revalidate.
Apart from the fact that calling repaint is good practice, layout managers can remove the need to make this call along with manage the sizing and positioning of components. This makes it a good reason to use a layout manager.

How do I make so when I click my checkbox, a separate and editable frame opens?

I am currently working with Java. I have made checkboxes and I would like to know how to make it so when the checkbox is clicked it opens a separate frame that can be modified and edited for my needs. I've heard that an array of frames/components would work. Any help/solutions would be appreciated.
If I understood your question you must implement a listener for your checkbox.
And in the body of that listener, there should be something like this:
//1. Create the frame.
JFrame frame = new JFrame("FrameDemo");
//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//3. Create components and put them in the frame.
//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//4. Size the frame.
frame.pack();
//5. Show it.
frame.setVisible(true);
The first and 5th points are the most important.
If you dont know how to create and register listener for checkbox, try to visit these sites:
http://examples.javacodegeeks.com/desktop-java/awt/event/checkbox-listener-example/
http://docs.oracle.com/javase/tutorial/uiswing/components/button.html
I hope that this advice help you.

Categories

Resources