I have a JPanel to allow the user to set the color of an object with these components:
- TextField (R)
- TextField (G)
- TextField (B)
Slider (Opacity 1-100)
开发者_运维技巧Button (preview of color using values from above elements)
What I'm asking is why the button get the color correctly but not the opacity.
Here's my code:public Color getColor() {
if (tfRed.getText().equals("") || tfGreen.getText().equals("") || tfBlue.getText().equals("")) {
return new Color(0, 0, 0, 0);
} else {
if (tfRed.getText().matches("\\d+") && tfGreen.getText().matches("\\d+") && tfBlue.getText().matches("\\d+")
&& Integer.parseInt(tfRed.getText()) <= 255 && Integer.parseInt(tfGreen.getText()) <= 255 && Integer.parseInt(tfBlue.getText()) <= 255
&& Integer.parseInt(tfRed.getText()) >= 0 && Integer.parseInt(tfGreen.getText()) >= 0 && Integer.parseInt(tfBlue.getText()) >= 0) {
return new Color(
Float.parseFloat(tfRed.getText()) / 255,
Float.parseFloat(tfGreen.getText()) / 255,
Float.parseFloat(tfBlue.getText()) / 255,
Float.parseFloat(sOpacity.getValue() + "") / 100
);
} else {
JOptionPane.showMessageDialog(this, "Invalid rgb value");
tfRed.setText("0");
tfGreen.setText("0");
tfBlue.setText("0");
return new Color(0, 0, 0, 0);
}
}
}
I set the color of the button in a single event for all textfield and another event for the slider:
// on keyup
private void button_color(java.awt.event.KeyEvent evt) {
bColor.setBackground(getColor());
}
// on mousedragged and mouseclicked
private void slider_value(java.awt.event.MouseEvent evt) {
lOpacity.setText(sOpacity.getValue() + "");
bColor.setBackground(getColor());
}
I debugged it and I saw that the color taken from getColor()
returns only rgb values w/o opacity, but when I use getColor()
with other custom components it works (rgb + opacity).
Thanks for help
EDIT
Found solution:
// on mousedragged and mouseclicked
private void slider_value(java.awt.event.MouseEvent evt) {
lOpacity.setText(sOpacity.getValue() + "");
bColor.setBackground(getColor());
bColor.getParent().repaint(); <------
}
I do not think setting button's background color is useful, JButton's background color set by look and feel, it's hard to change the button's color, use JLabel instead
精彩评论