Java: using an image as a button

后端 未结 9 2345
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 02:53

I would like to use an image as a button in Java, and I tried to do this:

BufferedImage buttonIcon = ImageIO.read(new File(\"buttonIconPath\"));
button = new         


        
相关标签:
9条回答
  • 2020-11-30 03:18

    This can be done easily in netbeans by setting the contentAreaFilled Property to False

    0 讨论(0)
  • 2020-11-30 03:24

    I followed below steps and i could create an 'ImageButton' successfully.

    1. Create a JButton
    2. Added an action listener
    3. Set an image icon (note i have placed the info.png icon in the src\main\resources folder and loaded using class loader). The project structure is as here.
    4. Set an empty Border
    5. Disabled the content area filling
    6. Disabled the focusability
    7. Added to the contentPane

    PFB the code that worked for me

    JButton btnNewButton = new JButton("");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Info clicked");
        }
    });
    
    String iconfilePath = this.getClass().getClassLoader().getResource("info.png").getFile();
    btnNewButton.setIcon(new ImageIcon(iconfilePath));
    btnNewButton.setBounds(10, 438, 39, 31);
    btnNewButton.setBorder(BorderFactory.createEmptyBorder());
    btnNewButton.setContentAreaFilled(false);
    btnNewButton.setFocusable(false);
    contentPane.add(btnNewButton);
    

    The output button resulted from above code is as below

    0 讨论(0)
  • 2020-11-30 03:27
    button.setBorderPainted( false );
    
    0 讨论(0)
  • 2020-11-30 03:29

    As far i know, there is no easy way of doing it, you will need to override the "paintComponent" method of the JButton class to aint your image, if you only want to display an image and behave like a button, you can add a JPanel wich draws the image (clicky) and add a MouseListener/MouseAdapter to handle the "mousePressed" event

    0 讨论(0)
  • 2020-11-30 03:31

    Remove the border like so:

    button.setBorder(BorderFactory.createEmptyBorder());
    

    and then also the contents1:

    button.setContentAreaFilled(false);
    

    1: Taken from the solution added to the question by @3sdmx

    0 讨论(0)
  • 2020-11-30 03:31
        BufferedImage buttonIcon = ImageIO.read(new File("myImage.png"));
        button = new JButton(new ImageIcon(buttonIcon));
        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setContentAreaFilled(false);
    
    0 讨论(0)
提交回复
热议问题