我有一個JPanel,以允許用戶設置的對象的顏色與這些組件:JButton的背景顏色從滑塊
- TextField的(R)
- TextField的(G)
- 的TextField(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值w/o不透明度,但當我使用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(); <------
}
我很高興你解決了你的o問題。但是這個問題非常複雜,因此很難回答。在將來,要調整你的問題,讓其他人能夠理解手頭的問題。 – mre