gpt4 book ai didi

java - 来自 slider 的 JButton 背景颜色

转载 作者:行者123 更新时间:2023-11-30 11:52:45 24 4
gpt4 key购买 nike

我有一个 JPanel 允许用户使用这些组件设置对象的颜色:

  • 文本字段 (R)
  • 文本字段 (G)
  • 文本字段 (B)
  • slider (不透明度 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);
}
}
}

我在单个事件中为所有文本字段设置按钮的颜色,为 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());
}

我调试了它,我看到从 getColor() 中获取的颜色只返回没有不透明度的 rgb 值,但是当我将 getColor() 与其他自定义一起使用时它工作的组件(rgb + opacity)。感谢帮助

编辑

找到解决方案:

// on mousedragged and mouseclicked
private void slider_value(java.awt.event.MouseEvent evt) {
lOpacity.setText(sOpacity.getValue() + "");
bColor.setBackground(getColor());
bColor.getParent().repaint(); <------
}

最佳答案

我认为设置按钮的背景颜色没有用,JButton 的背景颜色是通过外观设置的,很难更改按钮的颜色,请改用JLabel

关于java - 来自 slider 的 JButton 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6693002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com