有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

来自滑块的java JButton背景色

我有一个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();  <------
}

共 (0) 个答案