How to make the image scale its size automatically according to the parent JLabel's size, in Netbeans GUI Builder?

那年仲夏 提交于 2019-12-02 01:38:31
Paul Samsotha

" or if there is a way to disable the sizing of the window completely."

You can set the resizable property of the frame to false. From NetBeans GUI Builder

  1. Highlight/select the frame component from the design view, or from the navigator window.
  2. Go to the properties window on the right and look for the property resizable and make sure it's unchecked

"I also want to ensure that the image size, its parent JLabel's size, JPanel's size will all adjust to the frame when the I change the size of the window"

One way is to paint the background onto the background panel, instead of using a label with an icon. You can see an example of that here. For the GUI Builder, the easiest way (without having to edit the auto-generated code, which I don't recommend, if you don't know what you are doing) is to use a JPanel form instead of a JFrame form. Paint on the JPanel form, then you can add that JPanel form to the JFrame form. You can see here for an easy way to add the JPanel form to the JFrame form.


UPDATE

So your JPanel form class will ultimately look something like this

public class PanelForm extends javax.swing.JPanel {
    private BufferedImage image;

    public PanelForm() {
        try {
            image = ImageIO.read(getClass().getResource("/path/to/image/png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }  
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500, 500);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new PanelForm());     //  <--- add it here
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!