Search code examples
javaswingjava.util.scannerpaintcomponent

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


I am learning to use swing to create user interfaces. Currently, I have this JFrame and I need to place a shape inside it and provide methods to move the shape. I call the shape object Robot.

I want to draw something more creative than just a single red square. I have figured out how to add multiple shapes, but they are still all the same color. How can I use more than one color on this single 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();
    }

}

}


Solution

  • What you need is call the setColor method with a new Color of your Graphics object each time you paint a new component.

    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;
    
        g2.setColor(Color.RED);
        g2.fillRect(...);
    
        g2.setColor(Color.BLACK);
        g2.fillOval(...)
    }