I'm new to Java, especially to swing and I was trying to make a button that has some custom property (color, number) and I wanted to make it a round button so my implementation was the following:
NumberButton testbutton = new NumberButton("0");
testbutton.setUI(new BasicButtonUI() {
@Override
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(testbutton.getColor());
g.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 100, 100);
}
paint(g, c);
}
});
mainPanel.add(testbutton);
The problem is that I want to make this BasicButtonUI generally callable custom class but I don't know how can I get from inside the "void update" function the outer testbutton's color property.
The custom NumberButton:
public class NumberButton extends JButton {
private boolean pressState;
private int number;
private Color color;
public NumberButton(String title) {
super(title);
this.pressState = false;
this.number = 0;
this.color = new Color(86, 86, 86);
this.setPreferredSize(new Dimension(100, 100));
this.setBackground(new Color(24, 25, 27));
this.setAlignmentY(0.5F);
this.setOpaque(true);
this.addActionListener(actionEvent -> this.changePressState());
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public void changePressState(){
this.pressState = !this.pressState;
if(this.pressState) {
this.color = new Color(139, 239, 99, 166);
} else {
this.color = new Color(122, 154, 116);
}
this.number += 1;
this.setText(String.valueOf(this.number));
}
}
edit:
I tried creating a new class that extends to BasicButtonUI and the constructor takes one argument that can be set on call to the buttons color but than it doesn't changes it's color anymore:
public class RoundButtonUI extends BasicButtonUI {
private Color color;
RoundButtonUI(Color c) {
super();
this.color = c;
}
@Override
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(this.color);
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 100, 100);
}
paint(g, c);
}
}
and calling it like this:
NumberButton testbutton = new NumberButton("0");
testbutton.setUI(new RoundButtonUI(testbutton.getColor()));
edit #2: One thing that fixed is that in the action that is changing the color of the button I call:
public void changePressState(){
this.pressState = !this.pressState;
if(this.pressState) {
this.color = new Color(139, 239, 99, 166);
} else {
this.color = new Color(122, 154, 116);
}
this.number += 1;
this.setText(String.valueOf(this.number));
this.setUI(new RoundButtonUI(this.color));
}
but this is not a good solution just makes a mess so please if anybody have a better solution just tell!
The full source code is upp here to check: github