如何从JColorChooser获取颜色窗格并在我自己的窗口中使用它?



我是Java和Java的新手。

我只需要提取颜色窗格并在我自己的窗口中从该窗格中获取颜色。

基本上,我想删除默认 ColorPanel 中其他不必要的组件。 我成功地删除了其他面板和滑块。但不是更进一步。

JColorChooser

这很困难,需要一些AWT/Swing黑客(如Robot类(,但有可能。我不建议您使用此代码,但是如果需要...

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
/**
* <code>ChooserTryout</code>.
*/
public class ChooserTryout {
public static void main(String[] args) {
try {
Robot robot = new Robot();
SwingUtilities.invokeLater(() -> new ChooserTryout().startUI(robot));
} catch (AWTException e) {
e.printStackTrace();
}
}
public void startUI(Robot robot) {
JFrame frm = new JFrame("Color test");
JColorChooser chooser = new JColorChooser();
JLabel label = new JLabel("Here is your actual color");
label.setOpaque(true);
List<JComponent> comps =
getAllChildrenOfClass(chooser, JComponent.class, c -> c.getClass().getName().contains("DiagramComponent"));
JComponent c = comps.get(3);
c.setPreferredSize(new Dimension(300, 300));
c.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Point p = c.getLocationOnScreen();
p.translate(e.getX(), e.getY());
Color color = robot.getPixelColor(p.x, p.y);
System.out.println("You've clicked color: " + color);
label.setForeground(color);
};
});
frm.add(c);
frm.add(label, BorderLayout.SOUTH);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
/**
* Searches for all children of the given component which are instances of the given class and satisfies the given condition.
*
* @param aRoot start object for search. May not be null.
* @param aClass class to search. May not be null.
* @param condition condition to be satisfied. May not be null.
* @param <E> class of component.
* @return list of all children of the given component which are instances of the given class. Never null.
*/
public static <E> List<E> getAllChildrenOfClass(Container aRoot, Class<E> aClass, Predicate<E> condition) {
final List<E> result = new ArrayList<>();
final Component[] children = aRoot.getComponents();
for (final Component c : children) {
if (aClass.isInstance(c) && condition.test(aClass.cast(c))) {
result.add(aClass.cast(c));
}
if (c instanceof Container) {
result.addAll(getAllChildrenOfClass((Container) c, aClass, condition));
}
}
return result;
}
}

最新更新