Painting square matrix in Java - java

I am practicing with Java swing. I've created a matrix as 2D array of Rectangle2D objects. I've set the MouseListener to paint the square which was clicked. I've set up the for loop which checks which square was clicked. When I click on a square it's painted in blue. The thing is, when I click on the other square, the first one turns white and the other turns blue. My question is, how to keep the color of the square which was first clicked?
Here's the code of Matrica(Matrix) class(It's in my native tongue, crtanjeMatrice means drawMatrix and duzina is length.
public class Matrica extends JPanel implements MouseListener {
Rectangle2D[][] matrica = new Rectangle2D[8][8];
Color boja = Color.white;
int a = 0;
int b = 0;
public Matrica() {
addMouseListener(this);
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.clearRect(0, 0, this.getWidth(), this.getHeight());
crtanjeMatrice(g2);
g2.setColor(boja);
g2.fill(matrica[a][b]);
}
private void crtanjeMatrice(Graphics2D g2){
g2.setColor(Color.black);
int startX = 0;
int startY =0;
int duzina = 50;
for(int i=0; i < matrica.length; i++){
for(int j = 0; j < matrica.length; j++){
matrica[i][j] = new Rectangle2D.Double(startX,startY,duzina,duzina);
g2.draw(matrica[i][j]);
startX = startX + duzina;
}
startY = startY + duzina;
startX = 0;
}
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
int m,n;
int x = e.getX();
int y = e.getY();
for(int i = 0; i < matrica.length; i++)
for(int j =0; j < matrica.length; j++)
if(matrica[i][j].contains(x, y)){
boja = Color.blue;
a = i;
b = j;
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}

You are currently paint a single matrix cell in the paint method:
g2.fill(matrica[a][b]);
but you need to "remember" which rectangles have been clicked. To this end, a simple List can be used to store the indices of rectangles already clicked. A class based on the Point class offers a good means of storing row-column index information in the list.
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.clearRect(0, 0, this.getWidth(), this.getHeight());
crtanjeMatrice(g2);
for (MyRowColumn index : indexList) { // MyRowColumn based on Point
g2.setColor(Color.blue);
g2.fill(matrica[index.x][index.y]);
}
}
Aside:, don't use override paint, override paintComponent instead and remember to call super.paintComponent to render child components.

Related

Edit Shape location using mouse

I would like to move Shape objects, which I created previously. I cannot figure out how to change (update) shape location. Now I am getting cast error:
java.awt.geom.Ellipse2D$Double cannot be cast to java.awt.Graphics2D
Now I can access particular shape, but it seems it doesn't have setLocation() or something like that.
Please give me tip, because I got stuck.
Frame
public class Frame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(600, 600);
frame.setTitle("Prosty Paint");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Drawer drawer = new Drawer(frame.getComponents());
Menu menu = new Menu(drawer);
frame.setJMenuBar(menu.menuBar);
frame.add(drawer);
frame.setVisible(true);
}
}
Drawer
public class Drawer extends JPanel implements MouseListener, MouseMotionListener {
private final int defaultSize = 50;
private Color defaultColor = Color.BLACK;
private int oldX, oldY, currentX, currentY;
public String currentShape = "";
public Boolean editMode = false;
private int activeShape;
private final ArrayList<Shape> shapes = new ArrayList<>();
private final ArrayList<Color> colors = new ArrayList<>();
public Drawer(Component... components) {
for (Component c : components) {
c.addMouseListener(this);
c.addMouseMotionListener(this);
}
colors.add(Color.BLACK);
}
#Override
public void mousePressed(MouseEvent e) {
Point point = this.getMousePosition();
currentX = point.x;
currentY = point.y;
if (editMode) {
for (int i = 0; i < shapes.size(); i++) {
Shape shape = shapes.get(i);
if (shape.contains(e.getPoint())) {
System.out.println("Clicked shape " + i);
activeShape = i;
}
}
} else {
switch (currentShape) {
case "circle":
Ellipse2D ellipse2D = new Ellipse2D.Double(currentX, currentY, defaultSize, defaultSize);
shapes.add(ellipse2D);
colors.add(defaultColor);
break;
case "rec":
Rectangle2D rectangle2D = new Rectangle2D.Double(currentX, currentY, defaultSize, defaultSize);
shapes.add(rectangle2D);
colors.add(defaultColor);
break;
}
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
Point point = this.getMousePosition();
currentX = point.x;
currentY = point.y;
if(editMode){
Shape shape = shapes.get(activeShape);
Graphics2D g = (Graphics2D) shape;
g.translate(currentX,currentY);
}
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (int i = 0; i < shapes.size(); i++) {
Shape shape = shapes.get(i);
Color color = colors.get(i);
g2.setColor(color);
g2.fill(shape);
}
}
}
You haven't provided SSCCE (your code cannot be compiled by me) so I cannot test my solution, but your approach in the method mouseReleased is wrong. To translate the shape you need to replace
Graphics2D g = (Graphics2D) shape;
g.translate(currentX,currentY);
by
AffineTransform transform = new AffineTransform();
transform.translate(currentX, currentY);
shape = transform.createTransformedShape(shape);
shapes.set(activeShape, shape);
If it doesn't help please provide a SSCCE.

Adding Multiple JComponents deactivates mouse listener's

I have added 2 JComponent to JPanel.Both these JComponent have custom painted objects on them i.e multiple Circles and multiple Line2Ds.The dimensions of both these jcomponent's are set to the size of the screen which is required.When I add them to JPanel,the mouselisteners are not working.However if I comment one of them then that listener starts working.
public class MapXMLBuilder extends JFrame {
public void initialize() {
panel = new Jpanel();
addLine();//ading lines
addCircle();//adding cirlces
add(panel)
}
private void addLine() {
mDrawLine = new DrawLine(panel);
mDrawCircle.setDimensions(screenWidth, screenWidth);
panel.add(mDrawLine); //adding JComponent1 to panel
for (int i = 0; i < 10; i++) { //adding 10 circles
mDrawLine.addLine(new Point2D.Double(x, y));
}
}
private void addCircle() {
mDrawCircle = new DrawCircle(panel);
mDrawCircle.setDimensions(screenWidth, screenWidth);
panel.add(mDrawCircle); //adding JComponent1 to panel
for (int i = 0; i < 10; i++) { //adding 10 circles
mDrawCircle.addCircle(new Point2D.Double(x, y));
}
}
}
public class DrawLine extends JComponent {
public DrawLine(JPanel jpanel) {
lineList = new ArrayList();
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
setBackground(Color.white);
}
public void addLine(int x1, int y1, int x2, int y2, Color color) {
Shape currentShape = new Line2D.Float(x1, y1, x2, y2);
lineList.add(currentShape);
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.BLACK);
for (Shape shape: lineList) {
if (shapes != null && shapes.size() > 0) {
g2d.setColor(Color.YELLOW);
g2d.draw(shape);
}
}
}
public void setDimensions(int width, int height) {
setSize(new Dimension(width, height));
}
}
public class DrawCircle extends JComponent {
public DrawCircle(JPanel jpanel) {
circleList = new ArrayList();
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
setBackground(Color.white);
}
public void addCircle(Point2D p) {
Ellipse2D e = new Ellipse2D.Double(p.getX(), p.getY(), 5, 5);
circleList.add(e);
selectedPoint = null;
repaint();
}
public void setDimensions(int width, int height) {
setSize(new Dimension(width, height));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int diameter = 75;
Ellipse2D e;
Color color;
for (int j = 0; j < circleList.size(); j++) {
e = (Ellipse2D) circleList.get(j);
float alpha = 0.75f;
color = new Color(1, 0, 0, alpha); //Red
g2.setPaint(color);
Ellipse2D.Double circle = new Ellipse2D.Double(e.getX(), e.getY(), diameter, diameter);
g2.fill(circle);
}
}
}
You can forward the event from one to the other. Try something like this:
firstComponent.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent event){
// forward the event
secondComponent.dispatchEvent(event);
// handle the code here
}
});
secondComponent.addMouseListener(// etc.

Detecting when multiple Ellipse objects are being clicked

I am working on a version of the Squares game. For it I need to detect when my Ellipses are being clicked. But the problem is my method is using one Ellipse object. How can I detect which Ellipse is being clicked? Here is my code.
Main Squares class
public static boolean running = false;
public Squares() {
this.setSize(600, 600);
this.setTitle("Squares");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setContentPane(new SquarePane());
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
try {
new Squares();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Crashed");
System.exit(-1);
}
running = true;
}
}
SquaresPanel Class
public static int x = 100;
public static int y = 100;
public static Color randomColor;
public static float r;
public static float g;
public static float b;
public void paintComponent(Graphics gra) {
Graphics2D g2d = (Graphics2D) gra;
gra.setColor(Color.black);
gra.fillRect(0, 0, 600, 600);
Random rand = new Random();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
Ellipse2D oval = new Ellipse2D.Double(x, y, 10, 10);
r = rand.nextFloat();
g = rand.nextFloat();
b = rand.nextFloat();
randomColor = new Color(r, g, b);
g2d.setColor(randomColor);
g2d.fill(oval);
x += 50;
}
x = 100;
y += 50;
}
}
Thanks guys!
Will
Without looking too much at your code (as I see it's lacking alot) I will just explain how your requirement can be achieve.
1st : You need a MouseListener and implement the mousePressed. From the MouseEvent object, you can obtain the point clicked. See How to Write MouseListener if you are unsure.
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
}
2nd: Keep a List of your ellipses
List<Ellipse2D> ellipses;
3rd: Keep a selectedEllipse variable to hold the select one.
Ellipse2D selectedEllipse;
4th: After clicking the point, you loop through the list, checking if each Ellipse2D.contains the point. Then do something with the selected Ellipse
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
for (Ellipse2D ellipse : ellipses) {
if (ellipse.contains(p) {
selectedEllipse = ellipse;
// do something with selectedEllipse
break;
} else {
selectedEllipse = null;
}
}
}
5th: Loop through your ellipses to paint the in the paintComponent method
protected void paintComponent(Grapchics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (Ellipse2D ellipse : ellipses) {
g2.fill(ellipse):
}
}
Side Notes
You must call super.paintComponent in your paintComponent method
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
UPDATE
After taking a closer look at your code, I see more of what you are trying to achieve. Looks like you want am 8 by 8 grid of your ellipses. Another option is just to create 64 panels. and paint each of them.
First have a panel class where you can set the color
public class EllipsePanel extends JPanel {
private Color color;
public EllipsePanel(Color color) {
this.color = color;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillOval(0, 0, getWidth(), getHeight());
}
}
Then you can use a panel to hold all those panel and use a GridLayout, but also keeping a JPanel[][] so you can easily refer to each panel. You can also a add a mouselistener to each panel
JPanel gridPanel = new JPanel(new GridLayout(8, 8));
EllipsePanel[][] panels = new EllipsePanel[8][8];
EllipsePanel selectedPanel = null;
int currentRow;
int currentCol;
...
for (int i = 0; i < 8; i++) {
for (int j = 0; i < 8; j++) {
final EllipPanel panel = new EllipsePanel(getRendomColor);
panel.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
selectedPanel = panel;
// do something with selected panel;
}
});
gridPanel.add(panel);
}
}
You should implement a mouse listener on your JPannel, and then use the position clicked retrieved from the listener to work out which ellipse was clicked

Java Graphics2D to erase to a alpha background

I'm making an application that has a drawing board where you draw with your mouse, it draws ontop of an Label in a BUfferedImage. What I'm trying to implement right now is an eraser, the problem is I cannot find anywhere help to make an eraser to clearRect() to an alpha background. (I cannot have a defined color background since the user can change the background to any image he wants). To sum up:
How can you erase/overwrite Graphics2D pixels with alpha pixels? The way i found was with clearRect but you need to specify a background color.
The following is my DrawBoard class which constains everything to draw.
public class DrawBoard extends JPanel implements MouseListener, MouseMotionListener{
public JLabel status;
private JLabel imgLabel; // this is where the drawing happens
public Point pstart, pfinish;
private List<Point> points = new ArrayList<Point>();
private List<BufferedImage> lines = new ArrayList<BufferedImage>();
private static final int BI_WIDTH = 1024;
private static final int BI_HEIGHT = 800;
private static int STROKESIZE = 7;
private BufferedImage bImage = new BufferedImage(BI_WIDTH, BI_HEIGHT,
BufferedImage.TYPE_INT_ARGB);
public Color currentColor;
public static boolean eraser = false;
private int xX1, yY1;
public DrawBoard(){
Graphics2D g2d = bImage.createGraphics();
g2d.dispose();
Dimension size = getPreferredSize();
size.setSize(1024,800); //w, h
setPreferredSize(size);
//status = new JLabel("default");
//add(status, BorderLayout.SOUTH);
addMouseListener(this);
addMouseMotionListener(this);
imgLabel = new JLabel(new ImageIcon(bImage)) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
paintInLabel(g);
}
};
imgLabel.setOpaque(false);
setOpaque(false);
add(imgLabel, BorderLayout.CENTER);
}
private void paintInLabel(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(getColor()); // this colour is when mouse is pressed
g2d.setStroke(new BasicStroke(STROKESIZE));
if (points.size() < 2) {
return;
}
for (int i = 1; i < points.size(); i++) {
int x1 = points.get(i - 1).x;
int y1 = points.get(i - 1).y;
int x2 = points.get(i).x;
int y2 = points.get(i).y;
g2d.drawLine(x1, y1, x2, y2);
}
}
#Override
public void mouseExited(MouseEvent e){
}
#Override
public void mouseEntered(MouseEvent e){
}
#Override
public void mouseMoved(MouseEvent e){
}
// Where the drawing happens
#Override
public void mousePressed(MouseEvent e) {
//status.setText("you pressed down the mouse");
xX1 = e.getX();
yY1 = e.getY();
points.add(e.getPoint());
}
#Override
public void mouseDragged(MouseEvent e) {
//status.setText("you draged the mouse");
points.add(e.getPoint());
imgLabel.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
//status.setText("you release the mouse click");
Graphics2D g2d = bImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(getColor()); // this is the final colour
g2d.setStroke(new BasicStroke(STROKESIZE));
if (points.size() >= 2) {
for (int i = 1; i < points.size(); i++) {
int x1 = points.get(i - 1).x;
int y1 = points.get(i - 1).y;
int x2 = points.get(i).x;
int y2 = points.get(i).y;
g2d.drawLine(x1, y1, x2, y2);
}
}
g2d.dispose();
points.clear();
imgLabel.repaint();
}
// End of where the drawing happens
public void clearDrawBoard() {
}
private Color getColor() {
return ColourToolbar.selectedColor;
}
private void setColor(Color col){
this.currentColor = col;
}
#Override
public void mouseClicked(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
}
You should set a custom Composite for your Graphics2D, specifically AlphaComposite.Clear before drawing the rectangle. Don't forget to reset the composite to the default (SRC_OVER) when you are done, because the same Graphics object will be reused to paint other components.

Repaint() not being called

Recently I've been working on a program that paints an area with empty, colored squares. Their locations on the screen are based off of the values 1 and 2 in a text file. 1s are supposed to make red boxes, and 2s are supposed to make green boxes. However, when I run the program, only red boxes are painted. I did some testing and found out that the repaint method is only being called twice(once sometimes for some reason), even though there are close to 300 values in the file, and repaint() should be called once for every value. Here is my code:
public class MAP extends JFrame {
public static void main(String[] args) throws IOException {
MAP map = new MAP();
}
Shape shape;
int x = -32;
int y = 0;
ArrayList<Shape> shapes = new ArrayList<Shape>();
Graphics2D g2;
Color coulor = null;
private class PaintSurface extends JComponent {
public PaintSurface() {
}
public void paint(Graphics g) {
g2 = (Graphics2D) g;
g2.setColor(coulor);
for (Shape s : shapes) {
g2.draw(s);
}
}
}
public MAP() throws FileNotFoundException, IOException {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
frame.setTitle("Grid Maker");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(new PaintSurface(), BorderLayout.CENTER);
frame.setVisible(true);
readNextLine();
}
private void readNextLine() throws IOException {
File file = new File("map.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '1') {
coulor = Color.RED;
x += 32;
int smallX = x / 32;
int smallY = y / 32;
shape = new Rectangle2D.Float(x, y, 32, 32);
shapes.add(shape);
repaint();
} else if (c == '2') {
coulor = Color.GREEN;
x += 32;
int smallX = x / 32;
int smallY = y / 32;
shape = new Rectangle2D.Float(x, y, 32, 32);
shapes.add(shape);
repaint();
}
}
line = in.readLine();
x = -32;
y += 32;
}
}
}
Why isn't this code working properly?
Just to add to other answers, here is a piece of code (based on yours) which looks already a lot better (yet there are still some issues, but you are not there yet):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class MAP extends JFrame {
public static void main(String[] args) throws IOException {
MAP map = new MAP();
}
public static class ColoredShape {
private Shape shape;
private Color color;
public ColoredShape(Shape shape, Color color) {
super();
this.shape = shape;
this.color = color;
}
public Shape getShape() {
return shape;
}
public Color getColor() {
return color;
}
}
int x = -32;
int y = 0;
List<ColoredShape> shapes = new ArrayList<ColoredShape>();
Graphics2D g2;
private class PaintSurface extends JComponent {
public PaintSurface() {
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g2 = (Graphics2D) g;
for (ColoredShape s : shapes) {
g2.setColor(s.getColor());
g2.draw(s.getShape());
}
}
}
public MAP() throws FileNotFoundException, IOException {
JFrame frame = new JFrame();
frame.setTitle("Grid Maker");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(new PaintSurface(), BorderLayout.CENTER);
frame.setVisible(true);
readNextLine();
}
private void readNextLine() throws IOException {
BufferedReader in = new BufferedReader(new StringReader("11121\n1221\n2212\n221121\n111221\n11221\n222\n2222\n"));
String line = in.readLine();
while (line != null) {
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
Color color = null;
if (c == '1') {
color = Color.RED;
} else if (c == '2') {
color = Color.GREEN;
}
if (color != null) {
shapes.add(new ColoredShape(new Rectangle2D.Float(x, y, 32, 32), color));
x += 32;
repaint();
}
}
line = in.readLine();
x = -32;
y += 32;
}
}
}
Painting is transient, or stateless.
repaint is a "request" made to the repaint manager to tell it that it should, at some time in the future, when it's ready, it should paint some portion of the screen, that it deems to be dirty.
This means that when you call g2.setColor(coulor) in you paint method, it is using the LAST value that it was set to (when paint is called)....which is probably RED.
Raufio is right, you should be providing color information along with the shapes. Personally, I would set up a second List which just contained Color objects, where each index of the Shape list corresponded directly to the Color in the Color List.
Check out Painting in AWT and Swing for more details on how painting in works in Swing.
Now, to the whiny part ;)
It is not recommended to override paint. There are lots of reasons for this, paint is responsible for calling a number of important methods, including paintChildren and paintComponent, which perform very important tasks.
Instead, you should override paintComponent (and make sure you call super.paintComponent)
Check out Performing Custom Painting for more details.
Update with rough example
So this is a rough example of what I'm talking about...
public class TestPainting {
public static void main(String[] args) {
new TestPainting();
}
public TestPainting() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PaintingPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintingPane extends JPanel {
private static final int WIDTH = 200;
private static final int HEIGHT = 200;
private List<Shape> shapes;
private List<Color> colors;
public PaintingPane() {
shapes = new ArrayList<>(25);
colors = new ArrayList<>(25);
for (int index = 0; index < (int) Math.round(Math.random() * 100); index++) {
int x = (int) Math.round(Math.random() * (WIDTH * 0.75f));
int y = (int) Math.round(Math.random() * (HEIGHT * 0.75f));
int width = (int) Math.round(Math.random() * (WIDTH * 0.25f));
int height = (int) Math.round(Math.random() * (HEIGHT * 0.25f));
if (width < 5) {
width = 5;
}
if (height < 5) {
height = 5;
}
if (x + width > WIDTH) {
x -= width - WIDTH;
}
if (y + height > HEIGHT) {
y -= height - HEIGHT;
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
Color color = ((int)Math.round(Math.random() * 2)) == 1 ? Color.RED : Color.GREEN;
shapes.add(new Rectangle(x, y, width, height));
colors.add(color);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (int index = 0; index < shapes.size(); index++) {
g2d.setColor(colors.get(index));
g2d.draw(shapes.get(index));
}
g2d.dispose();
}
}
}
The first thing I see is that you are only coloring shapes one color at a time. So here:
public void paint(Graphics g) {
g2 = (Graphics2D) g;
g2.setColor(coulor); //set the drawing color
for (Shape s : shapes) {
g2.draw(s); //draw in that color
}
}
All your shapes are being drawn in the same color, when you want to color them differently. I think a better way to do things is to add all your shapes into your list, keeping track of their color, and calling repaint() once. Also, I would change the paint method to something to the effect of:
public void paint(Graphics g) {
g2 = (Graphics2D) g;
for (Shape s : shapes) {
g2.setColor(coulor[indexOfShape]); //set the drawing color
g2.draw(s); //draw in that color
}
}
Also, for repaint only being called twice: It is probably throwing an IOException. Try using a try {...} catch(IOException e) {...} block instead of just throwing it up the line. Something like:
private void readNextLine() {
try {
File file = new File("map.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
...
...
} catch (IOException e) {
e.printStackTrace();
}
}
It should complain about something if it isn't reading right.

Categories

Resources