可以在单个 JFrame 中的项目上使用多种颜色吗?

Can multiple colors be used on items in a single JFrame?

我正在学习使用 swing 创建用户界面。目前,我有这个 JFrame,我需要在其中放置一个形状并提供移动该形状的方法。我称形状对象为机器人。

我想画一些比一个红色方块更有创意的东西。我已经想出如何添加多个形状,但它们仍然是相同的颜色。如何在这个 JFrame 上使用多种颜色?

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

    frame.setSize(400,400);
    frame.setTitle("SwingBot");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Robot r = new Robot();

    frame.add(r);

    frame.setVisible(true);

    Scanner in = new Scanner(System.in);
    boolean repeat = true;
    System.out.println();
    while (repeat)
    {
        String str = in.next();
        String direc = str.toLowerCase();
        if (direc.equals("right"))
        {
            r.moveBot(10,0);
        }
        else if (direc.equals("left"))
        {
            r.moveBot(-10,0);
        }
        else if (direc.equals("up"))
        {
            r.moveBot(0,-10);
        }
        else if (direc.equals("down"))
        {
            r.moveBot(0,10);
        }
        else if (direc.equals("exit"))
        {
            repeat = false;
        }
    }

}


public static class Robot extends JComponent
{
    private Rectangle rect = new Rectangle(10,10);

    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;

        g2.setColor(Color.RED);

        g2.fill(rect);
    }

    public void moveBot(int x, int y)
    {
        rect.translate(x,y);

        repaint();
    }

}

}

您需要在每次绘制新组件时使用 Graphics 对象的新 Color 调用 setColor 方法。

public void paintComponent(Graphics g)
{
    Graphics2D g2 = (Graphics2D) g;

    g2.setColor(Color.RED);
    g2.fillRect(...);

    g2.setColor(Color.BLACK);
    g2.fillOval(...)
}

您可以拨打:

g.setColor(your color here);

在用另一种颜色绘制形状之前。

示例

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.setColor(Color.RED);
    g.fillRect(0, 0, 100, 100);   //Fill a Red Rectangle

    g.setColor(Color.YELLOW);
    g.fillOval(20, 20, 50, 50);   //Fill a Yellow Circle
}

您可能还想在 paintComponent() 方法中调用 super.paintComponent(g) 以防止视觉失真。

您可以为您的机器人 class 提供一个颜色属性,您可以在调用 moveBot 之前更改该属性。

类似于:

public static class Robot extends JComponent{
    private Rectangle rect = new Rectangle(10,10);
    private Color col = Color.RED;

    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;

        g2.setColor(col);
        g2.fill(rect);
    }

    public void setColor(Color c){
       col = c;
    }

    public void moveBot(int x, int y)
    {
        rect.translate(x,y);

        repaint();
    }
}