Skip to content
Advertisement

change color of already drawn Graphics object in java AWT not working

Am trying to change color after drawing the object in window, this is what i came up with, am a beginner so this is messy.

import java.awt.*;
import java.awt.event.*;
import java.awt.event.WindowEvent;
import java.util.Arrays;
import java.util.List;
public class TestGraphic extends Figure {

TestGraphic(){
    setSize(600,600);
    closeFrame();
}

public static void main(String[] args) {
    TestGraphic test = new TestGraphic();
    test.setVisible(true);

}
public void paint(Graphics gui) {
    drawComponent(gui);
    
}
public void drawComponent(Graphics gui) {
     gui.drawOval(108,110,200,200);
     gui.drawOval(160,150,20,20);
     gui.drawOval(240,150,20,20);
     gui.drawRect(160,220,100,40);
     Button btn = new Button("Change color");
     btn.setBounds(30,100,80,30);
     add(btn);
     changeColor(gui,btn);
    
     
}
@Override
void draw(Graphics gui) {
    // TODO Auto-generated method stub
    
}
@Override
public boolean contains(int x, int y) {
      
      return false;
}
 private void closeFrame(){
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
 }
 

 void changeColor(Graphics gui,Button btn) {
     List<Color> colorList;
     colorList = Arrays.asList(Color.black, Color.blue , Color.cyan, Color.red, Color.green, Color.magenta, Color.orange, Color.yellow);
      
      btn.addActionListener(new ActionListener() { 
             public void actionPerformed (ActionEvent e) {  
                 for(int i = 0;i < colorList.size(); i++) {
                    gui.setColor(colorList.get(i));
                }
                  }    
              }); 
     
    
}

}

The class Figure is an abstract class that is inheriting from java.awt.Frame Any remarks about how to make this code cleaner will be appreciated, thanks.

Advertisement

Answer

Before you begin on something as complex as custom painting, make sure you have a firm understanding of the basics of the language and the APIs

See Creating a GUI With Swing, Performing Custom Painting and Painting in AWT and Swing for more details.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Color desiredColor = Color.BLACK;
        private List<Color> avaliableColors = new ArrayList<>(16);

        public TestPane() {
            setLayout(new BorderLayout());
            avaliableColors.add(Color.BLACK);
            avaliableColors.add(Color.BLUE);
            avaliableColors.add(Color.CYAN);
            avaliableColors.add(Color.DARK_GRAY);
            avaliableColors.add(Color.GRAY);
            avaliableColors.add(Color.GREEN);
            avaliableColors.add(Color.LIGHT_GRAY);
            avaliableColors.add(Color.MAGENTA);
            avaliableColors.add(Color.ORANGE);
            avaliableColors.add(Color.PINK);
            avaliableColors.add(Color.RED);
            avaliableColors.add(Color.WHITE);
            avaliableColors.add(Color.YELLOW);

            JButton btn = new JButton("Change color");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Randomise the colors
                    Collections.shuffle(avaliableColors);
                    desiredColor = avaliableColors.get(0);
                    repaint();
                }
            });
            add(btn, BorderLayout.SOUTH);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(desiredColor);
            g2d.drawOval(108, 110, 200, 200);
            g2d.drawOval(160, 150, 20, 20);
            g2d.drawOval(240, 150, 20, 20);
            g2d.drawRect(160, 220, 100, 40);
            g2d.dispose();
        }

    }
}

Since you’re just starting out, I might suggest getting started with JavaFX instead

AWT

!! Warning !!

No one uses AWT anymore and you’re not likely to get much in the way of support for it here. This is a “basic” concept converted from the previous example, beware, AWT isn’t double buffered by default

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Frame frame = new Frame();
                frame.add(new TestCanvas());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestCanvas extends Container {

        private Color desiredColor = Color.BLACK;
        private List<Color> avaliableColors = new ArrayList<>(16);

        public TestCanvas() {
            setLayout(new BorderLayout());
            avaliableColors.add(Color.BLACK);
            avaliableColors.add(Color.BLUE);
            avaliableColors.add(Color.CYAN);
            avaliableColors.add(Color.DARK_GRAY);
            avaliableColors.add(Color.GRAY);
            avaliableColors.add(Color.GREEN);
            avaliableColors.add(Color.LIGHT_GRAY);
            avaliableColors.add(Color.MAGENTA);
            avaliableColors.add(Color.ORANGE);
            avaliableColors.add(Color.PINK);
            avaliableColors.add(Color.RED);
            avaliableColors.add(Color.WHITE);
            avaliableColors.add(Color.YELLOW);

            JButton btn = new JButton("Change color");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Randomise the colors
                    Collections.shuffle(avaliableColors);
                    desiredColor = avaliableColors.get(0);
                    repaint();
                }
            });
            add(btn, BorderLayout.SOUTH);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(desiredColor);
            g2d.drawOval(108, 110, 200, 200);
            g2d.drawOval(160, 150, 20, 20);
            g2d.drawOval(240, 150, 20, 20);
            g2d.drawRect(160, 220, 100, 40);
            g2d.dispose();
        }

    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement