Align text in JLabel to the right - java

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);

Related

JLabel text alignment

I need to change the label alignment from the default to the other way.
Tried to do that but it didn't work
JLabel label = new JLabel(text, SwingConstants.RIGHT);
label.setHorizontalAlignment(SwingConstants.RIGHT);
But the text stayed the same.

Java : JLabel with text and icon

I would like to ask if it is possible in a single JLabel to have text icon text, what i mean is the icon to be in the center of my String text.
I managed to move text left or right of the icon but i cant figure out how to put the icon in the middle.
icon to be in the center of my String text
A JLabel has text and icon - you can have the label on top of the text, but not two text's and one icon. You can achieve the same look with 3 JLabel's together in the proper Layout. For example, using a BoxLayout:
Box box = Box.createHorizontalBox();
box.add(new JLabel("Text 1"));
JLabel image = new JLabel();
image.setIcon(UIManager.getIcon("OptionPane.errorIcon"));
box.add(image);
box.add(new JLabel("Text 2"));
Alternatively, if you wish the text to be on top of the image you can do so by setting the appropriate alignments:
JLabel label = new JLabel();
label.setIcon(UIManager.getIcon("OptionPane.errorIcon"));
label.setText("My Text");
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);
I would like to ask if it is possible in a single JLabel to have text icon text
A JLabel can display simple HTML:
String html = "<html>before <img src=\"file:someFile.jpg\">after</html>";
JLabel label = new JLabel( html );
but HTML takes longer to render so you may want to consider the BoxLayout approach.

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.

Stretching in Java Swing Box

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.

Categories