I am trying something very basic:
I have a list of 5 buttons. They are in a FlowLayout and the general idea should be that once I click one it should disappear and the others should reorder themselves accordingly.
Now, if I call setVisible(false) the button becomes invisible, but it still occupies it's space in the Layoutmanager.
Is there any way to keep the Button in the JPanel while hiding it so it doesn't get picked up by Layout?
Update:: Thanks for all the answers, the problem with removing the buttons is that the order is important. The problem I was trying to solve was a find as you type szenario where a very long list of buttons gets filtered down to only the ones matching the characters entered so users can easily click them. Since users can delete characters from the search field ordering is important and buttons have to pop back in once they match again.
Works fine for me.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FlowLayoutInvisible extends JFrame
implements ActionListener
{
JPanel north;
int i;
public FlowLayoutInvisible()
{
north = new JPanel();
for (int i = 0; i < 5; i++)
{
JButton button = new JButton("North - " + i);
button.addActionListener(this);
north.add(button);
}
getContentPane().add(north, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e)
{
Component c = (Component)e.getSource();
c.setVisible(false);
((JPanel)c.getParent()).revalidate();
}
public static void main(String[] args)
{
FlowLayoutInvisible frame = new FlowLayoutInvisible();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
If you need more help post your SSCCE.
Update: I don't know if the revalidate() is required. I seemed to have a problem once but now I can't duplicate the problem.
Just remove it:
panel.remove( button );
What's wrong with this option?
Layout managers are thought precisely to avoid having the "user" to make tricks in order to have each component it the right place ( although it seems to provoke the opposite effect )
Removing the button from the panel will have the effect of laying out again all the remaining components. That's why it's name is "Layout manager" it manages to layout the components for you.
I see two possibilities:
Write your own layout manager that listens for changes to its children's visible property - shouldn't be too hard, you can probably subclass FlowLayout to do it.
actually remove the clicked-button from the panel and, if necessary, re-add it later.
You could override each button's getPreferredSize() methods (and possibly getMinimumSize() as well to return 0,0 when the component is invisible; and you need to call, I think, invalidate() (or revalidate or validate, I can never keep them straight) on the container.
Related
Alright I'm relatively new to programming and it may be just something simple that I'm missing but the other threads related to this topic the poster didn't give adequate information relative to their issue for others to provide quality answers so I will give it a shot.
public BenchUI(JFrame j){
jf = j;
init();
add(mainPanel);
topPanelButtons();
selectedCustomer();
rentalOptions();
clientListBox();
}
At this point i can point out that everything works perfectly until I add the clientListBox() method. (below)
public void clientListBox(){
clientList = new JComboBox(moo);
clientList.setPreferredSize(new Dimension(460,30));
gbc.gridx = 0;
gbc.gridy = 0;
leftSide.add(clientList,gbc);
}
i can comment it out and get my whole GUI back working perfectly but without a JComboBox.
moo is String [] moo = {"Fish","Goat", "Monkey"};
a dummy string just for testing purposes and initialized at the start.
So any idea why my GUI completely disappears when I place in the clientList?
If anything else is necessary I'll be watching this thread and can provide additional information.
As a side note I keep getting warnings for "Raw Types" but it works without specifiying, could I potentially run into trouble by not specifying my JComboBox?
EDIT:
ok I believe I've duplicated whatever the issue is in this code
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
public class main {
public static void main(String[] args){
JFrame jf = new JFrame();
jf.setExtendedState(JFrame.MAXIMIZED_BOTH);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setResizable(false);
BenchUI bu = new BenchUI(jf);
jf.add(bu);
}
}
public class BenchUI extends JPanel{
JPanel one;
JFrame jf;
JComboBox<String> clientList;
String[] moo = {"Goat", "Fish", "Donkey"};
public BenchUI(JFrame j){
jf = j;
one = new JPanel(new GridBagLayout());
one.setBackground(Color.blue);
one.setPreferredSize(new Dimension(300,300));
clientList = new JComboBox<String>(moo);
one.add(clientList);
add(one);
}
}
with the clientList stuff commented out I get my silly little blue panel and once it is added I lose the blue panel and the combobox doesnt show up as well...betting on this is a facepalm issue at this point >.<
EDIT: to include the main class.
EDIT: took out the comment marks for the JComboBox constructor and implementer
Your posted sort of sscce-like (not a real SSCCE by the way since we can't run it) code doesn't add any such as the JComboBox to the JPanel and adds no components such as the current JPanel to the JFrame.
public class BenchUI extends JPanel{
JPanel one;
JFrame jf;
JComboBox<String> clientList;
String[] moo = {"Goat", "Fish", "Donkey"};
public BenchUI(JFrame j){
jf = j;
one = new JPanel(new GridBagLayout());
one.setBackground(Color.blue);
one.setPreferredSize(new Dimension(300,300));
//clientList = new JComboBox<String>(moo);
//one.add(clientList);
add(one);
}
}
and so it makes sense that none of the components will show up on any JFrame. You will want to read the Swing tutorials on how to add components to other components (or containers) and how to create and show a JFrame. Have a look at How to Use Swing Components.
Edit
Your latest code now does in fact add the BenchUI JPanel to the JFrame, but still you add no components to the BenchUI JPanel, and in fact you don't even construct your JComboBox but only create a JComboBox variable. Again, I strongly urge you to read the Swing tutorials which I've linked to above as well as the general Java tutorials.
Edit 2
Some general advice:
If you want to add a component to a GUI you must first create the component object. You are declaring your clientList JComboBox, but you never create the object.
Then you must add the component object to a container that eventually will be part of the hierarchy leading to a top level window such as a JFrame, JDialog, JApplet and such. You never add a clientList object to the GUI.
You should add your components to the top level window before calling pack() on the top level window -- which tells all the layout managers to lay out all the components they hold.
You should then call setVisible(true). One problem with your code (other than not creating important components and not adding them to the GUI!) is that you're calling setVisible(true) on your JFrame way too early before adding anything to the GUI.
Read the Swing tutorial, but especially the one on using layout managers and on adding components to a top level window.
Edit 3
OK, now you're creating your JComboBox, but you still are adding all components to your JFrame after setting it visible. Please re-check my 3rd and 4th bullets in the bullet list above.
I am a beginner into Java and OOPS in general. Am studyin Head First Java to start, and studying GUI and Swing concepts in it.
The below code is just for understanding purposes.
On running the code, The frame window is displayed with Button, and when I expand it I can see Radio Button too.
Issues-
Button works till the window size is not more than the button size . As soon as I increase the window size even slightly more than button's dimensions, then the button is displayed only when cursor is on it.
I am changing window size using mouse.
Also even if I set Frame size to be more than button. say frame.setSize(800,800); then the button covers whole contentPane. and still behaves same way on resizing.
And the button responds to clicking on mouse, irrespective of where I click in the contentPane. It should respond only when i click directly on the button.
Please inform me why it is behaving this way.
And if possible,corrections in code or additions to correct this.
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
public class Test1 implements ActionListener {
JFrame frame = new JFrame("Frame");
JButton button = new JButton("Button!");
JRadioButton radio = new JRadioButton("VideoKilledTheRadioStar!",true);
int j=0;
public static void main(String[] args) {
Test1 t = new Test1();
t.method1();
}
public void method1()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setSize(100,100);
button.setBackground(Color.ORANGE);
frame.add(button);
frame.setSize(100,100);
frame.setVisible(true);
button.addActionListener(this);
frame.getContentPane().add(radio);
radio.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{j++;
button.setText("clicked .. " + j);
if(button.getBackground()==Color.ORANGE)
button.setBackground(Color.BLUE);
else
button.setBackground(Color.ORANGE);
}
}
P.S I did not know which segment of code is important or more relevant to this question, so I have put complete code.
You are trying to add the JButton button and JRadioButton objects in the default layout(BorderLayout) of the JFrame.
Whenevery you add a component to JFrame having BorderLayout the components goes in the Middle Section and BorderLayout center section has tendency to occupy the complete space, so to position elements properly you will need to specify the location as well as set the PreferredSize of the component.
frame.add(radio, BorderLayout.SOUTH);
component.setPreferredSize(Dimension);
You are adding the JButton button and the JRadioButton both in the BorderLayout.CENTER location so only one is being displayed. Components at this location will be sized in the X and Y axis.
The JButton only displays when the cursor is over it due to the fact that it has its own MouseListener used for painting.
Also, the statements
frame.add(myComponent);
and
frame.getContentPane().add(myComponent);
both add the component to the frame's ContentPane & are equivalent but the first is chosen for convenience.
Note that components cannot co-exist in the same position in a BorderLayout. You could place the button at the BorderLayout.SOUTH position (& add directly to the frame):
frame.add(radio, BorderLayout.SOUTH);
BorderLayout disregards any preferred sizes for components so you would have to use a different layout manager such as BoxLayout to maintain a fixed size JButton.
See more about Layout Managers
By input elements I mean things like JSpinners and JComboxBoxes. My glasspane is passed a JPanel containing JSpinners, JComboBoxes and for the most part, JLabels. The glasspane has a MouseListener attached. The surprising thing is that mouseEntered is called upon the mouse cursor leaving the input elements and hovering over the other parts or empty space of the JPanel! Is this normal behaviour? How can I get the input elements to be considered part of the JPanel for Glasspane purposes?
Here is a screenshot of my UI with its input elements and jLabels.
Here is an example piece of Code:
import javax.swing.*;
public class DialogTest {
public DialogTest() {
JPanel dialogPanel = new JPanel();
SpinnerModel edgeModel = new SpinnerNumberModel(1, 1, 9, 1);
JSpinner edgeSpn = new JSpinner(edgeModel);
dialogPanel.add(edgeSpn);
JDialog initialDialog = new JDialog(new JFrame(), "Test", true);
initialDialog.setContentPane(dialogPanel);
initialDialog.pack();
glass = new GlassComponent(dialogPanel);
initialDialog.setGlassPane(glass);
glass.setOpaque(false);
glass.setVisible(true);
initialDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
initialDialog.setVisible(true);
}
}
public class GlassComponent implements MouseListener {
JPanel c;
public GlassComponent(JPanel c) {
this.c = c;
this.c.addMouseListener(this);
}
...
public mouseEntered(MouseEvent e) {
System.out.println("Entered JPanel");
}
}
By way of explanation, my goal is to eventually use the GlassPane to block input for those elements marked with the prohibition sign. However, given that the mouseListener assigned to the dialogPanel is seemingly generating new events upon leaving the input elements, I may have some difficulties achieving this.
You can forward mouse events to the underlying components, as shown in The Glass Pane demo's method, redispatchMouseEvent().
You appear to be using glasspane in a way that I feel it shouldn't be used.
As far as I know, a glasspane typically shouldn't be holding components at all but rather cover over the top-level window and then can act as a gate-keeper for the components that are below it, all held by the top level window's contentPane.
you can use GlassPane for overlay required Container or JComponent by #camickr, or my questions based on his code here or here,
another suggestion could be use JLayer (required Java7 for Java6 is there JXLayer)
After manually swapping components via add and remove, I invoke validate() on the container. According to the documentation,
The validate method is used to cause a container to lay out its
subcomponents again. It should be invoked when this container's
subcomponents are modified (added to or removed from the container, or
layout-related information changed) after the container has been
displayed.
The phrase "lay out its subcomponents again" makes me think that the container will resize itself accordingly, but it doesn't. Instead, after invoking validate(), I need to invoke pack() as well in order to view all its subcomponents.
Why is this? Am I doing something wrong?
I think that you answered your question by yourself, hope help you this demo
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class AddComponentsAtRuntime {
private JFrame f;
private JPanel panel;
private JCheckBox checkValidate, checkReValidate, checkRepaint, checkPack;
public AddComponentsAtRuntime() {
JButton b = new JButton();
b.setBackground(Color.red);
b.setBorder(new LineBorder(Color.black, 2));
b.setPreferredSize(new Dimension(600, 10));
panel = new JPanel(new GridLayout(0, 1));
panel.add(b);
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel, "Center");
f.add(getCheckBoxPanel(), "South");
f.setLocation(200, 200);
f.pack();
f.setVisible(true);
}
private JPanel getCheckBoxPanel() {
checkValidate = new JCheckBox("validate");
checkValidate.setSelected(false);
checkReValidate = new JCheckBox("revalidate");
checkReValidate.setSelected(false);
checkRepaint = new JCheckBox("repaint");
checkRepaint.setSelected(false);
checkPack = new JCheckBox("pack");
checkPack.setSelected(false);
JButton addComp = new JButton("Add New One");
addComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton b = new JButton();
b.setBackground(Color.red);
b.setBorder(new LineBorder(Color.black, 2));
b.setPreferredSize(new Dimension(600, 10));
panel.add(b);
makeChange();
System.out.println(" Components Count after Adds :" + panel.getComponentCount());
}
});
JButton removeComp = new JButton("Remove One");
removeComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int count = panel.getComponentCount();
if (count > 0) {
panel.remove(0);
}
makeChange();
System.out.println(" Components Count after Removes :" + panel.getComponentCount());
}
});
JPanel panel2 = new JPanel();
panel2.add(checkValidate);
panel2.add(checkReValidate);
panel2.add(checkRepaint);
panel2.add(checkPack);
panel2.add(addComp);
panel2.add(removeComp);
return panel2;
}
private void makeChange() {
if (checkValidate.isSelected()) {
panel.validate();
}
if (checkReValidate.isSelected()) {
panel.revalidate();
}
if (checkRepaint.isSelected()) {
panel.repaint();
}
if (checkPack.isSelected()) {
f.pack();
}
}
public static void main(String[] args) {
AddComponentsAtRuntime makingChanges = new AddComponentsAtRuntime();
}
}
(may be due this ambiguity the description is changed in latest javaDoc )
JavaDoc 7 is NOT saying,
The validate method is used to cause a container to lay out its subcomponents again..
so its only laying the components, whereas you need a pack() again.
Note that pack() clearly says,
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.
The fundamental, yet subtle assumption at play here: layout and size are directly related, 1-to-1. This is not the case, and is a common assumption in Swing programming. Size is the result of layout and size constraints.
Layout is:
Within the space constraints you've specified
And given the components I have to fit within that space
Position those components in relation to one another given the specified strategy (BoxLayout, BorderLayout, etc.)
If the LayoutManager can fit the components you've given to it, without changing the overall size of the container, it will not alter the size of the container. A call to pack, on the other hand, is an explicit request to minimize the space being used. That's the basic reason you're seeing the results that you are.
Some things you might try:
Make sure you're setting a maximum size on your components/containers, which will force size constraints on components when re-doing the layout
Always call pack() as a habit
Try some of the suggestions regarding common layout issues
It's tricky with Swing, because you've got to understand the painting pipeline, the layout managers, and some details of the windowing system. When it comes to the Swing documentation (and all the methods and the several different ways there are to doing any one thing) I try to read the documentation with an "assume nothing" approach, meaning, "What's the minimum possible thing that this method's documentation implies that it might do," and unless you observe additional behavior, don't get tricked into thinking that it does more than that.
Finally, I would add that the job of LayoutManagers in general is not sizing of containers so much as it is to place components in some relation to one another, according to the layout strategy (this is discussed in additional detail here). The idea is that, with the proper LayoutManager, you specify a basic layout strategy, and as a result when you resize the window they LayoutManager will intelligently move the components around so that your UI continues to follow that overall strategy. In this way layouts are basically meant to be independent of the overall size of the space in which they work, so they try not to make assumptions about what space is available - instead they take the size they are given and try to do what makes sense. Unless you explicitly put size constraints on your components, you can't guarantee what size they will be.
That means, if the LayoutManager doesn't believe that it needs to resize something in order to make it fit its overall strategy, basically it won't resize it. A call to pack, on the other hand, is an explicit request to pack things together and remove extra space.
This code, when run, will make a window but not at the specified dimensions. What is wrong with it?
import javax.swing.*;
import java.awt.*;
public class Windowing {
void JFrame(){
JFrame frames = new JFrame("Total recall");
frames.setSize(1000,8000);
frames.setVisible(true);
frames.pack();
//Buttons push = new Buttons();
//((Buttons) push).buttons();
JTextField wager = new JTextField(1);
wager.setSize(100,200);
wager.setVisible(true);
wager.setLocation(100, 200);
frames.add(wager);
//frames.add(push);
}
}
You could remove the call to frames.pack(); it overrides the previously set frame size.
However, what you really want to do is remove the frames.setSize(1000,8000) and move frames.pack() down to the bottom of the method; that will ensure that the frame is big enough to display its contents but not too big to fit on the screen.
If you call pack before adding anything to the frame (like you are doing now), it will make the window extremely small; it's probably appearing near the upper left of your screen, but you won't notice it unless you know where to look.
It looks like you have a number of "opportunity areas" here.
To start, it seems like you set frame size to 1000x8000 because you didn't see any change right?
Secondly you call setVisible on the textField because you didn't see that either.
And finally you're setting the size of the textfield ( I guess because you're seeing it take the whole frame )
The problem here is that you have to invoke pack and setVisible at the end of the construction. Also, you have to learn how to use layout managers and frames.
Swing, is very powerful, but it is a bit hard to grasp at the beginning.
These two links will be helpful:
How to make frames
Using Layout Managers
I've changed your code and the result looks like this:
Here's the modified source code.
import javax.swing.*;
import java.awt.*;
public class Windowing {
public static void main( String [] args ) {
Windowing windowing = new Windowing();
windowing.showFrame();
}
void showFrame(){
JFrame frame = new JFrame("Total recall");
JButton push = new JButton("Push");
JTextField wager = new JTextField(15);
// Panels do have "FlowLayout"
JPanel panel = new JPanel();
panel.add(wager);
panel.add(push);
frame.add( panel );
frame.pack();
frame.setVisible(true);
}
}
Try to use setPreferredSize(Dimension) instead.