how can i put a JButton on an image?

后端 未结 4 1668
终归单人心
终归单人心 2020-12-18 07:54

I am trying to fix a JFrame where there will be a background image and on the image JButtons which will do some commands. I try to do it without layout because i want to pu

4条回答
  •  攒了一身酷
    2020-12-18 08:21

    You need to change the content pane to get a background for your Frame.

    public static void main(String[] args) throws IOException {
    
        JFrame frame = new JFrame("Test");
    
        frame.setContentPane(new JPanel() {
            BufferedImage image = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(image, 0, 0, 300, 300, this);
            }
        });
    
        frame.add(new JButton("Test Button"));
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
    

    Output:

    screenshot

提交回复
热议问题