如何覆盖JColorChooser的重置按钮?

huangapple go评论75阅读模式
英文:

How to override JColorChooser Reset Button?

问题

在之前的帖子中,我讨论了如何覆盖预览面板,并且一切都运行得很好,但是现在出现了一个新的问题,希望它的修复也同样简单。

这个新的问题涉及到“重置”按钮。根据文档,重置按钮将会将颜色重置为最初传入的颜色。这个功能很好,但是如果存在一个次要字段呢?

以下是代码...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ColorChooserSample implements Runnable{

    public static void main(String args[]) {
        SwingUtilities.invokeLater(
                new ColorChooserSample());
    }

    private JPanel panel;
    JTextField counter;
    int vCounter = 1;
    
    @Override
    public void run() {
        JFrame frame = new JFrame(
                "JColorChooser Sample");
        frame.setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        panel.setPreferredSize(new Dimension(300, 200));
        JButton button = new JButton(
                "Pick to Change JPanel Background");
        button.addActionListener(new ColorListener());
        panel.add(button);

        frame.add(panel, BorderLayout.CENTER);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public void setJPanelBackground(Color color) {
        panel.setBackground(color);
        panel.repaint();
    }

    public class ColorListener implements 
            ActionListener, ChangeListener {

        private JColorChooser chooser;

        private JPanel previewPanel;

        @Override
        public void actionPerformed(
                ActionEvent actionEvent) {
            Color backgroundColor = showDialog(panel, 
                    "Set JPanel Background", 
                    panel.getBackground());
            setJPanelBackground(backgroundColor);
        }

        private Color showDialog(Component component, 
                String title, Color initialColor) 
                        throws HeadlessException {
            chooser = new JColorChooser(initialColor);
            chooser.getSelectionModel()
                .addChangeListener(this);

            // 配置颜色选择器面板
            previewPanel = new JPanel();
            previewPanel.setBackground(initialColor);
            JLabel label = new JLabel("Hello World!");
            counter = new JTextField("0");
            previewPanel.add(label, BorderLayout.WEST);
            previewPanel.add(counter, BorderLayout.EAST);
            chooser.setPreviewPanel(previewPanel);

            // 创建对话框
            ColorTracker ok = new ColorTracker(chooser);
            JDialog dialog = JColorChooser.createDialog(
                    component, title, true, chooser, 
                    ok, null);
            dialog.setVisible(true);
            return ok.getColor();
        }

        @Override
        public void stateChanged(ChangeEvent event) {
            Color newColor = chooser.getColor();
            previewPanel.setBackground(newColor);
            counter.setText(Integer.toString(vCounter++));
        }
    }

    private class ColorTracker implements ActionListener {

        private Color color;

        private JColorChooser chooser;

        public ColorTracker(JColorChooser chooser) {
            this.chooser = chooser;
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            color = chooser.getColor();
        }

        public Color getColor() {
            return color;
        }

    }

}

上述代码首先会打开这个对话框。

如何覆盖JColorChooser的重置按钮?

一旦点击“Pick to Change JPanel Background”按钮,它会打开一个修改过的JColorDialog,其中包括“Hello World”用于更改背景颜色,以及一个计数器用于计算颜色更改的次数。

如何覆盖JColorChooser的重置按钮?

以下显示了最后选定的颜色,但同时在文本框中显示了5,表示已点击了5次颜色选项。

如何覆盖JColorChooser的重置按钮?

点击重置按钮,颜色背景会被重置为初始状态,但计数并没有被重置为0。

如何覆盖JColorChooser的重置按钮?

你可以为确定和取消按钮分别传递监听器,但不能为重置按钮传递监听器。

这只是一个示例,因为在预览部分可能会有其他项目。目标是如何重置除颜色以外的值?

英文:

In a previous post, I discussed overriding the Preview panel and all is working well, except a new question has come forth and hoping the fix for it is as easy.

This new question pertains to the Reset button. Based on the documentation, the Reset button will reset the Colors back to the original color that was passed in. This works great, but what if there is a secondary field?

Here is the code...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ColorChooserSample implements Runnable{
public static void main(String args[]) {
SwingUtilities.invokeLater(
new ColorChooserSample());
}
private JPanel panel;
JTextField counter;
int vCounter = 1;
@Override
public void run() {
JFrame frame = new JFrame(
"JColorChooser Sample");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 200));
JButton button = new JButton(
"Pick to Change JPanel Background");
button.addActionListener(new ColorListener());
panel.add(button);
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void setJPanelBackground(Color color) {
panel.setBackground(color);
panel.repaint();
}
public class ColorListener implements 
ActionListener, ChangeListener {
private JColorChooser chooser;
private JPanel previewPanel;
@Override
public void actionPerformed(
ActionEvent actionEvent) {
Color backgroundColor = showDialog(panel, 
"Set JPanel Background", 
panel.getBackground());
setJPanelBackground(backgroundColor);
}
private Color showDialog(Component component, 
String title, Color initialColor) 
throws HeadlessException {
chooser = new JColorChooser(initialColor);
chooser.getSelectionModel()
.addChangeListener(this);
// configuring color chooser panel
previewPanel = new JPanel();
previewPanel.setBackground(initialColor);
JLabel label = new JLabel("Hello World!");
counter = new JTextField("0");
previewPanel.add(label, BorderLayout.WEST);
previewPanel.add(counter, BorderLayout.EAST);
chooser.setPreviewPanel(previewPanel);
// creating dialog
ColorTracker ok = new ColorTracker(chooser);
JDialog dialog = JColorChooser.createDialog(
component, title, true, chooser, 
ok, null);
dialog.setVisible(true);
return ok.getColor();
}
@Override
public void stateChanged(ChangeEvent event) {
Color newColor = chooser.getColor();
previewPanel.setBackground(newColor);
counter.setText(Integer.toString(vCounter++));
}
}
private class ColorTracker implements ActionListener {
private Color color;
private JColorChooser chooser;
public ColorTracker(JColorChooser chooser) {
this.chooser = chooser;
}
@Override
public void actionPerformed(ActionEvent event) {
color = chooser.getColor();
}
public Color getColor() {
return color;
}
}
}

The above code will first open this dialog.

如何覆盖JColorChooser的重置按钮?

Once the "Pick to Change JPanelBackground" button is clicked, it opens the JColorDialog with a modified Preview section. This section includes "Hello World" that will change background colors and a counter to count how many times the color has changed.

如何覆盖JColorChooser的重置按钮?

The following shows the last color selected but also shows 5 in the Textbox to signify that there were 5 color options clicked.

如何覆盖JColorChooser的重置按钮?

Click the reset button and the color background is set to the original, but the count was NOT reset back to 0.

如何覆盖JColorChooser的重置按钮?

You can pass in a Listener for both the OK and Cancel button but not the Reset button.

This is only an example, as there could be other items in the Preview section. The objective is how can the values other than Color be reset?

答案1

得分: 1

reset按钮所做的唯一事情就是调用chooserPane.setColor(initialColor)。所以,如果你真正需要监听颜色变化,你可以通过以下方式实现:

chooser.getSelectionModel().addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent e) {
        Color newColor = chooser.getColor();
        previewPanel.setBackground(newColor);
        counter.setText(Integer.toString(vCounter++));
    }
});

这样你的次要面板就会得到更新。

话虽如此,如果你真的想要向按钮添加监听器,没有公开的方法可以直接访问它 - 你需要迭代所有的组件,直到找到按钮,然后给它添加一个监听器。

编辑
好的,所以它必须是重置按钮。由于它是某个创建内容的方法的局部变量,你需要进行精确删除。只需将new JButton("abc")更改为你自己的按钮,附带你自己的监听器(s)。

Locale locale = dialog.getLocale();
String resetString = UIManager.getString("ColorChooser.resetText", locale);

Container contentPane = dialog.getContentPane();
JPanel buttonPanel = null;
for (Component c : contentPane.getComponents()) {
    if (c instanceof JPanel) {
        buttonPanel = (JPanel) c;
    }
}

JButton resetButton = null;
if (buttonPanel != null) {
    for (Component b : buttonPanel.getComponents()) {
        if (b instanceof JButton) {
            JButton button = (JButton) b;
            if (resetString.equals(button.getText())) {
                resetButton = button;
                break;
            }
        }
    }
    if (resetButton != null) {
        buttonPanel.remove(resetButton);
        buttonPanel.add(new JButton("abc"));
    }
}
英文:

The only thing done by reset button is calling chooserPane.setColor(initialColor). So if what you really need is listening to color changes, you might do just that, by something like:

        chooser.getSelectionModel().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
Color newColor = chooser.getColor();
previewPanel.setBackground(newColor);
counter.setText(Integer.toString(vCounter++));
}
});

And your secondary panel gets updated.

Having said that, if you really want to add a listener to the button, there's no exposed way of accessing it - you need to iterate the components all the way down until you find the button, and then add a listener to it.

EDIT
Alright, so it has to be the reset button. Since that's a local variable of some content creating method, it has to be removed surgically. Just change new JButton("abc") to your own button, with your own listener(s).

        Locale locale = dialog.getLocale();
String resetString = UIManager.getString("ColorChooser.resetText", locale);
Container contentPane = dialog.getContentPane();
JPanel buttonPanel = null;
for (Component c : contentPane.getComponents()) {
if (c instanceof JPanel) {
buttonPanel = (JPanel) c;
}
}
JButton resetButton = null;
if (buttonPanel != null) {
for (Component b : buttonPanel.getComponents()) {
if (b instanceof JButton) {
JButton button = (JButton) b;
if (resetString.equals(button.getText())) {
resetButton = button;
break;
}
}
}
if (resetButton != null) {
buttonPanel.remove(resetButton);
buttonPanel.add(new JButton("abc"));
}
}

huangapple
  • 本文由 发表于 2020年5月30日 02:43:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/62092716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定