setBounds value for width that will set width to minimum? - java

Is there a value that can be put into setBounds to set the width to the minimum needed?
JLabel title = new JLabel("Title Text");
title.setBounds(50, 20, ?, 13);
Rather than using guess & check to find the minimum width, is there a value I can use?

If you already know the text that will be in the JLabel (i.e., if that text won't change after being assigned once), there is no need to set the minimum width; the JLabel should do so automatically.

Related

JLabel Width dependent from Text Length

So I have a JLabel here that's text is set from a String taken from a file seen here:
Label lName = new JLabel("Charater Name: " + data[FileIO.NAME]);
lName.setForeground(Color.WHITE);
lName.setBounds(640 - 110, 5, 110, 30);
add(lName);
Since the name could be 3 letters long to 24 letters long I don't want to use a fixed width, I want the label's width to wrap around the text enough so that the text isn't cut off but so that it's not wasting a bunch of space, how can I do this?
Edit:
The JLabel's location will be set programmatically depending on it's width.
Currently my only solution is setting the width to this:
(int) (lName.getText().length() * (double) 6.8)
Which lasts for around 40 letters before being cut off.

Change JSpinner Size (width) [duplicate]

This question already has answers here:
JSpinner: Increase length of editor box
(5 answers)
Closed 8 years ago.
My problem: JSpinner is so skinny that I can only see the chars on the string in the last spot.
ex: "Hello" I only see 'o'.
I have a JPanel in a JFrame's BorderLayout.SOUTH
The JPanel's layout manager is the default which is - correct me if I'm misinformed - a FlowLayout manager.
also there's multiple components in the previously mentioned JPanel.
I've tried
RandomSpinner = new JSpinner(tempModel);
int w = RandomSpinner.getWidth(); int h = RandomSpinner.getHeight();
RandomSpinner.setSize(new Dimension(w * 2, h));
add(RandomSpinner);
this had no effect on the width of the JSpinner.
How should I change the width of my JSpinner or is this a FlowLayout issue?
thank you
You can do it all in the following three steps:
// 1. Get the editor component of your spinner:
Component mySpinnerEditor = mySpinner.getEditor()
// 2. Get the text field of your spinner's editor:
JFormattedTextField jftf = ((JSpinner.DefaultEditor) mySpinnerEditor).getTextField();
// 3. Set a default size to the text field:
jftf.setColumns(your_desired_number_of_columns);
Set the preferred and minimum sizes:
RandomSpinner = new JSpinner(tempModel);
int w = RandomSpinner.getWidth(); int h = RandomSpinner.getHeight();
Dimension d = new Dimension(w * 2, h);
RandomSpinner.setPreferredSize(d);
RandomSpinner.setMinimumSize(d);
Setting preferred size should be enough if you have enough space in your frame.

How do you stop a JLabel changing its size when its text changes?

I'm generating some JComponents in code and using the GridBag layout to arrange them. My layout consists of 12 rows and 3 columns, with each row consisting of a JSlider, a JCheckBox and a JLabel. Here's the code I'm using to generate the UI:
final int NUM_MOTORS = 12;
// This is the panel I'm adding the components to.
pnlMotorSliders.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
for (int i = 0; i < NUM_MOTORS; ++i) {
c.gridy = i;
// Create the slider
JSlider slider = new JSlider(SwingConstants.HORIZONTAL, 10, 4085, 10);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.weightx = 0.9;
pnlMotorSliders.add(slider, c);
// Create the checkbox
JCheckBox checkBox = new JCheckBox();
checkBox.setOpaque(true);
checkBox.setBackground(Color.blue);
c.fill = GridBagConstraints.NONE;
c.gridx = 1;
c.weightx = 0.1;
pnlMotorSliders.add(checkBox, c);
// Create the current label
JLabel label = new JLabel("0");
label.setBorder(BorderFactory.createLineBorder(Color.red));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.weightx = 0.2;
pnlMotorSliders.add(label, c);
}
The problem I'm having is that when I set the text in any of the JLabels, they change their width and affect the rest of the layout, even if the width of the text that I'm setting appears to be much smaller than the width of the JLabel. The following two screenshots demonstrate what I mean (the red and blue borders were for debugging purposes):
I've set the text on the bottom JLabel to "-12". Even though the JLabel appears to be much wider than the text, it has changed its size, affecting the rest of the layout.
Why is this happening and what can I do to prevent it?
You can fix the size of the labels by setting the minimum, prefered and maximum size:
label.setMinimumSize(width, height);
label.setPreferedSize(width, height);
label.setMaximumSize(width, height);
Also make sure to set the GridBagConstraints#fill to NONE, although I am not sure if that is still neccessary (I think it is).
EDIT: btw, to get rid of those nasty dashed lines around the focused Component, you can just set it to be not focusable:
slider.setFocusable(false);
The set-the-preferred-size solution works only if you don't have the components horizontally fill their bag in the GridBagLayout.
Another solution is to remove the weight you have placed on components in that column of your GridBagLayout. You can then control the column width manually. An easy way to do so (at design time) is to place a JLabel in the column with zero height and the specific width you desire.
Why is this? You need to dig into how GridBagLayout works:
The GridBagLayout sizes its columns based on the space required, and then uses the weights to allocate the "left over" space so that the resulting column widths then add up to the total width of the panel. The space required for each column is computed by finding the widest of the components in that column.
The space required for each component is determined by asking it what width it would prefer. In your case, a JLabel with "0" is smaller than a JLabel with "-12" and so the column is changing size.
The left over space is allocated based on the horizontal weights assigned to components in each column. The weights are totaled and percentages for each column are determined based on that column's percent of the total.
The column size is determined based on the space required PLUS the left over space. So, if all your components in the column have no weight then you'll not get any left over space, and hence not get dynamic changes.
A third solution is to just not use GridBagLayout.
Explicitely set the preferred size of your labels using JLabel#setPreferredSize(Dimension).
This way, you lock the size of the component, and tell the layout manager not to resize it.
label.setPreferredSize(new Dimension(width, height));
This was only way i could find to make it work. Setting a Minimum and/or a Maximum didn't do anything for me. Also, for me on java 8 i needed to use a Dimension, or there was no change to the previous, inappropriate sizes.

JLabel Width Independent from Text Length

I have a JLabel in a horizontally re-sizable JPanel. The JLabel auto re-sizes its width to fit the JPanel. If I insert a long line of text (such as "aaaaaaaaaaaaaaaaaaaaaaaa") the JLabel doesn't truncate the text. Instead, the width re-sizes to fit the text, causing also an ugly re-sizing of the JPanel.
Instead, I want my text to be truncated with an elipse (...). The JLabel width must not inherit from the text's length but only from the JPanel width.
Try following:
final JLabel label = ...
...
label.setText("prototype text to define size");
final Dimension size = label.getPreferredSize();
label.setMinimumSize(size);
label.setPreferredSize(size);
...
label.setText(...);
Use a different layout or set a max size on the JLabel.
You need to disable 'Horizontal Resizable' when you define a max- and preferedsize

Java: Fonts and Pixels

I'm making a game and in the menu I want to display the text in the center of the screen.
Is there a way in Java to get/calculate the width of a piece of text in a specified font with specified size and style.
Martijn
The FontMetrics.stringWidth method does just that -- it will return the width in pixels for a given String.
One can obtain the FontMetrics from a Graphics object by the getFontMetrics method.
For example:
g.setFont(new Font("Serif", Font.BOLD, 24));
int width = g.getFontMetrics().stringWidth("Hello World!");
System.out.println(width);
The result was:
135
In the class Font you have methods such like getLineMetrics or getStringBounds that may help you.
Just use a JLabel that is center aligned and the proper layout manager and you don't have to worry about this.
JLabel label = new JLabel("Text");
frame.add(label , SwingConstants.CENTER);

Categories