当前位置: 首页 > 知识库问答 >
问题:

创建颜色选择器JSlider来影响矩形的填充颜色

爱刚捷
2023-03-14

任务是创建一个颜色选择器。为什么当我移动滑块时,颜色没有改变?我必须使用jslider来影响矩形的填充颜色。

最初的请求是:

(创建颜色选择器)声明JPanel的一个子类,称为MyColorChooser,它提供三个JSlider对象和三个JTextField对象。每个JSlider表示颜色的红色、绿色和蓝色部分的值从0到255。使用这些值作为Color构造函数的参数来创建新的Color对象。在相应的JTextField中显示每个JSlider的当前值。当用户更改JSlider的值时,JTextField也应相应更改。使用新的GUI组件作为应用程序的一部分,该应用程序通过绘制填充矩形来显示当前color值。

package creatingacolorchooser;

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 *
 * @author ian20
 */
public class MyColorChooser extends JPanel
{
    private JLabel redLabel;
    private JLabel greenLabel;
    private JLabel blueLabel;
    private JTextField redText;
    private JTextField greenText;
    private JTextField blueText;
    private JSlider redSlider;
    private JSlider greenSlider;
    private JSlider blueSlider;


   /**
    * Constructor
     */
    public MyColorChooser()
    {        
    //Create FlowLayout manager.
    setLayout(new FlowLayout());

    //Create message Labels
    redLabel = new JLabel("Red: ");
    greenLabel = new JLabel("Green: ");
    blueLabel = new JLabel("Blue: ");

    //Create read only text fields.
    redText = new JTextField("0", 5);
    greenText = new JTextField("0", 5);
    blueText = new JTextField("0", 5);

    //Create JSlider
    redSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
    redSlider.setPreferredSize(new Dimension(1000,75));
    redSlider.setMajorTickSpacing(10);
    redSlider.setMinorTickSpacing(1);
    redSlider.setPaintTicks(true);
    redSlider.setPaintLabels(true);
    redSlider.addChangeListener(new RedSlideListener());

    greenSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
    greenSlider.setPreferredSize(new Dimension(1000,75));
    greenSlider.setMajorTickSpacing(10);
    greenSlider.setMinorTickSpacing(1);
    greenSlider.setPaintTicks(true);
    greenSlider.setPaintLabels(true);
    greenSlider.addChangeListener(new GreenSlideListener());

    blueSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
    blueSlider.setPreferredSize(new Dimension(1000,75));
    blueSlider.setMajorTickSpacing(10);
    blueSlider.setMinorTickSpacing(1);
    blueSlider.setPaintTicks(true);
    blueSlider.setPaintLabels(true);
    blueSlider.addChangeListener(new BlueSlideListener());

    //
    add(redLabel);
    add(redSlider);
    add(redText);
    add(greenLabel);
    add(greenSlider);
    add(greenText);
    add(blueLabel);
    add(blueSlider);
    add(blueText);        
    }

    /**
     * Private inner class to handle the the change events that are 
     *  generated when the slider is moved 
     */
private class RedSlideListener implements ChangeListener
{
    public void stateChanged(ChangeEvent e)
    {
        int redInt;

        //get slider value
        redInt = redSlider.getValue();

        //Create object and set value.
        RectPanel rp = new  RectPanel();
        rp.setRed(redInt = redSlider.getValue());

        //Display slider value in text field.
        redText.setText(Integer.toString(redInt));
    }
}

/**
 * Private inner class to handle the the change events that are generated 
 * when the slider is moved 
 */
private class GreenSlideListener implements ChangeListener
{
    public void stateChanged(ChangeEvent e)
    {
        int greenInt;

        //get slider value
        greenInt = greenSlider.getValue();

        //Create object and set value.
        RectPanel rp = new  RectPanel();
        rp.setGreen(greenInt = greenSlider.getValue());

        //Display slider value in text field.
        greenText.setText(Integer.toString(greenInt));
    }
}

/**
 * Private inner class to handle the the change events that are generated 
 * when the slider is moved 
 */
private class BlueSlideListener implements ChangeListener
{
    public void stateChanged(ChangeEvent e)
    {
        int blueInt;

        //get slider value
        blueInt = blueSlider.getValue();

        //Create object and set value.
        RectPanel rp = new  RectPanel();
        rp.setBlue(blueInt = blueSlider.getValue());

        //Display slider value in text field.
        blueText.setText(Integer.toString(blueInt));
    }
   }
}


enter code here                

            package creatingacolorchooser;
            import java.awt.Color;
            import javax.swing.*;
            import java.awt.Graphics;

            /**
             *
             * @author ian20
             */
            public class RectPanel extends JPanel
            {
                private int red;
                private int blue;
                private int green;

                /**
                 * The setRed method sets int red to a int value.
                 * @param r 
                 */
                public void setRed(int r)
                {
                    red = r;
                }

                /**
                 * The setBlue method sets int blue to a int value.
                 * @param r 
                 */
                public void setBlue(int b)
                {
                    blue = b;
                }

                /**
                 * The setGreen method sets int Green to a int value.
                 * @param r 
                 */
                public void setGreen(int g)
                {
                    green = g;
                }

                /**
                 * The getRed method returns int value called red.
                 * @return 
                 */
                public int getRed()
                {
                    return red;
                }

                /**
                 * The getBlue method returns int value called blue.
                 * @return 
                 */
                public int getBlue()
                {
                    return blue;
                }

                /**
                 * The getGreen method returns int value called blue.
                 * @return 
                 */
                public int getGreen()
                {
                    return green;
                }

                @Override
                public void paintComponent(Graphics g) 
                {
                    super.paintComponent(g);

                    RectPanel rp = new RectPanel();

                    g.setColor(new Color(rp.getRed(),rp.getBlue(),rp.getGreen()));
                    g.fillRect(475, 50, 200, 200);
                }
            }


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package creatingacolorchooser;
import java.awt.GridLayout;
import javax.swing.JFrame;

/**
 *
 * @author ian20
 */
public class MainColor 
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Change Rectangle Color");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        RectPanel rect = new RectPanel();
        rect.repaint();

        MyColorChooser mcc = new MyColorChooser();
        frame.setLayout(new GridLayout(2, 1));
        frame.add(rect);
        frame.add(mcc);
        frame.setSize(1150, 600);
        frame.setVisible(true);        
    }
}

代码中唯一不按我想要的方式工作的部分是滑块不影响setcolor

我改变了周围的东西,它似乎工作,任何意见都将不胜感激。

    /*
     * Class MyColorChooser holds sliders affecting text fields, labels, and a 
     * graphic affected by the position of the sliders.
     */
    package creatingacolorchooser;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.*;
    import java.awt.Graphics;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;

    /**
     *
     * @author ian20
     */
    public class MyColorChooser extends JPanel
    {
        private int red;              //Holds int value as red.
        private int green;            //Holds int value as green.
        private int blue;             //Holds int value as blue.  
        private JLabel redLabel;      //Holds red color label
        private JLabel greenLabel;    //Holds blue color label
        private JLabel blueLabel;     //Holds green color label
        private JTextField redText;   //Holds numerical value of red colod
        private JTextField greenText; //Holds numerical value of green colod
        private JTextField blueText;  //Holds numerical value of blue colod
        private JSlider redSlider;    //Holds the red JSlider
        private JSlider greenSlider;  //Holds the green JSlider
        private JSlider blueSlider;   //Holds the blue JSlider

        public MyColorChooser()
        {
            //Create layout
            setLayout(new FlowLayout());

            //Create labels
            redLabel = new JLabel("Red: ");
            greenLabel = new JLabel("Green: ");
            blueLabel = new JLabel("Blue: ");

            //Create read only text fields.
            redText = new JTextField("0", 5);
            redText.setEditable(false);
            greenText = new JTextField("0", 5);
            greenText.setEditable(false);
            blueText = new JTextField("0", 5);
            blueText.setEditable(false);

            //Create JSlider
            redSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
            redSlider.setPreferredSize(new Dimension(1000,75));
            redSlider.setMajorTickSpacing(10);
            redSlider.setMinorTickSpacing(1);
            redSlider.setPaintTicks(true);
            redSlider.setPaintLabels(true);
            redSlider.addChangeListener(new ColorSlideListener());

            greenSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
            greenSlider.setPreferredSize(new Dimension(1000,75));
            greenSlider.setMajorTickSpacing(10);
            greenSlider.setMinorTickSpacing(1);
            greenSlider.setPaintTicks(true);
            greenSlider.setPaintLabels(true);
            greenSlider.addChangeListener(new ColorSlideListener());

            blueSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
            blueSlider.setPreferredSize(new Dimension(1000,75));
            blueSlider.setMajorTickSpacing(10);
            blueSlider.setMinorTickSpacing(1);
            blueSlider.setPaintTicks(true);
            blueSlider.setPaintLabels(true);
            blueSlider.addChangeListener(new ColorSlideListener());

            //Add components to the panel        
            add(redLabel);
            add(redSlider);
            add(redText);
            add(greenLabel);
            add(greenSlider);
            add(greenText);
            add(blueLabel);
            add(blueSlider);
            add(blueText);
        }

        /**
         * Private inner class to handle the the change events that are generated 
         * when the slider is moved 
         */
        private class ColorSlideListener implements ChangeListener
        {
            public void stateChanged(ChangeEvent e)
            {   
                //get slider value
                red = redSlider.getValue();
                green = greenSlider.getValue();
                blue = blueSlider.getValue();            

                //Display slider value in text field.
                redText.setText(Integer.toString(red));
                greenText.setText(Integer.toString(green));
                blueText.setText(Integer.toString(blue));

                //Set rectangle color.
                repaint();
            }
        }
        /**
         * The paintComponent creates a rectangle with adjustable coloring
         * @param g 
         */
        @Override
        public void paintComponent(Graphics g) 
        {
            super.paintComponent(g);

            g.setColor(new Color(red, green, blue));
            g.fillRect(420, 300, 300, 100);
        }
    }


    /*
     * The MainColor creates the GUI for the Selected RectPanel application.
     */
    package creatingacolorchooser;
    import java.awt.GridLayout;
    import javax.swing.JFrame;

    /**
     *
     * @author ian20
     */
    public class MainColor 
    {
        public static void main(String[] args)
        {
            //Create frame object
            JFrame frame = new JFrame("Change Rectangle Color");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            //Create rect object
            MyColorChooser mcc = new MyColorChooser();

            //Add to the frame, set layout, set size, and make it viable.
            frame.setLayout(new GridLayout(1, 1));
            frame.add(mcc);
            frame.setSize(1150, 500);
            frame.setVisible(true);        
        }
    }

共有1个答案

澹台冯浩
2023-03-14

这没有任何用处:

RectPanel rp = new  RectPanel();
rp.setRed(redInt = redSlider.getValue());

当您创建一个新的JPanel时,更改它的属性并不显示它。相反,您应该更改已经显示的RectPanel JPanel的状态,而不是创建新的RectPanel JPanel。这意味着对JPanel的who color将被更改的引用必须传递到您的颜色选择器对象中,以便可以更改其状态(颜色)。

另外,您不应该在paintComponent方法中创建RectPanel。

ColorSliderPanel的部分内容如下所示:

public class ColorSliderPanel extends JPanel {
    private static final int MAX_COLOR = 255;
    private Color color;
    private JSlider slider = new JSlider(0, MAX_COLOR, 0);
    private JTextField textField = new JTextField("0", 5);
    private MyColorPanel myColorPanel;

    // here is the key, my constructor takes MyColorPanel reference
    public ColorSliderPanel(String text, Color color, MyColorPanel myColorPanel) {
        this.color = color;
        this.myColorPanel = myColorPanel;  // and then sets the field of the class

        slider.setMajorTickSpacing(20);
        slider.setMinorTickSpacing(1);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.addChangeListener(new SliderListener());

        // .....

        setBorder(BorderFactory.createTitledBorder(text)); 

        // .....

    }

    private class SliderListener implements ChangeListener {
        @Override
        public void stateChanged(ChangeEvent cEvt) {
            int newValue = slider.getValue();

            // call getColor() on the original MyColorPanel object
            Color origClr = myColorPanel.getColor(); // get the original color
            textField.setText("" + newValue);

            // here we decide what the new color's r,g,b should be----

            // ......

            Color newColor = new Color(r, g, b);

            // set the color of the original MyColorPanel object
            myColorPanel.setColor(newColor);
        }
    }
}

MyColorPanel的部分。注意,我给它提供了getcolor()setcolor(Color Color)方法,但是如果您愿意,您可以使用单独的红/蓝/绿getters/setters:

public class MyColorPanel extends JPanel {
    private static final Color INIT_COLOR = Color.BLACK;
    private static final int RECT_WIDTH = 200;
    private Color color = INIT_COLOR;

    // ...

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(color);
        int rectX = (getWidth() - RECT_WIDTH) / 2;
        int rectY = (getHeight() - RECT_WIDTH) / 2;
        g.fillRect(rectX, rectY, RECT_WIDTH, RECT_WIDTH);
    }
}   

主GUI像这样将所有东西连接在一起:

public class MyColorFoo extends JPanel {
    private MyColorPanel myColorPanel = new MyColorPanel(1000, 400);

    public MyColorFoo() {
        JPanel slidersPanel = new JPanel(new GridLayout(0, 1, 3, 3));
        slidersPanel.add(new ColorSliderPanel("Red", Color.RED, myColorPanel));
        slidersPanel.add(new ColorSliderPanel("Green", Color.GREEN, myColorPanel));
        slidersPanel.add(new ColorSliderPanel("Blue", Color.BLUE, myColorPanel));

        setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
        setLayout(new BorderLayout(3, 3));
        add(myColorPanel, BorderLayout.CENTER);
        add(slidersPanel, BorderLayout.PAGE_END);
    }
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.*;
import javax.swing.event.ChangeListener;

@SuppressWarnings("serial")
public class ColorExample extends JPanel {
    private ColorSliderPanel[] sliders = { 
            new ColorSliderPanel(Color.RED, "Red"),
            new ColorSliderPanel(Color.GREEN, "Green"), 
            new ColorSliderPanel(Color.BLUE, "Blue") };
    private JPanel colorPanel = new JPanel();

    public ColorExample() {
        JPanel sliderPanel = new JPanel(new GridLayout(0, 1));
        for (ColorSliderPanel colorSliderPanel : sliders) {
            sliderPanel.add(colorSliderPanel);
            colorSliderPanel.addListener(evt -> setColorPanelBackground());
        }

        colorPanel.setPreferredSize(new Dimension(600, 300));
        setLayout(new GridLayout(0, 1));
        add(colorPanel);
        add(sliderPanel);
        setColorPanelBackground();
    }

    private void setColorPanelBackground() {
        int rgb = 0;
        for (ColorSliderPanel colorSliderPanel : sliders) {
            Color c = colorSliderPanel.getColor();
            int value = colorSliderPanel.getValue();

            // numeric magic here:
            rgb |= value * (0x10101 & c.getRGB());
        }
        colorPanel.setBackground(new Color(rgb));
    }

    private static void createAndShowGui() {
        ColorExample mainPanel = new ColorExample();

        JFrame frame = new JFrame("Color Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
@SuppressWarnings("serial")
class ColorSliderPanel extends JPanel {
    private final static int MAX_VALUE = 255;
    private Color color;
    private String text;
    private JSlider slider = new JSlider(0, MAX_VALUE, MAX_VALUE / 2);

    public ColorSliderPanel(Color color, String text) {
        this.color = color;
        this.text = text;
        setBackground(color);

        // lighter color
        int colorInt = color.getRGB() | 0x7f7f7f;
        slider.setBackground(new Color(colorInt));
        slider.setMajorTickSpacing(50);
        slider.setMinorTickSpacing(5);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);

        setLayout(new BorderLayout());
        add(slider);
        setBorder(BorderFactory.createTitledBorder(text));
    }

    public Color getColor() {
        return color;
    }

    public String getText() {
        return text;
    }

    public int getValue() {
        return slider.getValue();
    }

    public void addListener(ChangeListener listener) {
        slider.addChangeListener(listener);
    }

}
 类似资料:
  • 我按照ItextSharp的示例获取图形结构,并使用以下代码获取矩形坐标: 我尝试了renderInfo.getfillColor();但是没有这样的方法。 我想获得额外的矩形属性: 像矩形填充颜色,(一些类似于html中的DIV style=“background:blue;border:black;”标签)我如何获得它?

  • 艺术离不开色彩,今天咱们来介绍一下填充颜色,体会一下色彩的魅力。 填充颜色主要分为两种: 基本颜色 渐变颜色(又分为线性渐变与径向渐变) 我们一个个来看。 填充基本颜色 Canvas fillStyle属性用来设置画布上形状的基本颜色和填充。fillStyle使用简单的颜色名称。这看起来非常简单,例如: context.fillStyle = "red"; 下面是出自 HTML4 规范的可用颜色

  • 颜色字段存储一个字符串作为其值,并存储一个字符串作为其文本。 它的值是格式为#rrggbb的字符串,而其文本也可以是格式为#rgb的字符串。 颜色字段 打开编辑器的颜色字段 压缩的颜色字段 新建 { "type": "example_colour", "message0": "colour: %1", "args0": [ { "type": "field_colo

  • 用于颜色选择,支持多种格式。 基础用法 使用 v-model 与 Vue 实例中的一个变量进行双向绑定,绑定的变量需要是字符串类型。 <div class="block"> <span class="demonstration">有默认值</span> <el-color-picker v-model="color1"></el-color-picker> </div> <div clas

  • ColorPicker 颜色选择器 用于颜色选择,支持多种格式。 基础用法 :::demo 通过value属性控制当前显示的颜色。 render() { const color1 = '#20a0ff'; const color2 = null; return ( <div> <div className="block"> <span classNa

  • ColorPicker 颜色选择器 用于颜色选择,支持多种格式。 基础用法 使用 v-model 与 Vue 实例中的一个变量进行双向绑定,绑定的变量需要是字符串类型。 <div class="block"> <span class="demonstration">有默认值</span> <el-color-picker v-model="color1"></el-color-picker