How do you set JLabel borders in a JFrame?

I use JLabelto view the image in JFrame. I am loading it from a file using 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 the location and size JLabelbecause it runs automatically .

I need to manually set these values ​​because I want to crop the image (vertical progress bar).

+4
source share
3 answers

LayoutManager automatically adjusts your components, preventing you from manually resizing.

, LayoutManager.

frame.setLayout(null);

, null.

+1

- :

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

getWidth() getHeight() drawImage . , getPreferredSize() .

, , , , , FlowLayout GridBagLayout. , , , , , BorderLayout GridLayout

+5

(58 x 510). 20 x 420, , . - Image.getScaledImage(...). .

If you want to place your label (20, 20) in the upper left corner of the panel, you can add EmptyBorderto the panel or label.

Use the Swing features.

Edit:

I want to crop the image

Read your image in BufferedImage. Then you can use the method getSubImage(...)to get the image of any size you want. You can then use the helper image to create your ImageIcon and add it to the shortcut.

+4
source

All Articles