Adding JButton dynamically to the JPanel not working with Netbeans - java

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.

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.

Removing a button during actionperformed of that button

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

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.

Java Swing: Add a component by code in NetBeans

I'm using NetBeans, and I've a JFrame where I added a JPanel to it using the NetBeans's palette.
I want to add a JRadioButton manually to that JPanel, so this is the code I tried in the constructor :
ButtonGroup group = new ButtonGroup();
JRadioButton btn1 = new JRadioButton("btn1 ");
JPanel1.add(btn1);
But when I run that JFrame I don't see that JRadioButton anywhere, but it works when I add it using the NetBens's palette.
How can I solve this problem ?
Make sure that the JPanel is not using GroupLayout. Most any other layout would work well, but likely for the moment, JPanel's default FlowLayout will work best.
Be sure to call revalidate() and repaint() on the JPanel after adding a component, if you are adding the component after the GUI has been rendered, such as on a button push.
If still having problems, show your code.
General advice: avoid using code generation utilities until after you understand the underpinnings of the GUI library, here Swing. You won't regret doing this.
The problem with NetBeans GUI Builder is that it initializes everything for you, where you can't alter the code unless you open the file on some other platform. In which case you have the risk of totally messing up the code.
What I can suggest is to maybe attempt something like this
Create an empty JPanel with a preferred size that you set in the property pane. You may also want to set the layout also, depending on your requirements.
After the initComponent() then add the JRadioButtons
public MyGUI(){
initComponents();
ButtonGroup group = new ButtonGroup();
JRadioButton btn1 = new JRadioButton("btn1 ");
jPanel1.add(btn1);
jpanel1.revalidate(); // as #Hovercraft Full Of Eels suggested
jPanel1.repaint();
}

JTabbedPane doesn't work correctly

public void tabbedPane(){
JPanel tab1 = new JPanel();
JButton btn = new JButton("Buton - 1");
btn.setPreferredSize(new Dimension(50, 20));
btn.setLocation(0, 10);
tab1.add(btn);
JTabbedPane tabPanel = new JTabbedPane();
tabPanel.addTab("tab1", null, tab1);
tabPanel.addTab("tab2", tab1);
tabPanel.addTab("tab3", btn);
tabPanel.setPreferredSize(new Dimension(450, 150));
tabPanel.setLocation(50, 0);
mainPanel.add(tabPanel);//Main panel on frame
}
When I run my application, I see only tab2 and tab3 pane, and I have many issues:
tabPanel.setLocation doesn't work
tabPanel.addTab("tab1" ...) doesn't work
btn.setPreferredSize(new Dimension(50, 20)); when I
click "tab2" it works correctly, however when I click "tab3" it doesn't change button
size.. why?
and i use null layout
tabPanel.setLocation doesn't work
Don't use setLocation(...) but instead use nested components and layout managers to achieve a pleasing and easy to maintain GUI layout.
tabPanel.addTab("tab1" ...) doesn't work
With Swing, you can only add a component to one container, that's it. The component will only show up in the last container that it was added to.
btn.setPreferredSize(new Dimension(50, 20)); when I click "tab2" it works correctly, however when I click "tab3" it doesn't change button size.. why?
Again, you will want to study the layout managers
and i use null layout
You almost never want to do this as this will make your application not look correct on any platform but your own and will make it very very difficult to maintain and upgrade. It is much better to use the layout managers and let them do the heavy lifting of laying out and sizing components for you.
What is your objective with this?
A JTabbedPane is used to organize views, I see you're trying to add a JPanel as a first tab, this is the 'main goal' of the JTabbedPanes.
tabPanel.addTab("Tab 1", tab1);
Try to add the tab like this, you're passing a 'null' value as the icon, which must not affect at all, but if you're not using an icon, then just add the panel as a tab with the intended name.
On second adding, you're adding again the same component (tab1).
On third adding, you're trying to add a component already on a container (tab1). This will make this component to appear only in the last container you add it to. Besides, component is a JButton. I cannot see the goal of a JButton as a tab.
For the setLocation(x, y) issue, check the layout you're using on the container.
Again, I think the main issue here is that you're not correctly approaching your problem, or you're not using the required tools.

Categories

Resources