JLabel label = new JLabel("Hello, world!"); label.setPreferredSize(new Dimension(200, 50));
JLabel label = new JLabel(new ImageIcon("image.png")); label.setPreferredSize(new Dimension(label.getIcon().getIconWidth(), label.getIcon().getIconHeight()));In this example, the preferred size of the label is set to match the size of the image loaded into the label using the ImageIcon class. These examples belong to the javax.swing package library.