我有一个颜色选择器应用程序,它使用JSlider来显示RGB值。我想让它也显示十六进制值。有人可以指点我正确的方向吗?我希望在面板右侧出现的颜色框下显示十六进制值。
/*
* Program: ColorSlider.java
* Descrip: Using JSlider and BoxLayout
*/
package colorslider;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class ColorSlider
{
static JPanel controls, colorPanel;
static JSlider rSlider, gSlider, bSlider;
static JLabel rLabel, gLabel, bLabel;
public static void main(String[] args)
{
JFrame win = new JFrame("Color Chooser");
win.setDefaultCloseOperation(3);
win.add(new SlideColorPanel());
win.pack();
win.setResizable(false);
win.setVisible(true);
}
static class SlideColorPanel extends JPanel
{
public SlideColorPanel()
{
rSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
rSlider.setMajorTickSpacing(50);
rSlider.setMinorTickSpacing(10);
rSlider.setPaintTicks(true);
rSlider.setPaintLabels(true);
rSlider.setAlignmentX(LEFT_ALIGNMENT);
gSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
gSlider.setMajorTickSpacing(50);
gSlider.setMinorTickSpacing(10);
gSlider.setPaintTicks(true);
gSlider.setPaintLabels(true);
gSlider.setAlignmentX(LEFT_ALIGNMENT);
bSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
bSlider.setMajorTickSpacing(50);
bSlider.setMinorTickSpacing(10);
bSlider.setPaintTicks(true);
bSlider.setPaintLabels(true);
bSlider.setAlignmentX(LEFT_ALIGNMENT);
SliderListener listener = new SliderListener();
rSlider.addChangeListener(listener);
gSlider.addChangeListener(listener);
bSlider.addChangeListener(listener);
rLabel = new JLabel("Red: 0");
rLabel.setAlignmentX(LEFT_ALIGNMENT);
gLabel = new JLabel("Green: 0");
gLabel.setAlignmentX(LEFT_ALIGNMENT);
bLabel = new JLabel("Blue: 0");
bLabel.setAlignmentX(LEFT_ALIGNMENT);
controls = new JPanel();
BoxLayout layout = new BoxLayout(controls, BoxLayout.Y_AXIS);
controls.setLayout(layout);
controls.add(rLabel);
controls.add(rSlider);
controls.add(Box.createRigidArea(new Dimension(0,20)));
controls.add(gLabel);
controls.add(gSlider);
controls.add(Box.createRigidArea(new Dimension(0,20)));
controls.add(bLabel);
controls.add(bSlider);
controls.add(Box.createRigidArea(new Dimension(0,20)));
colorPanel = new JPanel();
colorPanel.setPreferredSize(new Dimension(100,100));
colorPanel.setBackground(Color.black);
add(controls);
add(colorPanel);
}
}
static class SliderListener implements ChangeListener
{
private int red, green, blue;
@Override
public void stateChanged(ChangeEvent e)
{
red = rSlider.getValue();
green = gSlider.getValue();
blue = bSlider.getValue();
rLabel.setText("Red: " + red);
gLabel.setText("Green: " + green);
bLabel.setText("Blue: " + blue);
colorPanel.setBackground(new Color(red, green, blue));
}
}
}
答案 0 :(得分:1)
您可以使用以下命令将int值转换为十六进制值:
String hex = Integer.toHexString(...);
您可以为每个单独的值执行此操作。
或者,如果您只需要整个Color的一个十六进制值,那么您需要使用Color
方法获取getRGB(...)
对象的int值。在这种情况下,十六进制值将包含alpha值,因此您可能希望忽略前两个字符。