Question

image here I have created an image which looks like a 3d button and I want to use it as a button in java swing for my application.

I tried the following code:

 ImageIcon water = new ImageIcon("button.jpeg"); 
    exceptionButton = new JButton(water);

I got it as image but it had featured like border of the button so i used the following code:

   exceptionButton.setBorder(BorderFactory.createEmptyBorder());
    exceptionButton.setContentAreaFilled(false);
    exceptionButton.setFocusPainted(false);
    exceptionButton.setOpaque(false);

But it didnt help. I want the actual image to act as a button. The image has rounded corners but right now the image is coming in the button and loosing its actual effect of rounded corners. Also I want it focussed when a user brings mouse over it. Since I have put image for button with above code, I am not getting the effect of button press when user clicks on it.

How should I change my code?

No correct solution

OTHER TIPS

The image has rounded corners but right now the image is coming in the button and loosing its actual effect of rounded corners.

Don't use an EmptyBorder, that will always be Rectangular. Also try using setBorderPainted(false).

Also I want it focussed when a user brings mouse over it. Since I have put image for button with above code

Then you will also need to provide a rollover icon. See setRolloverIcon(...)

use jlabel instead of jbutton

 jLabel5 = new javax.swing.JLabel();

    jLabel5.setIcon(new javax.swing.ImageIcon(youriconpath)); 
jLabel5.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        jLabel5MouseClicked(evt);
    }
    public void mouseEntered(java.awt.event.MouseEvent evt) {
        jLabel5MouseEntered(evt);
    }
    public void mouseExited(java.awt.event.MouseEvent evt) {
        jLabel5MouseExited(evt);
    }
});

    private void jLabel5MouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        // write your code 
    }                                    

    private void jLabel5MouseEntered(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        //change your jlabel icon 
        jLabel5.setIcon(new ImageIcon("yourNewIconpath"));
    }                                    

    private void jLabel5MouseExited(java.awt.event.MouseEvent evt) {                                    
        // TODO add your handling code here:
        //resete your icon 
    }     
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top