Set size for jLabel in a swing

I want to install jLabelwith dimension(50,75)inside a JFrame.

I tried to use

label.setPreferredSize(new Dimension(50, 75)); 

But that does not work. How can i do this?

+4
source share
4 answers

setPreferredSizewill really change the size of the label, which you should just try to draw using the method setBorderto check the new size, but the font size has not changed, if you want the large font to try to call setFontand set a new font size, here to start, enter the code:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;

public class Test {
    public static void main(String[] args) {
        JFrame t = new JFrame();
        t.setBounds(100, 100, 500, 400);
        JLabel l = new JLabel("Hello");
        // new font size is 20
        l.setFont(new Font(l.getFont().getName(), l.getFont().getStyle(), 20));
        // draw label border to verify the new label size
        l.setBorder(new LineBorder(Color.BLACK));
        // change label size
        l.setPreferredSize(new Dimension(200, 200));
        t.getContentPane().setLayout(new FlowLayout());
        t.add(l);
        t.setVisible(true);
    }
}
+3
source

A simple example:

class Testing extends JFrame  
{  
  int counter = 1;  
  javax.swing.Timer timer;  
  public Testing()  
  {  
    setSize(100,50);  
    setLocation(300,100);  
    setDefaultCloseOperation(EXIT_ON_CLOSE);  
    JPanel p = new JPanel();  
    final JLabel label = new JLabel("1",JLabel.CENTER);  
    label.setBorder(BorderFactory.createLineBorder(Color.BLACK));  
    Dimension d = label.getPreferredSize();  
    //label.setPreferredSize(new Dimension(d.width+60,d.height));//<-----------  
    p.add(label);  
    getContentPane().add(p);  
    ActionListener al = new ActionListener(){  
      public void actionPerformed(ActionEvent ae){  
        counter *= 10;  
        label.setText(""+counter);  
        if(counter > 1000000) timer.stop();}};  
    timer = new javax.swing.Timer(1000,al);  
    timer.start();  
  }  
0
source

JLabel setBounds(x, y, width, height)

. x y, .

-1

LayoutManager, Pack.

LayoutManager , pack() .

public void pack()

Causes this window to be sized to fit the preferred sizes and layouts of its subcomponents. The resulting width and height of the window automatically increases if any of the sizes is less than the minimum size specified by the previous call to the setMinimumSize method. If the window and / or its owner are not yet displayed, both of them become displayed before calculating the preferred size. The window is checked after calculating its size.

-1
source

All Articles