|
-
March 22nd, 2012, 04:52 AM
#1
Drawing Rectangles in Java
Hello People
I have my program the need to generate rectangles on the screen when i click on a JButton and then be able to drag them on the screen but I am having one problem:
here is my code for that class:
Code:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
public class GUI extends JFrame {
static BufferedImage img = imageloading.mImage;
private static final int width = img.getWidth();
private static final int height = img.getHeight();
static int cellSize = 5;
public static int cellInWidth = width/cellSize;
public static int cellInHeight = height/cellSize;
public static Cell[][] cells = new Cell[cellInWidth][cellInHeight];
private JPanel mainPanel = new JPanel();
private JScrollPane scrollBar=new JScrollPane(mainPanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
private GridPanel gridPanel = new GridPanel();
private JPanel buttonPanel = new JPanel();
private JButton startButton = new JButton("Start");
private JButton edgeButton = new JButton("Detect Edge");
private JButton woodButton = new JButton("Detect Wood");
private JButton doorButton = new JButton("Find Door");
private JButton rectButton = new JButton("Add Object");
private JButton loadImage = new JButton("Select Image");
private JLabel label = new JLabel("Cell size:");
private JComboBox comboBox = new JComboBox(new Integer[]{5, 10, 15, 20, 25, 30});
File curFile;
private Logic logic = new Logic(this);
public static boolean runnedFirstTime = false;
static {
for (int i = 0; i < cellInWidth; i++) {
for (int j = 0; j < cellInHeight; j++) {
cells[i][j] = new Cell(i, j);
}
}
}
private MouseAdapter mousePressed = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
mousePressedLogic(e);
}
};
private MouseAdapter mouseMotion = new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
mousePressedWoodLogic(e);
}
};
private void mousePressedLogic(MouseEvent e) {
if (logic.hasStarted()) return;
int x = e.getY();
int y = e.getX();
int gridsToTheLeft = y / cellSize;
int gridsFromTop = x / cellSize;
if (gridsToTheLeft >= cellInWidth || gridsFromTop >= cellInHeight)
return;
cells[gridsToTheLeft][gridsFromTop].setStatus(Cell.BURNING);
repaint();
}
private void mousePressedWoodLogic(MouseEvent e) {
if (logic.hasStarted()) return;
int x = e.getY();
int y = e.getX();
int gridsToTheLeft = y / cellSize;
int gridsFromTop = x / cellSize;
if (gridsToTheLeft >= cellInWidth || gridsFromTop >= cellInHeight)
return;
cells[gridsToTheLeft][gridsFromTop].setStatus(Cell.DOOR);
repaint();
}
/**
* Constructor
*/
public GUI() {
setTitle("Fire Spreading");
setSize(1000, 700);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
mainPanel.setLayout(new BorderLayout());
mainPanel.add(gridPanel, BorderLayout.CENTER);
buttonPanel.add(startButton);
buttonPanel.add(edgeButton);
buttonPanel.add(woodButton);
buttonPanel.add(doorButton);
buttonPanel.add(rectButton);
buttonPanel.add(loadImage);
buttonPanel.add(label);
buttonPanel.add(comboBox);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
//mainPanel.setBackground(Color.GREEN);
comboBox.setSelectedItem(5);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cellSize = (Integer)comboBox.getSelectedItem();
cellInWidth = width/cellSize; //number of cells in width
cellInHeight = height/cellSize;
cells = new Cell[cellInWidth][cellInHeight];
for (int i = 0; i < cellInWidth; i++) {
for (int j = 0; j < cellInHeight; j++) {
cells[i][j] = new Cell(i, j);
}
}
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[0].length; j++) {
cells[i][j].setStatus(Cell.DEFAULT);
}
}
logic.setCells(cells);
logic.setStarted(false);
if (logic.isTimerCreated())
runnedFirstTime = true;
repaint();
}
});
rectButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//add rectangle shape
addshape(new RectShape());
logic.setStarted(false);
runnedFirstTime = false;
repaint();
}
});
woodButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[0].length; j++) {
int cellColor=0;
int cellColorG=0;
int cellColorB=0;
for (int ii = 0; ii < cellSize; ii++) {
for (int jj = 0; jj < cellSize; jj++) {
// calculate new pixel position
int pixelPositionX = i * cellSize + ii;
int pixelPositionY = j * cellSize + jj;
int pixel = img.getRGB(pixelPositionX, pixelPositionY);
Color color = new Color(pixel);
if (color.getRed()>60 && color.getRed() <255 && color.getGreen()>50 && color.getGreen() <190 && color.getBlue()<105)
cellColor++;
}
}
if (cellColor >= 1 )
cells[i][j].setStatus(Cell.WOOD);
cells[i][j].setCellType(new CellType(CellType.Type.WOOD));
}
}
logic.setStarted(false);
runnedFirstTime = false;
repaint();
}
});
loadImage.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//mainPanel.setVisible(false);
new imageloading();
}
});
startButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
logic.setStarted(true);
if (!runnedFirstTime)
logic.startSimulation();
}
});
doorButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[0].length; j++) {
int cellColor=0;
int cellColorG=0;
int cellColorB=0;
for (int ii = 0; ii < cellSize; ii++) {
for (int jj = 0; jj < cellSize; jj++) {
// calculate new pixel position
int pixelPositionX = i * cellSize + ii;
int pixelPositionY = j * cellSize + jj;
int pixel = img.getRGB(pixelPositionX, pixelPositionY);
Color color = new Color(pixel);
if (color.getRed()==0 && color.getGreen()>0 && color.getBlue()==0)
cellColor++;
}
}
if (cellColor >= 1 )
cells[i][j].setStatus(Cell.DOOR);
cells[i][j].setCellType(new CellType(CellType.Type.DOOR));
}
}
logic.setStarted(false);
runnedFirstTime = false;
repaint();
}
});
edgeButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//BufferedImage img = imageloading.mImage;
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[0].length; j++) {
int cellColorR=0;
int cellColorG=0;
int cellColorB=0;
for (int ii = 0; ii < cellSize; ii++) {
for (int jj = 0; jj < cellSize; jj++) {
// calculate new pixel position
int pixelPositionX = i * cellSize + ii;
int pixelPositionY = j * cellSize + jj;
int pixel = img.getRGB(pixelPositionX, pixelPositionY);
Color color = new Color(pixel);
if (color.getRed() < 10)
cellColorR++;
if (color.getGreen() < 10)
cellColorG++;
if (color.getBlue() < 10)
cellColorB++;
}
}
if (cellColorR > 1 && cellColorG > 1 && cellColorB > 1)
cells[i][j].setStatus(Cell.EDGE);
}
}
logic.setStarted(false);
runnedFirstTime = false;
repaint();
}
});
add(mainPanel);
gridPanel.addMouseMotionListener(mouseMotion);
gridPanel.addMouseListener(mousePressed);
}
/**
* @return this grid panel
*/
public GridPanel getGridPanel() {
return gridPanel;
}
/**
* The panel that contains the grid.
*/
public class GridPanel extends JPanel {
private Graphics g;
ArrayList shapes = new ArrayList();
/**
* overrides javax.swing.JComponent.paintComponent
*
* @param g
*/
protected void paintComponent(Graphics g) {
super.paintComponents(g);
this.g = g;
//
//BufferedImage img = imageloading.mImage;
/*BufferedImage img = null;
try {
img = ImageIO.read(new File("C:\\Users\\Test 1\\Desktop\\alo5.jpg"));
} catch (IOException ee) {
}
*/
//image = Toolkit.getDefaultToolkit().getImage("C:\\Users\\Test 1\\Desktop\\alo6.jpg");
g.drawImage(img,0,0,img.getWidth(),img.getHeight(), this);
int top = shapes.size();
for (int i = 0; i < top; i++) {
Shape s = (Shape)shapes.get(i);
s.draw(g);
}
for (int i = 0; i < width; i += cellSize) {
for (int j = 0; j < height; j += cellSize) {
g.drawRect(i, j, cellSize, cellSize);
}
}
//draw all cells
for (int i = 0; i < width; i += cellSize) {
for (int j = 0; j < height; j += cellSize) {
boolean isIndexLegal = j /cellSize < cells[0].length && i / cellSize < cells.length;
if (isIndexLegal) {
if (GUI.cells[i / cellSize][j / cellSize].getStatus() == Cell.BURNING)
drawBurningCell(i, j);
else if (GUI.cells[i / cellSize][j / cellSize].getStatus() == Cell.WOOD)
drawWoodBurningCell(i, j);
else if (GUI.cells[i / cellSize][j / cellSize].getStatus() == Cell.DOOR)
drawDoorCell(i, j);
else if (GUI.cells[i / cellSize][j / cellSize].getStatus() == Cell.EMPTY)
drawEmptyCell(i, j);
else if (GUI.cells[i / cellSize][j / cellSize].getStatus() == Cell.EDGE)
drawEdgeCell(i, j);
}
}
}
// dessine rectangle
}
public void addShape(Shape shape) {
shape.setColor(Color.red);
shape.reshape(10, 10, 50, 30);
shapes.add(shape);
}
Shape clickedShape = null; // This is the shape that the user clicks on.
Shape draggedShape = null; // This is null unless a shape is being dragged.
int prevDragX; // During dragging, these record the x and y coordinates of the
int prevDragY; // previous position of the mouse.
public void mousePressed(MouseEvent evt) {
if (draggedShape != null) {
return;
}
int x = evt.getX(); // x-coordinate of point where mouse was clicked
int y = evt.getY(); // y-coordinate of point
clickedShape = null; // This will be set to the clicked shape, if any.
for ( int i = shapes.size() - 1; i >= 0; i-- ) {
// Check shapes from front to back.
Shape s = (Shape)shapes.get(i);
clickedShape = s;
}
if (clickedShape == null) {
return;
}
else if (evt.isPopupTrigger()) {
//popup.show(this,x-10,y-2);
}
else if (evt.isShiftDown()) {
shapes.remove(clickedShape);
shapes.add(clickedShape);
repaint();
}
else {
draggedShape = clickedShape;
prevDragX = x;
prevDragY = y;
}
}
public void mouseDragged(MouseEvent evt) {
// User has moved the mouse. Move the dragged shape by the same amount.
if (draggedShape == null) {
// User did not click a shape. There is nothing to do.
return;
}
int x = evt.getX();
int y = evt.getY();
draggedShape.moveBy(x - prevDragX, y - prevDragY);
prevDragX = x;
prevDragY = y;
repaint(); // redraw canvas to show shape in new position
}
public void mouseReleased(MouseEvent evt) {
if (draggedShape == null) {
return;
}
int x = evt.getX();
int y = evt.getY();
if (evt.isPopupTrigger()) {
// popup.show(this,x-10,y-2);
}
else {
draggedShape.moveBy(x - prevDragX, y - prevDragY);
if ( draggedShape.left >= getSize().width || draggedShape.top >= getSize().height || draggedShape.left + draggedShape.width < 0 || draggedShape.top + draggedShape.height < 0 ) { // shape is off-screen
shapes.remove(draggedShape); // remove shape from list of shapes
}
repaint();
}
draggedShape = null; // Dragging is finished.
}
public void mouseEntered(MouseEvent evt) { } // Other methods required for MouseListener and
public void mouseExited(MouseEvent evt) { } // MouseMotionListener interfaces.
public void mouseMoved(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public abstract class Shape {
int left, top; // Position of top left corner of rectangle that bounds this shape.
int width, height; // Size of the bounding rectangle.
Color color = Color.white; // Color of this shape.
boolean drawOutline; // If true, a black border is drawn on the shape
void reshape(int left, int top, int width, int height) {
// Set the position and size of this shape.
this.left = left;
this.top = top;
this.width = width;
this.height = height;
}
void setSize(int width, int height) {
// Set the size of this shape
this.width = width;
this.height = height;
}
void moveBy(int dx, int dy) {
left += dx;
top += dy;
}
void setColor(Color color) {
// Set the color of this shape
this.color = color;
}
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(left,top,width,height);
if (drawOutline) {
g.setColor(Color.black);
g.drawRect(left,top,width,height);
}
}// Draw the shape in the graphics context g.
// This must be overridden in any concrete subclass.
}
public class RectShape extends Shape {
// This class represents rectangle shapes.
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(left,top,width,height);
if (drawOutline) {
g.setColor(Color.black);
g.drawRect(left,top,width,height);
}
}
}
public void drawDoorCell(int xPos, int yPos) {
int gridsToTheLeft = xPos / cellSize;
int gridsFromTop = yPos / cellSize;
g.setColor(new Color(0,100,0,100));
g.fillRect(gridsToTheLeft * cellSize, gridsFromTop * cellSize, cellSize, cellSize);
}
public void drawWoodBurningCell(int xPos, int yPos) {
int gridsToTheLeft = xPos / cellSize;
int gridsFromTop = yPos / cellSize;
g.setColor(new Color(255,102,0,100));
g.fillRect(gridsToTheLeft * cellSize, gridsFromTop * cellSize, cellSize, cellSize);
}
public void drawBurningCell(int xPos, int yPos) {
int gridsToTheLeft = xPos / cellSize;
int gridsFromTop = yPos / cellSize;
g.setColor(Color.RED);
g.fillRect(gridsToTheLeft * cellSize, gridsFromTop * cellSize, cellSize, cellSize);
}
public void drawEdgeCell(int xPos, int yPos) {
int gridsToTheLeft = xPos / cellSize;
int gridsFromTop = yPos / cellSize;
g.setColor(new Color(0,0,255,100));
g.fillRect(gridsToTheLeft * cellSize, gridsFromTop * cellSize, cellSize, cellSize);
}
public void drawEmptyCell(int xPos, int yPos) {
int gridsToTheLeft = xPos / cellSize;
int gridsFromTop = yPos / cellSize;
g.setColor(new Color(255,255,0,100));
g.fillRect(gridsToTheLeft * cellSize, gridsFromTop * cellSize, cellSize, cellSize);
}
}
}
the error is coming in the button segment:
rectButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//add rectangle shape
addshape(new RectShape());////////// new Rectangle() is underlined in red and says to create a new class
logic.setStarted(false);
runnedFirstTime = false;
repaint();
}
});
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|