user3453226
user3453226

Reputation:

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).

Upvotes: 4

Views: 4240

Answers (3)

ControlAltDel
ControlAltDel

Reputation: 35011

The LayoutManager is auto-sizing your components, not allowing you to resize manually.

If you want to get away from this, you can turn off the LayoutManager.

frame.setLayout(null);

Please note that you should not use the null layout.

Upvotes: 1

camickr
camickr

Reputation: 324098

The size of your original is (58 x 510). If you want to display the image at a fixed size of 20 x 420, then you should scale your image to that size to you don't truncate any of the image. One way to do that is to use the Image.getScaledImage(...) method. Then you just add the scaled image to the label.

If you want to position your label (20, 20) from the top left of the panel, then you can add an EmptyBorder to the panel or the label.

Use the features of Swing.

Edit:

I want to truncate the image

Read your Image into a BufferedImage. Then you can use the getSubImage(...) method to get an image any size you want. Then you can use the sub image to create your ImageIcon and add it to a label.

Upvotes: 4

Paul Samsotha
Paul Samsotha

Reputation: 208944

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

Upvotes: 5

Related Questions