【发布时间】:2011-07-14 12:18:46
【问题描述】:
我有一个 JPanel 允许用户使用这些组件设置对象的颜色:
- 文本字段 (R)
- 文本字段 (G)
- 文本字段 (B)
滑块(不透明度 1-100)
按钮(使用上述元素的值预览颜色)
我要问的是为什么按钮可以正确获取颜色而不是不透明度。
这是我的代码:
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);
}
}
}
我在一个事件中为所有文本字段设置按钮的颜色,为滑块设置另一个事件:
// 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());
}
我对其进行了调试,发现取自 getColor() 的颜色仅返回不带不透明度的 rgb 值,但是当我将 getColor() 与其他自定义组件一起使用时,它可以工作(rgb + 不透明度)。
感谢帮助
编辑
找到解决方案:
// on mousedragged and mouseclicked
private void slider_value(java.awt.event.MouseEvent evt) {
lOpacity.setText(sOpacity.getValue() + "");
bColor.setBackground(getColor());
bColor.getParent().repaint(); <------
}
【问题讨论】:
-
很高兴您解决了自己的问题。但是这个问题非常复杂,因此很难回答。将来,请调整您的问题,以便其他人能够理解手头的问题。