Java Swing: Add a component by code in NetBeans - java

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();
}

Related

How to refresh a JPanel at runtime?

I have found that there are many similar topics here, but my problem is something more complicated.
Background of my problem:-
I have a JFrame called Main. On this JFrame I have two buttons and one JPanel called WorkingPanel. Then I have another JPanel(called PlayerPanel) but this one is a seprate file (as a class).
Now I want that when I click a button, it should change WorkingPanel to PlayerPanel. I have wrote following code.
private void MenuButtonPlayerViewMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
WorkingPanel = new PlayerPanel();
System.out.println(WorkingPanel.getName());
WorkingPanel.revalidate();
WorkingPanel.repaint();
WorkingPanel.setVisible(true);
Window.revalidate();
Window.repaint();
}
Please guide me, Thanks.
I have found that there are many similar topics here, but my problem is something more complicated.
On the contrary, your description is of a rather basic problem that is very easily solved by using a CardLayout. I suggest that you do this now. If you had it in place your method could be as simple as:
private void MenuButtonPlayerViewMouseClicked(java.awt.event.MouseEvent evt) {
cardLayout.show(cardPanel, WORKING_PANEL);
}
where cardLayout is your CardLayout variable, cardPanel is the JPanel that displays the "cards" that displays the swapping JPanels, and WORKING_PANEL is a String constant that you used when you added your WorkingPanel instance to the cardPanel.
Point 2:
Don't use a MouseListener on a JButton as it won't behave correctly. For instance, if you disable the button via setEnabled(true) the button won't truly be disabled. Instead use an ActionListener with JButtons as the tutorials will show you. That is what they are for.
Edit
For examples of CardLayout-using GUI's, please check out:
getting Jcomponent from other class changes frame size
Java CardLayout Main Menu Problem
Change size of JPanel using CardLayout
Java CardLayout JPanel moves up, when second JPanel added
Java swing; How to toggle panel's visibility?
Clear components of JFrame and add new componets on the same JFrame
gui multiple frames switch
JLabel displaying countdown, java
This one is unusual in that it uses a CardLayout and has one panel fading into the other panel:
CardLayout showing two panels, flashing.
You could use CardLayout instead of that approach. You will be able to switch between different panels very easy and efficiently. It's also wort of mentioning that use of CardLayout is less verbose approach.
Use a CardLayout, containing your two panels, but only showing one at a time. The CardLayout is documented, with examples, in the Swing tutorial.

How to add/remove a JPanel from a JFrame

I'm trying to set a variable to be a new JPanel and then add it once a button is pressed, but it is not working and I don't know why.
code:
private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {
remove(scriptPanel);
scriptPanel = new GemPanel();
add(scriptPanel);
validate();
repaint();
pack();
}
GemPanel is just a JPanel class I made. When I press the next button, it re-sizes the frame to be as small as possible and nothing actually happens. If I re-size it to normal, the original scriptPanel is still there.
What gives?
Instead of trying to remove and add entire panels, a better, less problem prone approach would be to use a CardLayout that will allow to swap views. You can see more at How to use Cardlayout
Also, by the looks of your method signature, it seems you're using the Netbeans builder too. You may also want to take a look at How to Use CardLayout with Netbeans Gui Builder

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.

Java Swing Components does not have correct Size when added to JPanel

It's my first Post here, so forgive me please if i'm doing something wrong.
My Problem is:
I am trying to add Components to a JPanel with defined values for Size etc.
But when i add them to the Panel, they do absolutely not have the Size and Location they should have.
For example:
public class Console extends JFrame {
private JPanel mainPanel = new JPanel();
private JTextArea textField = new JTextArea();
private JTextArea textField2 = new JTextArea();
public Console() {
this.setSize(500,300);
this.mainPanel.setSize(this.getWidth(),this.getHeight());
this.textField.setEditable(false);
this.textField.setSize(this.mainPanel.getWidth(), 100);
this.textField.setPreferredSize(new Dimension(this.mainPanel.getWidth(),this.mainPanel.getHeight()));
this.textField.setLocation(0, 0);
this.textField.setText("some text");
this.textField.setVisible(true);
this.textField2.setSize(this.mainPanel.getWidth(),200);
this.textField2.setPreferredSize(new Dimension(this.getWidth(),this.getHeight()));
this.textField2.setLocation(0,this.mainPanel.getHeight()-this.textField.getHeight());
this.textField2.setText("blabla");
this.textField2.setVisible(true);
this.mainPanel.add(textField);
this.mainPanel.add(textField2);
this.mainPanel.setVisible(true);
this.add(this.mainPanel);
// I know you should not call setVisible() in the Constructor, just for making Code more simple here.
this.setVisible(true);
}
}
When i start the Application, both JTextArea's are really small and somewhere in the middle (not as set above) while the mainPanel is correct.I tried to call setSize() and setPreferredSize() in different Places in the Code, but it didn't work. I know it is better to use a LayoutManager for doing this as far as i heard but to be honest, i do not get how to use it correctly. I checked it on Oracle Doc's but i would appreciate it if someone could post a clean Solution for this, Thanks in Advance.
You need to set a proper Layout for your Container. You setLayout for a Container like JFrame, JPanel and so on. You don't add other components to layout, but to a container. Then it would layout them accordingly. It is how it works.
With proper layout you would not need to call setLocation(). Also setVisible(true) is excessive, because true is default values for those components in your code.
Better not to extend JFrame, extend JPanel instead and add it to JFrame.
Please, learn about EDT and SwingUtilities.invoketLater() you need to use it.
Also you can save some bytes, not typing this. all the time.
it's all about the layout Swing layout.
For your JTextArea problem, use:
JTextArea j=new JTextArea();
j.setColumns(20);
j.setRows(5);
Change the values of setColumns() and setRows() to vary the size; + the suggestion given about Layout Managers.
Hope this works ;)
try using the absolute layout of the jpanel.

Adding JPanel onto another JPanel after button click

I'm using Netbeans IDE to make a gui application. I have a JFrame with a JPanel inside it. After a button click I want to display a different JPanel inside the first. The other JPanel is in a different file. How would I go about doing this? If this is not practical I don't mind replacing the first JPanel with the second one.
I've tried the following but it doesn't seem to work. I'm new to Java and Gui programming so I would appreciate any help I can get.
private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {
JPanel2 jPanel2 = new JPanel2();
JPanel1.add(jPanel2);
}
See the javadoc of the Container#add method:
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.
So it is not sufficient to add the panel, but you must also validate the hierarchy again, e.g. by calling
JPanel1.validate();
JPanel1.repaint();
Using a CardLayout as #Andrew suggested in his answer is probably a better alternative then manually replacing panels
Two side-notes:
Learn and respect Java naming conventions (e.g. instances of a class start with a lowercase). so your JPanel1.add call would become jPanel1.add
There is in most cases no need to extend the Jxxx Swing classes. Looking at your class names JPanel1 and JPanel2 you are exactly doing that. It is better to use the available API to customize those classes then to extend them.
You will also have to add the following code such as your changes to take effect:
jPanel1.validate();
jPanel1.repaint();
Use a CardLayout, as shown here.
newPanel obj = new newPanel ();
setLayout(new BorderLayout());
add(obj ,BorderLayout.EAST ,1);//3rd argument is index
repaint();
revalidate();

Categories

Resources