2013-07-16

Cannot resize my JLabel

Recently, I encountered a problem with my code. I placed added JLabel object inside a JPanel with GridLayout(4,1) Manager. However, the "0" in my JLabel meant that it did not fully take the available column space well. I wanted to make the column with the components wider. GridLayout Manager would make all the Components the same size.

I first tried JLabel.setSize( width, height ) but it did not work. The size remained unchanged.
I later realized that I had to use JLabel.setPreferredSize( new Dimension( width, height) ) instead of calling the JLabel.setSize().

package app1;
import java.awt.*;
import javax.swing.*;

public class ResizeLabel extends JFrame {
    JLabel jlbl[] = new JLabel[4];
    JPanel pnl;
   
    public ResizeLabel() {
        pnl = new JPanel();
        pnl.setLayout(new GridLayout(4,1));
        for (int i = 0; i < jlbl.length; i++) {
            jlbl[i] = new JLabel("" + i, SwingConstants.CENTER);
            // setSize doesn't work
            jlbl[i].setSize(

                new Dimension(500, jlbl[i].getHeight() ));
            pnl.add(jlbl[i]);
        }  
        this.add(pnl);
    }
   
    public static void main(String[] args) {
        ResizeLabel f = new ResizeLabel();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
   
} // end class



ResizeLabel.java
 1 package app1;
 2 import java.awt.*;
 3 import javax.swing.*;
 4 
 5 public class ResizeLabel extends JFrame {
 6 
 7     JLabel jlbl[] = new JLabel[4];
 8     JPanel pnl;
 9     
10     public ResizeLabel() {
11         pnl = new JPanel();
12         pnl.setLayout(new GridLayout(4,1));
13         for (int i = 0; i < jlbl.length; i++) {
14             jlbl[i] = new JLabel("" + i, SwingConstants.CENTER);
15             // setPreferredSize works
16             jlbl[i].setPreferredSize(
17                     new Dimension(500, 20 ));
18             pnl.add(jlbl[i]);
19         }   
20         this.add(pnl);
21     }
22     
23     public static void main(String[] args) {
24         ResizeLabel f = new ResizeLabel();
25         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
26         f.pack();
27         f.setVisible(true);
28     }
29     
30 } // end of class

No comments:

Post a Comment

Github CoPilot Alternatives (VSCode extensions)

https://www.tabnine.com/blog/github-copilot-alternatives/