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

时间:2015-09-20 19:23:43

标签: java swing java.util.scanner paintcomponent

我正在学习使用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();
    }

}

}

3 个答案:

答案 0 :(得分:2)

您可以致电:

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)以防止出现视觉瑕疵。

答案 1 :(得分:1)

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

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

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

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

答案 2 :(得分:1)

您可以为Robot类提供Color属性,您可以在调用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();
    }
}