Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Draw Image as JButton

801682Jan 20 2011 — edited Jan 23 2011
Hello,

I'm trying to paint and image and use it like JButton. But I don't know what I'm doing wrong.

There is my code:

ImageButton.java
public class ImageButton extends JButton {

    protected ImageButton(){

    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Image img = Toolkit.getDefaultToolkit().getImage("right.png");
        
        g2.drawImage(img, 45, 35, this);
        g2.finalize();
    }
    
}
And:

ButtonTest.java
public class ButtonTest extends JFrame{

    public ButtonTest(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 500);
        getContentPane().add(createImageButtonPanel(), BorderLayout.PAGE_START);
        
    }

    public final JPanel createImageButtonPanel(){
        JPanel panel = new JPanel(new BorderLayout());
        panel.setPreferredSize(new Dimension(45, 35));
        panel.add(new ImageButton());
        return panel;
    }

    public static void main(String [] args){
        new ButtonTest().setVisible(true);
    }

}
My image is in the same package where the ImageButton class is. When I start my project there is no button displayed on the frame.
Maybe somebody could tell me what I'm doing wrong?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 20 2011
Added on Jan 20 2011
11 comments
1,144 views