我必须编写一个程序,在该程序中两次打开JColorChooser,这将允许用户选择背景色和前景色。但是,如果用户选择的颜色太相似,则程序应抛出错误消息并再次打开JColorChoosers。
我知道我必须使用VetoableChangeListener,但是我不知道如何在我的代码中实现它...
在此之前的代码下面。
帮助将不胜感激
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class jcolortest{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public jcolortest(){
prepareGUI();
}
public static void main(String[] args){
jcolortest swingControlDemo = new jcolortest();
swingControlDemo.showColorChooserDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("JColorChooser");
mainFrame.setSize(400,200);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showColorChooserDemo(){
headerLabel.setText("Test foreground text");
headerLabel.setForeground(Color.RED);
Color backgroundColor = JColorChooser.showDialog(mainFrame,
"Background Color", Color.white);
if(backgroundColor != null){
controlPanel.setBackground(backgroundColor);
mainFrame.getContentPane().setBackground(backgroundColor);
}
Color foregroundColor = JColorChooser.showDialog(mainFrame,
"Text Color", Color.white);
if(foregroundColor != Color.RED){
controlPanel.setForeground(foregroundColor);
headerLabel.setForeground(foregroundColor);
}
mainFrame.setVisible(true);
}
}
最佳答案
在这种情况下,我会适当地使用类似这样的东西:
Color foregroundColor;
do{ //loop as long as colors are similar
foregroundColor = JColorChooser.showDialog(mainFrame,
"Text Color", Color.white);
}while (isSimilar(backgroundColor, foregroundColor));
并添加方法:
public boolean isSimilar(Color background, Color foreground){
int r1 = background.getRed();
int g1 = background.getGreen();
int b1 = background.getBlue();
int r2 = foreground.getRed();
int g2 = foreground.getGreen();
int b2 = foreground.getBlue();
if((r2 >= r1+150 || r2 <= r1-150) || (g2 >= g1+150 || g2 <= g1-150) || (b2 >= b1+150 || b2 <= b1-150)){
return false; // 150 controls the "sensitivity"
}
JOptionPane.showMessageDialog(mainFrame,"Too similar color","Error",JOptionPane.INFORMATION_MESSAGE);
return true;
}
没什么花哨的,它是相当原始的,但是在一定程度上可以工作。问题在于将“灵敏度”设置为令人满意的水平。