Adding JPanel onto another JPanel after button click - java

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

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

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.

how to start, developing swing based application with few panels with next buttons for each

I'm new to java.I'm creating a swing based UI. I've created 2 frames, each one in separate .java file inside same package.
These two frames represents 2 screens (panels) of application. When Next button in first frame is clicked, it should move to second frame.
When I checked, these two classes are having main method, I think it should be correct way for creating applications. there should be only one main method.
When Next is clicked, I'm trying to make setVisible(false) for main panel of first frame and setVisible(true) for main panel of second frame. But this cannot be done, since the panels within a class are private. Any resolution for the above problem?
As I'm beginner, Can somebody suggest me in how to start up with these kind of applications? what are the guidelines that need to be followed? And please help me in finding documentation related to starting up with the development of such applications.
After going through the answers, My comments are:
I used the following code to go to next panel from first panel, but didn't worked.
private void gotoNextPanel(){
// jPanelFirstScreen.setVisible(false);
JPanelSecondScreen jpanelSecondScreen= new JPanelSecondScreen();
jpanelSecondScreen.setVisible(true);
UpgradeUtilityGUI upgradeUtilityGUI = new UpgradeUtilityGUI();
upgradeUtilityGUI.removeAll();
validate();
repaint();
// upgradeUtilityGUI.add(jpanelSecondScreen);
upgradeUtilityGUI.getContentPane().add(jpanelSecondScreen, "card2");
jpanelSecondScreen.setVisible(true);
validate();
repaint();
}
I'm using netbeans, and 've added two panels to the cardlayout of frame. And when I use the above code to change panels, Nothing is happening, the first panel is still appearing. Can somebody tell me, how to write code for moving from one panel to another when both the panels 've been added to cardlayout of jFrame ?
Use a CardLayout, as shown here (and one frame) as mentioned by others.
When Next is clicked, I'm trying to make setVisible(false) for main panel of first frame and setVisible(true) for main panel of second frame. But this cannot be done, since the panels within a class are private. Any resolution for the above problem?
Make the panels public access level and they will be available from other packages.
One problem in that code snippet is implied by the line:
UpgradeUtilityGUI upgradeUtilityGUI = new UpgradeUtilityGUI();
It goes out of scope before ever being added to a container. Also, their should be no need to remove anything when adding a new card to the layout, and no need to call repaint().
If your application is as simple as having only two panels you shouldn't create two JFrames. You should create a JFrame with two JPanel each of them contains the neccessary information for you. If you are ready with your first panel you can call setVisible(false) on it, and call setVisible(true) on the 2nd frame. It is the one of the most easy-to-understand solution.
But, it only depends on you if it is good for you or you would like to use some more detailed solution.
Don't use two or more JFrames, nor with separated and compiled Jar files, this is road to the hell, better would be look at CardLayout,
What you should do is have a single JFrame for the application, then you add and remove JPanels as you want to move between screens.
Each of your JPanels should basically have the following...
1. A JButton called "Next"
2. A ButtonListener for each button, that tells the JFrame to load panel2, panel3, etc.
As part of the ButtonListener, you basically just want to call something like JFrame.removeAll() to remove the existing panel, then JFrame.add(JPanel) to add the next panel.
By having 1 JFrame, you also only have 1 main() method.

How do I dynamically add Panels to other panels at runtime in Java?

I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this.
When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically.
I've been trying to use JPanels like usercontrols in C#. I created a JPanel form called BlurbEditor. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event.
Here is the code that I thought would work:
mainPanel.add(new BlurbEditor());
mainPanel.revalidate();
//I've also tried all possible combinations of these too
//mainPanel.repaint();
//mainPanel.validate();
This unfortunately is not working. What am I doing wrong?
I figured it out. The comments under the accepted answer here explain it:
Dynamically added JTable not displaying
Basically I just added the following before the mainPanel.add()
mainPanel.setLayout(new java.awt.BorderLayout());
Swing/AWT components generally have to have a layout before you add things to them - otherwise the UI won't know where to place the subcomponents.
BFreeman has suggested BorderLayout which is one of the easiest ones to use and allows you to 'glue' things to the top, bottom, left, right or center of the parent.
There are others such as FlowLayout which is like a textarea - it adds components left-to-right at the top of the parent and wraps onto a new row when it gets to the end.
The GridBagLayout which has always been notorious for being impossible to figure out, but does give you nearly all the control you would need. A bit like those HTML tables we used to see with bizarre combinations of rowspan, colspan, width and height attributes - which never seemed to look quite how you wanted them.
I was dealing with similar issue, I wanted to change the panel contained in a panel on runtime
After some testing, retesting and a lot of failing my pseudo-algorithm is this:
parentPanel : contains the panel we want to remove
childPanel : panel we want to switch
parentPanelLayout : the layout of parentPanel
editParentLayout() : builds parentPanel with different childPanel and NEW parentPanelLayout every time
parentPanel.remove(childPanel);
editParentLayout();
parentPanel.revalidate();
parentPanel.repaint();
As with all swing code, don't forget to call any gui update within event dispatch thread. See this for why you must do updates like this
// Do long running calculations and other stuff outside the event dispatch thread
while (! finished )
calculate();
SwingUtilities.invokeLater(new Runnable(){
public void run() {
// update gui here
}
}
mainPanel.add(new BlurbEditor());
mainPanel.validate();
mainPanel.repaint();
Try mainPanel.invalidate() and then if necessary, mainPanel.validate(). It also might be worth checking that you're doing this all in the event dispatch thread, otherwise your results will be spotty and (generally) non-deterministic.

Categories

Resources