JLabel text alignment - java

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.

Related

JComponent partially hidden due to scrollpane in a BoxLayout

I want to add the possibility for my users to add a comment on a form. To display them, I created JPanel inside a simple JScrollPane. I set the layout of this JPanel to BoxLayout because I wish to add them all in only one column and it seemed to be the easiest way by calling BoxLayout.Y_AXIS in the constructor. I also tried GridLayout and GridBagLayout but it was not what I was looking for.
My problem is that when a JPanel has the BoxLayout layout, it's width automatically is the same as it's container, but my container is a JScrollPane and the caret hides the right side of my comment!
You can see the JTextField and a JButton on the bottom left, here's the code on the click event :
private void btnAjoutCommentaireActionPerformed(java.awt.event.ActionEvent evt) {
//I take the text from the JTextField and format it to html
String formattedComment = "<html><br><div style='width:280px;'>" +
txtArCommentaire.getText().replaceAll("\n", "<br>") +
"</div><br></html>";
JLabel label = new JLabel(formattedComment);
//I add a blue border
label.setBorder(new TitledBorder(new EtchedBorder(Color.lightGray, Color.blue), ConfigUser.getCu().toString()));
//this below doesn't work
label.setSize(280, 200);
//I tried adding a JPanel in between but it didn't really worked out
//JPanel panel = new JPanel();
//panel.setLayout(new GridLayout(1, 1));
//panel.setSize(297, 200);
//panel.add(label);
///pnlCommentaire is the JPanel inside the JScrollPane
pnlCommentaire.setLayout(new BoxLayout(pnlCommentaire, BoxLayout.Y_AXIS));
pnlCommentaire.add(label);
pnlCommentaire.revalidate();
pnlCommentaire.repaint();
}
As you can see I tried to adust the size in html using style='width:280px'and on the JLabel using label.setSize(280, 200); but none of them worked.
Do you have any idea on how I could resize this Jlabel?
EDIT :
I added a margin-right property to the div so that I can at least fully see the text in the JLabel but the right border is still hidden.
String formattedComment = "<html><br><div style='width:280px;margin-right:50px;'>" +
txtArCommentaire.getText().replaceAll("\n", "<br>") +
"</div><br></html>";

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.

When typing into JTextArea, text in JLabel moves

I'm making a simple GUI and have a problem.
This is my code :
JFrame jFrame = new JFrame();
jFrame.setTitle("Simple Editor");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setLocation(50,50);
jFrame.setResizable(true);
Box box = new Box(BoxLayout.Y_AXIS);
JTextArea jTextArea = new JTextArea();
jTextArea.setPreferredSize(new Dimension(470,500));
JLabel jLabel = new JLabel();
box.add(jTextArea);
box.add(jLabel);
jLabel.setText("Font type : " + Main.fontType + " font size : " + Main.size
+ " background color : " + Main.backgroundColor
+ " font color : " + Main.fontColor);
jFrame.setContentPane(box);
jFrame.pack();
jFrame.setVisible(true);
When I typing something in JTextArea, text in JLabel is moving. I can't figure out how to solve this. Maybe some component between them? Any advice and help is welcome.
This looks like an artifact of how the Box is calculating sizes and locations. Note that some components and layout managers do not use setPreferredSize, or only take it as a hint, or use it as only one part of a computation, or etc. so it cannot be depended upon as a reliable method to set the size of a component.
In this case, I would hypothesize what is going on is something like: BoxLayout generally uses minimum/maximum sizes, not preferred sizes, and the min/max of a JTextArea is computed based on its text content. As the text changes, the size is recalculated so the layout changes too.
In general if you have a text area, you should put it in a JScrollPane instead:
Box box = new Box(BoxLayout.Y_AXIS);
JTextArea jTextArea = new JTextArea();
JScrollPane jScrollPane = new JScrollPane(jTextArea);
jScrollPane.getViewport().setPreferredSize(new Dimension(470,500));
JLabel jLabel = new JLabel();
box.add(jScrollPane);
box.add(jLabel);
This way when the text content changes in the JTextArea it can simply do its thing, recalculating its size, and flow out the side of the scroll pane.
Also see How to Use Scroll Panes, How to Use Text Areas.
Per Andrew's comment, here are a couple ways to set the initial size of the scroll pane which are perhaps more reliable than setting the viewport's preferred size explicitly:
// specify rows & columns
JTextArea jTextArea = new JTextArea(20, 20);
// specify preferred scrollable viewport size
JTextArea jTextArea = new JTextArea() {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(470,500);
}
};
jTextArea.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
jLabel.setText(jTextArea.getText());
}
});
where,
jTextArea - your name object of JTextArea class
jLabel - your name object of JLabel class
You add text in the textarea and text in the label is changing. I think, this code help you to decide your problem.

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

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