Reputation: 37
I would like to create my own custom buttons with a defined size and a defined color.
For this purpose I used the Custom Component creating a class that extend a JButton.
Unfortunately I realized that when I override paintComponent()
and call super.paintComponent(g)
at the end of the method, it cause the overriding of the color setting made. However, if I don't call the super method, the button does not have the clickable functionality anymore.
Any suggestion if there is anything wrong in my code, or something missing? Any advise for achieve my goal?
Upvotes: 0
Views: 77
Reputation: 485
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JFrame;
public class CreateRoundButton extends JButton {
public CreateRoundButton(String label) {
super(label);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width,size.height);
setPreferredSize(size);
//added to remove a border of the text in jbutton
setFocusPainted(false);
setContentAreaFilled(false);
}
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0, 0, getSize().width-1,getSize().height-1);
super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}
Shape shape;
public boolean contains(int x, int y) {
if (shape == null ||
!shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}
public static void main(String[] args) {
JButton button = new CreateRoundButton("Click");
button.setBackground(Color.gray);
JFrame frame = new JFrame();
frame.getContentPane().add(button);
frame.getContentPane().setLayout(new FlowLayout());
frame.setSize(150, 150);
frame.setVisible(true);
}
}
Taken from here http://www.roseindia.net/tutorial/java/swing/createRoundButton.html
Upvotes: 2
Reputation: 37
I tried as well in this way, but putting the calling to the super method in the beginning cause that the text button is not visibile any more! Actually in both case I call the super method the properties that I setted has been overridden.
My goal si change size, shape and color of the button kipping all other Jbutton proteries. Here my code.
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (getModel().isArmed()) {
g2d.setColor(Color.LIGHT_GRAY);
} else {
g2d.setColor(this.colorwell);
}
g2d.fillOval(0, 0, getSize().width-1,getSize().height-1);
g.dispose();
}
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}
Upvotes: 0