I have a JButton that is much wider than the text I put into it. I've researched this, and I keep finding the suggestion that I use Jbutton.setMargin(new Insets(0,0,0,0)); But this just does not seem to work. Also, setMaximumSize has no effect, although if I also set a minimum size, it does change the size of the button. But I don't want to set the size manually. I just want it to be less wide. What am I missing?
Here's my code to create the button:
plusminus = new JButton("+");
plusminus.setMargin(new Insets(0,0,0,0));
And here's what it looks like:
Thanks.
I'm manually making my GUI. In this case, the layout is GroupLayout
Then that may be part of your problem. Your JButton's size is constrained by the layout of the container that holds it. One possible solution if you absolutely need to use GroupLayout (which I hate by the way), is to place your JButton inside of a JPanel that uses FlowLayout or some other layout that allows flexible sized components, and place this JPanel into the container that's currently holding your button. Beware though if your button's bigger than the JPanel.
On a lark i tried negative left & right insets & unbelievably it worked. I did not then need to mess w/ the min/max/pref sizes. Btw my buttons are in one column of a JTable.
Related
I created a jframe, added a jbutton to it, and set the size of the jframe as 500,500 and size of the jbutton as 40,60. However, when I executed my program, my jbutton was covering the whole of my jframe. I
tried many things and looked into many sources, but I could not find a solution.
Please help me solve this.
You're not using a LayoutManager of any kind. The JButton will try to inherit the size of the parent container, as the default for a JFrame is BorderLayout (specifically, BorderLayout.CENTER). You could try using
button.setPreferredSize(x, y);
However I don't think this would be enough by itself. Call getContentPane on the Jframe, and set a layout on that contentPane container (I use FlowLayout a lot, as it respects setPreferredSize). Put your JButton inside that.
This is always a good starting point:
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
As the methods that you can call on a UI element vary depending on what LayoutManager you're assigning them to (be the child of). Sometimes it's setMinimumSize, sometimes it's setPreferredSize, and sometimes it's a combination.
I am setting a JLabel for the error messages in my program, so initially the label is empty label.setText(""), but when there is an error it should change to something like label.setText("Error, you have entered invalid data...").
If I use setSize(x,y) on the label, it forces other components to displace when error message takes place. But using setPreferredSize(Dimension(x,y))doesn't impact them.
Q1. Why is that?
Q2. What is the difference between setSize(x,y) and setPreferredSize(Dimension(x,y))
Q3. Does it have to do anything with layout?
Thank you in advance for explanation!
P.S. I am using GridBagLayout for positioning my components on the JPanel.
Don’t use the setSize method.
setSize is called by LayoutManagers, like GridBagLayout, to lay out child components. When you call setSize explicitly, you are fighting with the GridBagLayout. Eventually, GridBagLayout will undo your setSize call, when it calls setSize for its own purposes.
In other words, any call to setSize eventually will be wiped out by the parent layout.
setPreferredSize will not be wiped out. Most LayoutManagers, including GridBagLayout, do their best to respect a component’s preferred size.
However, you should not be calling setPreferredSize. Components already have a preferred size by default, and it is almost certainly better than any numbers you can come up with. For instance, a JLabel’s default preferred size is the size which is just large enough to accommodate its text, icon, and borders.
Computing a preferred size is harder than you might think. How many pixels does text use? How many pixels high is a 12 point font? 12 points is not 12 pixels. 12 points is 12⁄72 inch. How many pixels is that? It depends on the user’s monitor and graphics resolution. All of this is known to the Swing rendering system, and JLabel uses all of that information to determine its default preferred size. You should not try to reinvent all of that work, and you should not try to replace that work with something simpler, as it will be inadequate.
If you just let the JLabel keep its preferred size, GridBagLayout will do its best to accommodate that. If the window itself does not have room to display the JLabel’s new text, you probably should call the window’s pack() method after changing the text.
Update: This appears to be an XY problem—you really want a message that you can show and hide.
You want your layout to be big enough to accommodate your message text as soon as you create it. This is typically done with a CardLayout, which lets you place several components on top of each other, with only one of them visible at any given moment. Since you want to show no text at all, initially, you would add an empty JLabel as the first component in the CardLayout, so it is shown by default:
JLabel label = new JLabel("Error, you have entered invalid data...");
CardLayout messageLayout = new CardLayout();
JPanel messagePane = new JPanel(messageLayout);
messagePane.add(new JLabel(), "blank");
messagePane.add(label, "message");
// Do not add label directly to your user interface.
// Add messagePane instead.
mainWindow.add(messagePane);
// ...
// Show message
messageLayout.show(messagePane, "message");
// ...
// Hide message
messageLayout.show(messagePane, "blank");
"message" and "blank" are never seen by the user. They are just unique identifiers for each component (“card”) in the CardLayout. You can make them anything you want.
The setSize() function sets the size not based on any LayoutManager. Thats why you should always use setPrefferedSize() when working with a LayoutManager. setPrefferedSize() firstly tries to be conform with the LayoutManagers dimensions if then possible Java tries to set the size of the Label according to your setPrefferedSize() input.
So yes, it does have anything to do with layout. If possible, you should only use setPrefferedSize() as you are working with layout managers.
I have a JPanel identified by myPanel. I create a series of JButtons, and add() them to myPanel. At the end of my generating-and-adding loop, I call myPanel.validate(). The buttons show up.
The problem is the size of the panel is affected. No matter what Layout Manager I choose, the buttons are always added on the same line (even though there is more space beneath them).
I have tried setting myPanel's maximum size and setting its size after every add(). No matter what I do, after that validate(), the panel is blown up and my application's GUI is screwed.
Any ideas?
I create a series of JButtons, and add() them to myPanel... the buttons are always added on the same line (even though there is more space beneath them).
None of the default layout managers provide automatic wrapping. You need to specify how you want wrapping to occur. A GridLayout or a GridBagLayout can be used in these cases.
Or you can try the Wrap Layout which was written for this purpose.
i would firstly set a preferred size on the jpanel:
myPanel.setPreferredSize(new Dimension(X, Y));
this will tell your layout manager how to try to fit the contents within this dimension.
without seeing your source code, i can't add much more than that.
I'm trying to put two buttons inside a panel using Swing widgets. Inside the NetBeans IDE, my JSeparator border property is set to (No border) in the properties pane.
Nevertheless a line appears. This is not what I would expect from a separator object. Am I doing something wrong? Coming from a background in Delphi, and C# WinForms, I expect to find some oddities in Swing. But how exactly do you make a transparent gap of a particular size, between two buttons in a panel? Do I have to play with layouts and avoid the JSeparator?
Update: It should be trivial to do this with a layout and without any separator object. So how do you do that? I am looking into the NetBeans layout customizer and properties inspector and finding no way to do it. (Answer: Layouts with Insets, instead of separators.)
You should take a look at the static utility methods on the Box class. They can be used to manufacture fixed struts that act as invisible separators; e.g.
JPanel pnl = new JPanel(new FlowLayout());
pnl.add(new JButton("Hello"));
pnl.add(Box.createHorizontalStrut(10)); // Fixed width invisible separator.
pnl.add(new JButton("Goodbye");
This produces more compact code than creating / configuring a JPanel yourself with appropriate minimum, maximum and preferred dimensions.
JSeparator is meant to be a visible separator between components.
From the javadoc for JSeparator:
JSeparator provides a general purpose component for implementing divider lines - most commonly used as a divider between menu items that breaks them up into logical groupings.
If you want to put a component in between two components that is invisible just use an JPanel instead. Then set the size of the panel with setPreferedSize() and setMin/MaxSize().
You don't need JSeparator. Most layouts allow you to set gap (space) between compoponents. And Box class can be particularly useful.
Using addSeparator with a value of 1 for height makes it invisible for me, for example:
MyJToolBar.addSeparator(new Dimension(20, 1));
I have Java application which adds JTextFields # runtime to JPanel. Basically user clicks a button and new JTextField is added, clicks again added again...
Each new JTextField is directly below the previous one. Obviously I run out of space pretty soon so I'm trying to use JScrollPane and thats where the hell begins, because it just doesnt work no matter what I try.
Right click on JPanel and Enclose in Scroll Pane. Didnt work.
After reading some examples I realized I must have JPanel as an argument for JScrollPane constructor. Which I did via right clicking on ScrollPane and CustomizeCode. Because apparently auto-generated code is protected in NetBeans and I cannot just change all those declarations, etc. manually. Still doesnt work.
I did try to set PreferedSize to null for JPanel and/or JScrollPane, didnt help.
JScrollPane is a child of lets call it TabJPanel (which in turn is a tab of TabbedPane). I tried to mess with their relationships, basically trying every possible way of parentship between JFrame, JPanel(holding textfields), TabJPanel and JScrollPane, but nothing worked.
I also made VerticalScrollBar "always visible" just in a case. So I see the scrollbar, it's just that populating that JPanel with JTextFields does not affect it.
When there are too many JTextFields I they go "below" the bottom border of JPanel and I cannot see them anymore.
Code for adding new JTextFields is like this, in a case it's relevant.
JTextField newField = new JTextField( columns );
Rectangle coordinates = previousTextField.getBounds();
newField.setBounds(coordinates.x , coordinates.y + 50, coordinates.width, coordinates.height);
JPanel.add(newField);
JPanel.revalidate();
JPanel.repaint();
Sorry for a long post I'm just trying to provide as much info as possible, because being newbie I dont know whats exactly relevant and whats not. Thanks in advance :)
As there is another answer now, I'm adding my suggestion too.
This sounds exactly like a problem to use a JTable with a single column. JList is not yet editable (and might never be).
JTable would handle the layout problems for you, and you can easily access the values via the table.
Use your own TableModel (a simple Vector should be sufficient in your case), and add values to it.
An option you have is to utilize a LayoutManager, instead of setting the bounds directly on the components. To test this, a simple single column GridLayout with the alignment set to vertical should prove the concept.
panel.setLayout(new GridLayout(0,1));
zero in the rows param allows for rows to be added to the layout as needed.
I do this way to add a scrollpane, create a panel and fill it with few components, then create a scrollpane in the component you want to add it, cut and paste the panel in which all your details will fall in and resize the scrollpane.Because the components take a larger space than the one visible right click on the scrollpane and select design this container, there you can increase the size of the scrollpane and add as many components as you have.