यह से अपडेट के साथ Vivien Barousse द्वारा दिए गए उत्तर का एक अनुकूलित संस्करण है। इस उदाहरण में मैं स्लाइडर का उपयोग तीन स्लाइडर से आरजीबी मूल्यों को गतिशील रूप से पुनः प्राप्त करने और आयत में उस रंग को प्रदर्शित करने के लिए करता हूं। फिर विधि में हेक्स() में मैं रंग बनाने और संबंधित हेक्स रंग कोड प्रदर्शित करने के लिए मानों का उपयोग करता हूं।
इस उदाहरण में ग्रिडबैगलाउट के लिए उचित बाधाएं शामिल नहीं हैं। हालांकि कोड काम करेगा, प्रदर्शन अजीब लगेगा।
public class HexColor
{
public static void main (String[] args)
{
JSlider sRed = new JSlider(0,255,1);
JSlider sGreen = new JSlider(0,255,1);
JSlider sBlue = new JSlider(0,255,1);
JLabel hexCode = new JLabel();
JPanel myPanel = new JPanel();
GridBagLayout layout = new GridBagLayout();
JFrame frame = new JFrame();
//set frame to organize components using GridBagLayout
frame.setLayout(layout);
//create gray filled rectangle
myPanel.paintComponent();
myPanel.setBackground(Color.GRAY);
//In practice this code is replicated and applied to sGreen and sBlue.
//For the sake of brevity I only show sRed in this post.
sRed.addChangeListener(
new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e){
myPanel.setBackground(changeColor());
myPanel.repaint();
hexCode.setText(toHex());
}
}
);
//add each component to JFrame
frame.add(myPanel);
frame.add(sRed);
frame.add(sGreen);
frame.add(sBlue);
frame.add(hexCode);
} //end of main
//creates JPanel filled rectangle
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(360, 300, 10, 10);
g.fillRect(360, 300, 10, 10);
}
//changes the display color in JPanel
private Color changeColor()
{
int r = sRed.getValue();
int b = sBlue.getValue();
int g = sGreen.getValue();
Color c;
return c = new Color(r,g,b);
}
//Displays hex representation of displayed color
private String toHex()
{
Integer r = sRed.getValue();
Integer g = sGreen.getValue();
Integer b = sBlue.getValue();
Color hC;
hC = new Color(r,g,b);
String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
while(hex.length() < 6){
hex = "0" + hex;
}
hex = "Hex Code: #" + hex;
return hex;
}
}
एक विशाल दोनों विविएन और वल्कन लिए धन्यवाद। यह समाधान पूरी तरह से काम करता है और लागू करने के लिए बहुत आसान था।
हेक्साडेसिमल मान जैसी कोई चीज़ नहीं है। हेक्साडेसिमल * प्रतिनिधित्व है। * – EJP