Java根据输入更改形状的颜色

时间:2016-09-26 20:52:18

标签: java swing graphics

我有这个课,我创造了一个明星。当我运行它时,我有一个消息框,要求选择一种颜色。我希望我的明星成为那种颜色。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.GeneralPath;
import javax.swing.*;
public class Control extends JPanel{
JFrame frame = new JFrame();
String background;
final Color color = Color.getHSBColor(0.56f, 1.0f, 0.8f);
final Color red=Color.red;
final Color green=Color.GREEN;
final Color yellow=Color.YELLOW;
private final double points[][] = { 
    { 0, 85 }, { 75, 75 }, { 100, 10 }, { 125, 75 }, 
    { 200, 85 }, { 150, 125 }, { 160, 190 }, { 100, 150 }, 
    { 40, 190 }, { 50, 125 }, { 0, 85 } 
};


private void doDrawing(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                         RenderingHints.VALUE_ANTIALIAS_ON);

    g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
                         RenderingHints.VALUE_RENDER_QUALITY);
    GeneralPath star = new GeneralPath();

    star.moveTo(points[0][0], points[0][1]);

    for (int k = 1; k < points.length; k++)
        star.lineTo(points[k][0], points[k][1]);

    star.closePath();
    g2d.fill(star);  

    g2d.dispose();
}

@Override
public void paintComponent(Graphics g) {
    g.setColor(Color.MAGENTA); //should be the color of chosen button
    super.paintComponent(g);
    doDrawing(g);
}


 public void addMessage() {
    Object[] options = {"Red","Green","Yellow", "Black"};
    int n = JOptionPane.showOptionDialog(frame, "Choose a color ", "Question of a day",
            JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,
            null,options, options[2]);
    for (int i = 0; i < 4; i++) {
        if(options[i]=="Red"){
            //paint star red }
        else if(options[i]=="Green")
               //paint star ="Green"; 
        else if(options[i]=="Yellow")
            //paint star   ="Yellow"; 
    }
}

}

1 个答案:

答案 0 :(得分:0)

最简单的方法是拥有一个用户可以设置的Color对象:

Color userChosenColor;

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

然后将paintComponent中的颜色设置为:

g.setColor(userChosenColor);

或者(如果您希望它们能够选择最广泛的颜色),让它们根据红色,绿色和蓝色值设置颜色:

public void setColor(int redVal, int greenVal, int blueVal) {
    this.userChosenColor = new Color(redVal, greenVal, blueVal);
}

修改

重新阅读问题后,您似乎在询问如何将其设置为与按钮颜色相同的颜色。您可以使用button.getBackground()获取按钮的颜色。

g.setColor(button.getBackground());