Saturday 28 September 2013

Re-positioning the ContentPane of a JFrame

Re-positioning the ContentPane of a JFrame

I'm trying to draw a grid inside the content pane of my JFrame but when I
do, everything is off. The grid starts too wide and offset (presumably set
where the border of the window overlaps the contentpane) and it doesn't
draw the entire grid correctly. When i use frame.setUndecorated(true);
everything works perfectly.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.*;
@SuppressWarnings("serial")
class Creator extends JFrame{
JFrame frame;
int[][] Grid = new int[18][27];
public Creator(){
frame = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for(int i = 0; i < 18; i++) {
for(int j = 0; j < 27; j++) {
Grid[i][j] = 0;
}
}
setSize(864, 544);
getContentPane().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int yLocation = e.getX()/32;
int xLocation = e.getY()/32;
System.out.println(xLocation + " " + yLocation);
if(e.getButton() == 1){
if(xLocation < 1 || yLocation < 1){
Grid[xLocation][yLocation] = 2;
System.out.println("Enemy Added");
}else if(xLocation > 16 || yLocation > 25){
Grid[xLocation][yLocation] = 2;
System.out.println("Enemy Added");
}else {
Grid[xLocation][yLocation] = 1;
System.out.println("Obstacle Added");
}
}else {
Grid[xLocation][yLocation] = 0;
System.out.println("Item Removed");
}
frame.invalidate();
frame.validate();
frame.repaint();
}
});
}
public void paint(Graphics g) {
g.clearRect(0, 0, 864, 544);
Graphics2D g2 = (Graphics2D) g;
for(int i =0; i < 18; i++) {
for(int j =0; j < 27; j++) {
if(Grid[i][j] != 0){
if( i < 1 || j < 1 || i > 26 || j > 17) {
g2.setColor(Color.RED);
g2.fillRect(j*32, i*32, 32, 32);
}else {
g2.setColor(Color.BLUE);
g2.fillRect(j*32, i*32, 32, 32);
}
}
//System.out.print(Grid[i][j]);
}
//System.out.println();
}
for(int i = 0; i < 27; i++) {
Line2D lin = new Line2D.Float(i*32, 0, i*32, 544);
g2.draw(lin);
}
for(int i = 0; i < 18; i++) {
Line2D lin = new Line2D.Float(0, i*32, 864, i*32);
g2.draw(lin);
}
}
public static void main(String []args){
Creator s=new Creator();
s.setVisible(true);
}
}

No comments:

Post a Comment