user2184376
user2184376

Reputation: 13

Custom Button Classes in Java

I know that my approach isnt practical, but this is going to help me get used to Java a bit more. I am trying to create a JButton subclass (named MyButton). MyButton basically will create a new Gui button, with a custom image background. I know how to create a new button in the class, but dont know how to refer to the button that the MyButton class creates. As the code shows, the button's icon needs to be set, but this needs to be done inside the subclass, so that said used doesnt have to use it. On creation, the coder inputs the string that refers to the texture, and then the MyButton has all the properties of a JButton, but also already has its image set. Below is my source code.

package Classes;
import javax.swing.ImageIcon;
import javax.swing.JButton;

public class MyButton extends JButton{
private static final long serialVersionUID = 1L;

public JButton abc = new JButton();
private ImageIcon def;
private MyButton ghi;

public MyButton(String image){

    def = new ImageIcon(getClass().getResource(image));

    //abc.setIcon(def);
    //abc.setPressedIcon(def);

    ghi = new MyButton("image.png");
    ghi.setIcon(def);


}
}

UPADTE Solved it. Thanks Sam. "this.setIcon" works I believe

Upvotes: 0

Views: 2027

Answers (3)

HUNeater
HUNeater

Reputation: 166

If you extend the JButton, then you got a new object wich is a button.
The original JButton has a draw method, where it draws the button to the canvas.

I think you should override the button's paintComponent() method like this:

@Override
public void paintComponent(Graphics g) {
    // g.drawImage(image) or something...
}

//  Also has a paintBorder() method
public void paintBorder(Graphics g) {
   // Draw your border if mouse over
}

So you can draw your initalised image file. The button will works like the normal JButton, but the constructor will takes the image url. (you arleady did this).

Upvotes: 0

Hong Wei Wang
Hong Wei Wang

Reputation: 1398

public class MyButton extends JButton{
private static final long serialVersionUID = 1L;
private ImageIcon def;
private MyButton ghi;

public MyButton(){
def = new ImageIcon("image.png");
super(def);
}
}

Something along the above class.

Upvotes: 0

Nick
Nick

Reputation: 2845

Perhaps I'm misunderstanding you, but MyButton doesn't (or probably shouldn't) create a button, it is the button. (Technically, it's a type of button.) The method public MyButton... is a constructor method for the MyButton class; it initializes a new MyButton. The this keyword will refer to the button within the MyButton class; outside of it, you'll use code that looks something like this:

MyButton aButton = new MyButton();

Upvotes: 2

Related Questions