简体   繁体   English

更改 JLabel 中图标的颜色

[英]Changing the color of an icon in a JLabel

I need to make a program that shows three buttons in a jframe along with an initially red circle.我需要制作一个程序,显示jframe中的三个按钮以及最初的红色圆圈。 The three buttons must say "RED" "GREEN", and "BLUE", and when you click the buttons, the red circle should change to whatever color you clicked on.这三个按钮必须说“红色”“绿色”和“蓝色”,当您单击按钮时,红色圆圈应变为您单击的任何颜色。

At first I tried to actually alter the color of the icon, but I thought that it would be easier just to make three circles each a different color and add an action listener to each button which will the correct color circle to the frame while replacing the previous one whenever the user clicks a color.起初我尝试实际更改图标的颜色,但我认为将三个圆圈分别设置为不同的颜色并为每个按钮添加一个动作侦听器会更容易,这将在替换框架时将正确的颜色圆圈添加到框架中每当用户单击一种颜色时,前一个。 I am having trouble figuring how to do that.我无法弄清楚如何做到这一点。 Should I make three separate classes for each circle?我应该为每个圈子制作三个单独的课程吗? Or is there an easier way?或者有没有更简单的方法?

Another thing is, I must use JLabel so I can call the repaint() method at the end of each color change that's part of the project.另一件事是,我必须使用 JLabel,这样我才能在作为项目一部分的每次颜色更改结束时调用repaint()方法。 I also need to add a static method in the main method which returns an action listener which I haven't figured out how to do yet.我还需要在 main 方法中添加一个 static 方法,该方法返回一个我还没有弄清楚该怎么做的动作监听器。

Here's what I have so far:这是我到目前为止所拥有的:

/**
 * Write a description of class CircleIcon here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class CircleIcon implements Icon
{
    // Instance variables - replace the example below with your own

    /**
     * Constructor for objects of class CircleIcon
     */
    private int size;

    public CircleIcon(int aSize)
    {
        // Initialise instance variables
        size = aSize;
    }

    public int getIconWidth() {
        return size;
    }

    public int getIconHeight() {
        return size;
    }

    public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D.Double circle = new Ellipse2D.Double(x, y, size, size);
        g2.setColor(Color.RED);
        g2.fill(circle);
    }
}

CircleIconTester class: CircleIconTester class:

/**
 * Write a description of class CircleIconTester here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.color.*;

public class CircleIconTester
{
    public static void main(String[] args) {
        JFrame frame = new JFrame();

        CircleIcon circle = new CircleIcon(50);
        JLabel label = new JLabel(circle);
        frame.add(label);

        JButton red = new JButton("RED");
        JButton blue = new JButton("BLUE");
        JButton green = new JButton("GREEN");
        frame.add(red);
        frame.add(blue);
        frame.add(green);

        ActionListener redAL = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
            }
        };

        red.addActionListener(redAL);

        frame.setLayout(new FlowLayout());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

 }

Changing the (foreground) color of a JLabel is a simple call of the setForeground(...) method on the JLabel object.更改JLabel的(前景色)颜色是对JLabel object 的setForeground(...)方法的简单调用。 But your icon implementation must get the properties of the component it is placed in. Luckily the paintIcon() method returns the parent component the icon is placed in. See the documentation of paintIcon() :但是您的图标实现必须获取它所在组件的属性。幸运的是, paintIcon()方法返回了图标所在的父组件。请参阅paintIcon()的文档

 void paintIcon(Component c, Graphics g, int x, int y)

Draw the icon at the specified location.在指定位置绘制图标。 Icon implementations may use the Component argument to get properties useful for painting, eg the foreground or background color.图标实现可以使用 Component 参数来获取对绘画有用的属性,例如前景色或背景色。

The documentation even mentions that you can use it for getting the color.文档甚至提到您可以使用它来获取颜色。 Inside your paintIcon() method you can use the getForeground() method to get the foreground color of the JLabel .在您的paintIcon()方法中,您可以使用getForeground()方法来获取JLabel的前景色。

public void paintIcon(Component c, Graphics g, int x, int y){
    Graphics2D g2 = (Graphics2D) g;
    Ellipse2D.Double circle = new Ellipse2D.Double(x, y, size, size);
    g2.setColor(c.getForeground()); // <-- get foreground color from parent.
    g2.fill(circle);
}

Now you have to set the correct foreground color in your action listener.现在你必须在你的动作监听器中设置正确的前景色。 As you want to build an action listener with a static method you can do that.当您想使用 static 方法构建动作侦听器时,您可以这样做。 Create a new static method BuildActionListener which gets two arguments.创建一个新的 static 方法BuildActionListener获得两个 arguments。 One for the JLabel object to change and one for the foreground color to use.一种用于更改JLabel object,另一种用于前景色。 It returns an ActionListener object which changes the foreground color:它返回一个改变前景色的ActionListener object:

/**
 * Build an action listener to change the color of the label.
 *
 * @param label The label to change.
 * @param color The color to use.
 * @returns The action listener which changes the color.
 */
public static ActionListener BuildActionListener(JLabel label, Color color) {
    return new ActionListener(){
        public void actionPerformed(ActionEvent event){
            label.setForeground(color);
        }
    };
}

Use this helper method to assign custom action listeners for each button:使用此辅助方法为每个按钮分配自定义操作侦听器:

red.addActionListener(BuildActionListener(label, Color.RED));
blue.addActionListener(BuildActionListener(label, Color.BLUE));
green.addActionListener(BuildActionListener(label, Color.GREEN));

And to start with an red circle (and not with a black circle), set the foreground color of the label somewhere at the beginning:从红色圆圈开始(而不是黑色圆圈),在开头的某处设置 label 的前景色:

JLabel label = new JLabel(circle);
label.setForeground(Color.RED);

Simply the code is:简单的代码是:

label.setForeground(Color.red);

Try the following.试试下面的。 It works:有用:

red.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
        label.setForeground(Color.red);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM