Stretching in Java Swing Box - java

I have a code:
Box box_general = Box.createHorizontalBox();
Box box_panel1 = Box.createVerticalBox();
Box box_panel2 = Box.createVerticalBox();
JPanel jpanel_1 = new JPanel();
jpanel_1.setPreferredSize(new Dimension(50, 152));
jpanel_1.setOpaque(true);
jpanel_1.setBorder(BorderFactory.createLineBorder(Color.BLUE));
JPanel jpanel_2 = new JPanel();
jpanel_2.setPreferredSize(new Dimension(340, 152));
jpanel_2.setOpaque(true);
jpanel_2.setBorder(BorderFactory.createLineBorder(Color.RED));
JTextField jtxtf_populationSize = new JTextField();
jtxtf_populationSize.setSize(10, 20);
JTextField jtxtf_processorsAmount = new JTextField();
JButton jbtn_loadProcesses = new JButton("File path");
box_panel1.add(Box.createRigidArea(new Dimension(0,4)));
box_panel1.add(jtxtf_processorsAmount);
box_panel1.add(Box.createRigidArea(new Dimension(0,20)));
box_panel1.add(jbtn_loadProcesses);
jpanel_1.add(box_panel1);
JLabel jlbl_populationSize = new JLabel("Enter the population size");
JLabel jlbl_processorsAmount = new JLabel("Enter the amount of processors");
JLabel jlbl_loadProcesses = new JLabel("Load processes from file");
jlbl_populationSize.setFont(font);
jlbl_processorsAmount.setFont(font);
jlbl_loadProcesses.setFont(font);
box_panel2.add(jlbl_populationSize);
box_panel2.add(Box.createRigidArea(new Dimension(0,4)));
box_panel2.add(jlbl_processorsAmount);
box_panel2.add(Box.createRigidArea(new Dimension(0,15)));
box_panel2.add(jlbl_loadProcesses);
jpanel_2.add(box_panel2);
box_general.add(jpanel_2);
box_general.add(Box.createRigidArea(new Dimension(10,0)));
box_general.add(jpanel_1);
It creates 3 boxes, where the general box contains two other boxes. The problem is: in the box all the compopents are stretched of width. For example, there is a line jtxtf_populationSize.setSize(10, 20); but this text field is stretched in the box_panel1 on width. I tried to use a BoxLayout with it's Alignment_X but this didn't work.
Could you, please, advise me, what to do - how to avoid stretching?

Most of the swing layouts will use the preferred size and the minimum/maximum size over a call to setSize. The key here is to get the right preferred and minimums so that they don't shrink too much, and then insert a strut (Box#createHorizontalStrut) to fill up space where you don't want a component.
With complex layouts like this, consider the SpringLayout, which admittedly has a higher learning curve, but once you get used to it, will allow you to more naturally state the constraints you want.

Related

Java - Distance between JLabel and vertical box

I wrote this code for realize a box into I put four JRadioButtons
JRadioButton beginner = new JRadioButton("Beginner"); beginner.setSelected(true);
JRadioButton intermedie = new JRadioButton("Intermedie");
JRadioButton expert = new JRadioButton("Expert");
JRadioButton custom = new JRadioButton("Custom");
Box boxDifficulty = Box.createVerticalBox();
boxDifficulty.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 50));
boxDifficulty.add(beginner);
boxDifficulty.add(intermedie);
boxDifficulty.add(expert);
boxDifficulty.add(custom);
Furthermore I set the border of the box using the setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 50)) method.
Also, I created a JLabel for indicate the title of the box:
JLabel difficulty = new JLabel("Choose the difficulty:");
This is the portion complete of the code:
Box boxDifficulty = Box.createVerticalBox();
boxDifficulty.add(difficulty);
boxDifficulty.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 50));
boxDifficulty.add(beginner);
boxDifficulty.add(intermedie);
boxDifficulty.add(expert);
boxDifficulty.add(custom);
How can I increase the space between JLabel and JRadioButton?
How can I increase the space between JLabel and JRadioButton?
You can add a spacing component to the panel after you add the label:
boxDifficulty.add(difficulty);
boxDifficulty.add( Box.createVerticalStrut(...) );
A strut is a fixed height(width) invisible component.

JTextField becomes HUGE in a HorizontalBox

Please consider this Java code fragment:
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(new JCheckBox("Select all"));
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(new JLabel("Filter: "));
buttonBox.add(new JTextField());
Box paneBox = Box.createVerticalBox();
paneBox.add(buttonBox);
paneBox.add(new JScrollPane(jList));
For some reason i don't get, the JTextField takes up most of the screen. The jList isn't even visible anymore. I would like to know why and how to fix it.
When i comment the line with the JTextField, it looks fine (except no JTextField, of course). Why does the JCheckBox and the JLabel not get ridiculously big? What is the purpose of a one-line JTextField being able to take up almost the whole screen?
Most people suggest to set the size of the JTextField field to my needs. However, i read that i should not call these methods, but let the LayoutManager take care of it. Now what is the most elegant solution to prevent the JTextField from becoming so big?
Try using the setPreferredSize method like this:
textFieldName.setPreferredSize(new Dimension(x, y));
Obviously input the values for x and y that you wish the JTextField size to be
You can avoid this problem by using a simple JPanel() instead of a Box for the horinzontal one. And after just set the prefered size to your JTextField.
//Box buttonBox = Box.createHorizontalBox();
JPanel buttonBox = new JPanel();
buttonBox.add(new JCheckBox("Select all"));
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(new JLabel("Filter: "));
JTextField jt = new JTextField();
jt.setPreferredSize(new Dimension(100,25));
buttonBox.add(jt);
EDIT
Btw the defaut Layout of a JPanel is the FlowLayout which place components from left to right and with centered alignement by default. You can still change the alignement.
For example:
JPanel buttonBox = new JPanel(new FlowLayout(FlowLayout.LEFT));
You can also change the gap between each components. There is some other Layout like the BorderLayout or GridLayout / GridBagLayout. I let you search on Google for more information about them.
See in yellow the JPanel, in red the VerticalBox
Box box = Box.CreateVerticalBox();
Use box.setMaximumSize(Dimension(160,80))
and box.setMinimumSize(Dimension(160,80))
then it will work :D
If you need a strut for your layout, put it in between boxes.

Java Styling - Spacing

So I've been learning Java for the very first time and it's time for me to attempt my first project. And I'm stuck at the "first hurdle" haha.
The issue I have is the fact that I don't actually know how to space J Items apart.
I have a 250,350 window for a Log In form with a JLabel, a JTextField for username and JLabel JPassword for Password with a JButton at the bottom.
What I want to do now is style it so that the spacing between the top and the bottom of the form makes it so that the form is centered as well as adding a line's height space between the JLabel and the JTextField. (Basically a \n type deal but that isn't working.)
Hopefully this makes sense, if not, I apologise and I'll try to rephrase/add code!
public Game() {
this.setSize(250,350);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Sticket Cricket - Login");
JPanel loginMenuPanel = new JPanel();
loginButton = new JButton("Login");
usernameField = new JTextField();
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setColumns(10);
passwordField.requestFocus();
usernameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
this.add(loginMenuPanel);
loginMenuPanel.add(usernameLabel);
loginMenuPanel.add(usernameField);
loginMenuPanel.add(passwordLabel);
loginMenuPanel.add(passwordField);
loginMenuPanel.add(loginButton);
this.setVisible(true);
}
Short Answer:
Create a JPanel, set the layoutmanger of the panel (some examples, GridLayout, BorderLayout, Check out the tutorial here where more of these are explained)
Then add your components to this panel accordingly
For the layout you are looking for it would possibly be easier to use an IDE to create this, I find Net Beans to be the easiest for doing this.
My recommendation would be for you to create a JPanel with a grid layout of 2 columns and 2 rows, to this add you JLabels and Text fields for the logon name and password.
Then create another JPanel possibly BorderLayout or Flow Layout and add the above panel to this then add this parent panel to the frame.

Align text in JLabel to the right

I have a JPanel with some JLabel added with the add() method of JPanel. I want to align the JLabel to the right like the image below but I don't know how to do that. Any Idea? Thanks!
This can be done in two ways.
JLabel Horizontal Alignment
You can use the JLabel constructor:
JLabel(String text, int horizontalAlignment)
To align to the right:
JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);
JLabel also has setHorizontalAlignment:
label.setHorizontalAlignment(SwingConstants.RIGHT);
This assumes the component takes up the whole width in the container.
Using Layout
A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout:
Box box = Box.createVerticalBox();
JLabel label1 = new JLabel("test1, the beginning");
label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label1);
JLabel label2 = new JLabel("test2, some more");
label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label2);
JLabel label3 = new JLabel("test3");
label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label3);
add(box);
JLabel label = new JLabel("fax", SwingConstants.RIGHT);
To me,
it seems as if your actual intention is to put different words on different lines.
But let me answer your first question:
JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);
And if you have an image:
JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);
But, I believe you want to make the label such that there are only 2 words on 1 line.
In that case try this:
String urText="<html>You can<br>use basic HTML<br>in Swing<br> components,"
+"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);

How to have a specific component resize based on available, visible space?

In my application, I have a layout similar to what is shown below:
#######
XXXXXXX***
XXXXXXX***
XXXXXXX***
%%%%%%%
In this layout, X is a JTable. The other components can remain the same size. Is there a layout or strategy that will have the JTable (X) resize based on available screen size and have everything else stay on the sides properly?
Thanks.
That looks very much like a BorderLayout to me. Have you tried that?
It can also be done with GroupLayout, but it is designed for GUI builders, as it's very verbose. So if you already have existing code, you might not want to try it first.
I am a big fan of JGoodies FormLayout. Here is some sample code of one way to do this with FormLayout.
JPanel panel = new JPanel();
FormLayout layout = new FormLayout("100dlu, 20dlu:grow", "pref, pref, pref");
panel.setLayout(layout);
JTextField t1 = new JTextField();
JTextField t2 = new JTextField();
JTable tb = new JTable();
JScrollPane sp = new JScrollPane();
sp.setViewportView(tb);
CellConstraints cc = new CellConstraints();
panel.add(t1, cc.xy(1, 1));
panel.add(t2, cc.xy(1, 3));
panel.add(sp, cc.xyw(1, 2, 2));

Categories