Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set the bounds of a JLabel in a JFrame?

I use a JLabel to view an image in a JFrame. I load it from a file with an ImageIcon.

JFrame frame = new JFrame(String);
frame.setLocationByPlatform(true);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel cpu = new JLabel(new ImageIcon(String));
cpu.setLocation(20, 20);
cpu.setSize(20, 460);
frame.add(cpu);
frame.setVisible(true);

I can't set location and size of the JLabel because it is done automatically.

I have to manually set these values because I want to truncate the image (vertical progress bar).

like image 622
Atom 12 Avatar asked Dec 25 '22 03:12

Atom 12


1 Answers

One way is to just paint the image:

final ImageIcon icon = new ImageIcon(path);
JPanel panel = new JPanel() {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(icon.getImage(), 0, 0, getWidth(), getHeight(), this);
    }
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500, 500);
    }
};
frame.add(panel); 

The getWidth() and getHeight() in drawImage will force the image to stretch the size of the panel. Also the getPreferredSize() will give a size to the panel.

If want the panel to stay that size, then make sure it's parent container has a layout manager that will respect preferred sizes, like FlowLayout or GridBagLayout. If you want the panel to be stretched, the make sure it's parent container has a layout manager that disregards the preferred size, like BorderLayout or GridLayout

  • See Performing Custom Painting for more info on painting.

  • See Laying Out Components Within a Container to learn more about layout managers (which you should be using). Also see Why is it frowned upon to use a null layout in SWING? and What's wrong with the Null Layout in Java?

like image 91
Paul Samsotha Avatar answered Jan 06 '23 11:01

Paul Samsotha