У меня есть JPanel, чтобы позволить пользователю установить цвет объекта с этими компонентами:
Я спрашиваю, почему кнопка получает цвет правильно, а не непрозрачность.
Вот мой код:
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(); <------
}