(Java) setBounds issue with a JLabel

Ill keep this brief, because all im simply asking is for a line of code. Heres my problem, so in order for my Jlabel to show up i Use .setBounds

My problem is I cannot guess the width of my text so what would i need to do in order for my setBounds to take the Width and Height as the text is.

If i have not explained this very well do say and ill try and explain more.

Some1 wanted an example so here goes:

My Code Snippet:

JLabel poisonDescription = new JLabel("This is the poison icon, when this appears...");
//My declaration.. the next is inside a void.
poisonDescription.setBounds(50, 50, 400, 20);
        add(poisonDescription);

its pretty simple, i want the Bounds to resize to the size of the font!

Oh yeah another question... How do i make a JLabel multi line?

Upvotes: 1

Views: 3441

Answers (4)

Hrishi D Developer
Hrishi D Developer

Reputation: 13

    l1 = new JLabel("UserName");
    l2 = new JLabel("Password");

    t1 = new JTextField();
    t2 = new JTextField();

    b1 = new JButton("Log In");
    b2 = new JButton("Cancel");

    l1.setBounds(100,100,40,30);
    l2.setBounds(100,150,70,30);
    t1.setBounds(200,100,150,30);
    t2.setBounds(200,150,150,30);
    b1.setBounds(100,200,90,30);
    b2.setBounds(200,200,90,40);

simply you can provide the dimensions for button textfield and others ...

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35011

The answer to your main question is this is the problem that LayoutManagers were designed to fix. If you want to fix this problem, stop using a null layout, start using a simple layout manager like FlowLayout or BorderLayout and let the layoutmanager size your label

For question #2 about multiline labels, the easiest way is to pass in properly formatted HTML with <HTML> tag included

Upvotes: 1

Paul Vargas
Paul Vargas

Reputation: 42010

You can use HTML for do it.

import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Main {
    public static void main(String[] args) {
        JLabel label = new JLabel("<html>One<br>Two!");
        JOptionPane.showMessageDialog(null, label);
    }
}

For more details, see in How to Use HTML in Swing Components in The Java Tutorial

Upvotes: 1

Guillaume Polet
Guillaume Polet

Reputation: 47608

Don't use setBounds, simply leave the JLabel handle himself its preferredSize. Whatever Layout you choose for the label container, it will handle the label properly.

To have a multiline label, simply use a JTextArea:

JTextArea textArea = new JTextArea();
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setOpaque(false);
textArea.setWrapStyleWord(false);

Upvotes: 1

Related Questions