Swing add new Component - java

I need to add dynamicaly Components to JPanel, but if i make just add(Component) then component doesn't appears, if i make then JPanel.revalidate(); then it appears, but JPanel blinks, can I make it more fine, without blinking?
Hm, i have found solution,just after add(component); i have write component.repaint(); and it works, but now there is another Problem with Window resizing, if i resize window then all my added components disapeard!!!

This is basic, but you should make sure each component is
1) added from the EDT (see SwingUtilities.invokeLater())
2) added only once per instance

Might be a better idea to add the components on initialization and hide them, making them visible when needed.
Use the method Component.setVisible(boolean b) so show and hide components.
Edit:
I just tried a simple test class where I added random components to the main JFrame and it worked fine.
Try calling JFrame.pack() following JPanel.revalidate().
If this does not make a difference could you post some of your code where you add the dynamic components?
Another Edit:
Make your main component Implement the ComponentListener interface and implement the componentResized(ComponentEvent e) method to call JFrame.pack().

if you add a new component you have to call revalidate.
Example:
panel.add(new JButton(...), ...);
panel.revalidate();
Make sure you're calling this from within the EDT.
If it still flickers have a look at panel.setDoubleBuffered.
Hope that helps, even though example code from your side would be nice to actually see the effect you are describing.

Related

.pack() causes the components to be in the wrong place but works after window resize

I am creating a game in java using Swing.
I am using
mainJFrame.setExtendedState(mainJFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
on my JFrame to start it as a maximized window.
After this I am using
mainJFrame.pack();
to be able to get the correct x & y coordinates of components in the GUI. I need those coordinates since i'm painting custom images to the GUI. So far everything is fine.
When a user has passed a level, i rebuild the GUI to updated it to the new level settings and then i call pack() again.
When calling pack() the components are placed in the wrong place, slightly below where they are supposed to be.
However, manually resizing the window causes the components to go to the right place again.
I have tried calling mainJFrame.revalidate() and mainJFrame.repaint() after the pack() but this gives no effect.
If needed I can supply printscreens and code.
Thanks for your time.
Manually resizing the window validates the enclosing container and all of its subcomponents. To avoid the effect you describe, call setVisible() only after you have added components and invoked pack(). More related suggestions may be found here. If the problem persists, please edit your question to include an mcve that exhibits the problem.

Why do I have to use setvisible() on my JFrame when I change components?

So for the sake of simplicity I set up a little test code just to figure out this problem. Basically I have a JFrame and I added 'this' to it (I just extended my main class from JComponent to save time). this component fills in a red background. Then I have it sleep for 2 seconds and then type this.
f.remove(this);
thing t = new thing();
f.add(t);
f.setVisible(true);
f being my JFrame object and 'thing' is just another class extending JComponent that paints a blue background..
when I comment out setvisible() it no longer changes to blue.. I've tried using t.setVisible(true) but it seems I have to make the frame visible again, not the component
does anyone know why I have to call that... or if there is another way to change components within a single frame?
"Basically I have a JFrame and I added 'this' to it (I just extended my main class from JComponent to save time). this component fills in a red background. Then I have it sleep for 2 seconds and then type this."
Don't "sleep" your program. Instead use a java.swing.Timer to perform repeated tasks on the GUI or for animation. See more at How to Use Swing Timers. You can see a bunch of Timer examples here and here and here and here and here
Instead of trying to add and remove panels look into using a CardLayout which allows you to switch between views. It will help you avoid a lot of problems that come with with adding and removing components/containers. See more at How to Use CardLayout. Also see a simple example here.
To answer your main question, whenever you remove and add components from your frame, you need to revalidate() it. setVisible() takes care of that for you.
Side Note
Seems like a lot adding an removing background panels) just to change the background. Why not just setBackround()? You can switch colors with the use of the Timer
Calling setVisible(true) makes the frame appear onscreen. Sometimes you might see the show method used instead. The two usages are equivalent, but we use setVisible(true) for consistency's sake.

Difference between JScrollPane.setviewportview vs JScrollPane.add

I faced this new thing today, and I didn't know why. When I want to show something in panel for example, I just add it to panel; but why I cannot add a table to scroll pane directly, and why I have to call the setviewportview() method? What does add() method do and what does setViewProtView() do?
Basically, you should not use JScrollPane#add.
JScrollPane has a single component already attached to it, a JViewport, this is what the JScrollPane uses to display any component added to the view port.
setViewportView is a convenience method for for JScrollPane#getViewport#setView
The basic concept comes down to the fact that from the scroll panes point of view, it will only show a single component, so add doesn't actually make any sense for it. The method is a consequence of extending from JComponent -> Container

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