The panel doesn't fit in the frame, and when I change the size of the frame a new panel is painted. I want the panel to fit and also to change the size on the frame without painting a new panel.
Here is the code:
import java.awt.*;
import javax.swing.*;
public class ColorGrid extends JPanel {
int length=200;
int width=200;
double stokastik;
public ColorGrid(int x,int y) {
setSize(200,200);
width=18*x;
length=18*y;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int row=0; row <=length;row+=20) {
for(int col=0; col <=width;col+=20) {
stokastik= Math.random();
if(stokastik < 0.25){
g.setColor(Color.YELLOW);
}
else if (stokastik < 0.5) {
g.setColor(Color.BLUE);
}
else if (stokastik < 0.75) {
g.setColor(Color.GREEN);
} else {
g.setColor(Color.RED);
}
g.fillRect(row, col, 18, 18);
}
}
}
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setBounds(300,300,300,300);
ColorGrid grid = new ColorGrid(10,10);
frame.add(grid);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
}
Your code is confusing because you call setBounds/setSize, but eventually, you call pack() which will just resize everything according to preferred size of components.
The proper way to go is to override getPreferredSize() in your custom component. By all means, avoid calling setSize/setBounds/setLocation. This is the job of the LayoutManager.
Regarding the repaint of the panel, you don't have a choice. A panel can get repainted many times independently of your will. So the only way to avoid the change of colors when the repaint occurs, is to pre-calculate the colors upfront and then only iterate over the same colors when performing the custom painting.
Small demo code illustrating this:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ColorGrid extends JPanel {
double stokastik;
private int width;
private int length;
private Dimension preferredSize;
private Color[][] colors;
public ColorGrid(int x, int y) {
width = 20 * x;
length = 20 * y;
preferredSize = new Dimension(width, length);
colors = new Color[x][y];
for (int row = 0; row < x; row++) {
for (int col = 0; col < y; col++) {
stokastik = Math.random();
if (stokastik < 0.25) {
colors[row][col] = (Color.YELLOW);
} else if (stokastik < 0.5) {
colors[row][col] = (Color.BLUE);
} else if (stokastik < 0.75) {
colors[row][col] = (Color.GREEN);
} else {
colors[row][col] = (Color.RED);
}
}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int row = 0; row < colors.length; row++) {
for (int col = 0; col < colors[row].length; col++) {
g.setColor(colors[row][col]);
g.fillRect(row * 20, col * 20, 18, 18);
}
}
}
#Override
public Dimension getPreferredSize() {
return preferredSize;
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorGrid grid = new ColorGrid(10, 10);
frame.add(grid);
frame.pack();
frame.setVisible(true);
}
});
}
}
In your constructor set the preferred size.
public ColorGrid(int x, int y) {
setSize(200, 200);
setPreferredSize(new Dimension(200, 200));
width = 18 * x;
length = 18 * y;
}
Then it will show correctly on initial load..
As mentioned by another answer, also have your length and width defined proportionally.
Related
The printout of the array lifegrid2 just gives all zeros. I tested the lifegrid array in MyPanel and that is populating, but the values are pulling through as zeros. I checked by putting some values in lifegrid2 and they are being wiped, so it is pulling through from MyPanel, but only zeros. There are no errors being reported.
I have made a small test program with a 2d array which does pull values through.
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import java.awt.*;
import java.awt.event.*;
public class SwingPaintDemo3 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Swing Paint Demo");
f.setPreferredSize(new Dimension(1280,800));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
JPanel subPanel = new JPanel();
JButton start = new JButton("START");
subPanel.add(start);
start.setPreferredSize(new Dimension(100,50));
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae1) {
System.out.println("START");
int [][][] lifegrid2 = new int [12][12][2];
int temp;
for (int i=0; i<12; i++) {
for (int j=0; j<12; j++) {
**MyPanel obj = new MyPanel();
temp = obj.lifegrid [i][j][0];
lifegrid2 [i][j][0] = temp;**
if (j<11)
{System.out.print(lifegrid2 [j] [i] [0]);}
else
{System.out.println(lifegrid2 [j] [i] [0]);}}}
}
});
f.add(subPanel, BorderLayout.EAST);
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
class MyPanel extends JPanel {
public int [][][] lifegrid = new int [12][12][2];
private int squareX = 1280;
private int squareY = 800;
private int gridX, gridY ;
public MyPanel() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
squareX = e.getX();
squareY = e.getY();
if ((squareX>50 & squareX <550) & (squareY>50 & squareY <550) ){
gridX =(squareX-50)/50+1;
gridY =(squareY-50)/50+1;
squareX = (squareX -50)/50 * 50 + 50;
squareY = (squareY -50)/50 * 50 + 50;
System.out.println(gridX + " " + gridY);
lifegrid [gridX] [gridY] [0] = 1;
repaint(squareX,squareY,50,50);}
else {
}
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("This is my custom Panel!",10,20);
g.setColor(Color.RED);
g.fillRect(squareX,squareY,48,48);
g.setColor(Color.BLACK);
g.drawRect(squareX,squareY,48,48);
}
}
I have made a small test program with a 2d array
int [][][] lifegrid2 = new int [12][12][2];
That is a 3D array.
A 2D array is defined as:
int [][] lifegrid2 = new int [12][12];
The logic to initialize the array belongs in the constructor of your class:
MyPanel()
{
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
lifegrid [i][j] = 0)
}
}
}
Then your paintComponent() method needs to iterate through the 2D grid and only paint the grids that have a value of 1.
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
if (lifegrid[i][j] = 1)
// paint the grid
}
}
}
}
Edit:
As best as I can tell you are trying to create a grid based game. When you click on a cell in the grid the cell turns red. The are two common ways to approach this:
Use components. In this approach you have a parent panel using a GridLayout and you add a child panel to each cell in the grid. You would also add your MouseListener to each child panel. When you click on the child panel you change the background of the panel to red.
Do custom painting. In this approach you have a single JPanel. This class keep a 2D Array for the "state" of each cell in the grid. You add a single MouseListener to the panel. When you click on the panel you determine which cell was clicked and then you update the state of that cell. In the paintComponent() method you iterate through the 2D Array and paint each cell where that state has changed.
Your approach seems to be some kind of hybrid between the two and is not working.
I am trying to make a basic tetris game, first I am looking to draw a grid to make sure that I am creating blocks as I want to, however I can't get my program to access my paintComponent method.
package tetris;
import javax.swing.*;
import java.awt.*;
public class TetrisMain extends JFrame {
final int BoardWidth = 10;
final int BoardHeight = 20;
public static int HEIGHT = 400;
public static int WIDTH = 200;
Timer timer;
boolean isFallingFinished = false;
boolean isStarted = false;
boolean isPaused = false;
int score = 0;
int curX = 0;
int curY = 0;
int[][] grid = new int[BoardWidth][BoardHeight];
public static void main(String[] args) {
JFrame frame = new JFrame("Charles Walker - 1504185");
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.repaint();
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.setColor(Color.BLACK);
for (int i = 0; i < BoardWidth; i++) {
for (int j = 0; j < BoardHeight; j++) {
curX = grid[i][curY];
curY = grid[curX][j];
g.fillRect(WIDTH / BoardWidth, HEIGHT / BoardHeight, curX, curY);
}
}
}
}
Here is a basic code to do what you want :
import javax.swing.JFrame;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.*;
public class Name extends JFrame {
public Name() {
super("Name");
setTitle("Application");
setContentPane(new Pane());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setResizable(true);
setVisible(true);
while (true){
try { //Update screen every 33 miliseconds = 25 FPS
Thread.sleep(33);
} catch(InterruptedException bug) {
Thread.currentThread().interrupt();
System.out.println(bug);
}
repaint();
}
}
class Pane extends JPanel {
public void paintComponent(Graphics g) { //Here is were you can draw your stuff
g.drawString("Hello World",0,20); //Display text
}
}
public static void main(String[] args){
new Name();
}
}
I think you forgot that line to set the content pane :
setContentPane(new Pane());
and, important, you need a while loop to redraw :
while (true){
try { //Update screen every 33 miliseconds = 25 FPS
Thread.sleep(33);
} catch(InterruptedException bug) {
Thread.currentThread().interrupt();
System.out.println(bug);
}
repaint();
}
I was wondering if anybody here knows how to make a seamlessly endless loop with shapes using a timer. Basically I'm trying to make a new set of moving shapes while the current set of shapes is moving so that it looks like it's just infinitely moving along the top of the screen. I have tried the if statements alongside the public int getX(){return x;)}, but I have not succeeded in doing so. Maybe it's possible to have a second timer linked with a second set of shapes and set a delay time? (However, I do not know how to go about writing a second timer and I do not know how to set a delay, help me??)
Any solutions or suggestions?
Here is an example, notice how the set of shapes is redrawn after all of the shapes pass the screen. This is not what I want. I want it to appear as if it were infinitely running along the top of the screen in smooth succession.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExampleLoop extends JPanel implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ExampleLoop());
frame.setVisible(true);
}
Timer timer = new Timer(50, this);
int x = 0, velX = 7;
// CHRISTMAS THEME :D
public void paintComponent(Graphics g) {
g.setColor(Color.RED);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.GREEN);
for (int z = 0; z <= 500; z += 100)
g.fillRect(x + z, 0, 20, 20);
timer.start();
}
public void actionPerformed(ActionEvent e) {
if (x < 500) {
velX = velX;
x = x + velX;
}
else {
x = 0;
}
repaint();
}
}
I can't really figure out what going on in your code, but I reproduce the effect you're looking for. You can examine it. It runs.
What i did was make 5 different xPoints. You could have done this by using an array of int but I thouhgt it would be easier to read this way.
For each xPoint, I incremented each timer iteration. If the xPoint reached the screen width, I made it equal 0. Then repaint. I did that for all the points.
Code Edited: to use arrays and loops
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class GreenRects extends JPanel {
private static final int SCREEN_WIDTH = 500;
private static final int SCREEN_HEIGHT = 500;
private static final int OFFSET = 100;
private static final int SIZE = 20;
private static final int INC = 5;
int[] xPoints = new int[5];
public GreenRects() {
int x = 0;
for (int i = 0; i < xPoints.length; i++) {
xPoints[i] = x;
x += OFFSET;
}
Timer timer = new Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < xPoints.length; i++) {
if (xPoints[i] + INC < SCREEN_WIDTH) {
xPoints[i] += INC;
} else {
xPoints[i] = 0;
}
}
repaint();
}
});
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
g.setColor(Color.green);
for (int i = 0; i < xPoints.length; i++) {
g.fillRect(xPoints[i], 0, SIZE, SIZE);
}
}
public Dimension getPreferredSize() {
return new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT);
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new GreenRects());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You can try this code in if clause
if (x < 80)
{
velX = velX;
x = x + velX;
}
I am trying to create a grid UI (5*5) using Swing classes. I tried a nested loop and adding a jPanel dynamically to the jFrame. And I also tried to change the background colour of each jPanel when user clicks and drops over it.
But with my code there are huge gaps between each cell and I can't get the drag event to work.
public class clsCanvasPanel extends JPanel {
private static final int intRows = 5;
private static final int intCols = 5;
private List<JPanel> jpllist = new ArrayList<JPanel>();
public clsCanvasPanel() {
/*
*
* Add eventListener to individual JPanel within CanvasPanel
*
*
* TODO :
* 1) mousePressed --> update Temperature and HeatConstant of clsElement Class
* 2) start a new thread and
* 3) call clsElement.run() method
*
*
* Right Now : it updates the colours of the JPanel
* */
MouseListener mouseListener = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
JPanel panel = (JPanel) e.getSource();
Component[] components = panel.getComponents();
for (Component component : components) {
component.setVisible(!component.isVisible());
component.setBackground(new Color(255,255,0));
}
panel.revalidate();
panel.repaint();
}
};
//TODO : refactoring
GridLayout gdlyPlates = new GridLayout();
gdlyPlates.setColumns(intCols);
gdlyPlates.setRows(intRows);
gdlyPlates.setHgap(0);
gdlyPlates.setVgap(0);
setLayout(gdlyPlates);
//TODO : refactoring
for (int row = 0; row < intRows; row++) {
for (int col = 0; col < intCols; col++) {
JPanel panel = new JPanel(new GridBagLayout());
panel.setOpaque(false);
JPanel jl = new JPanel();
jl.setVisible(true);
panel.add(jl);
panel.addMouseListener(mouseListener);
jpllist.add(panel);
add(panel);
}
}
}
}
So now I am trying to create one panel and draw grids on it, then detects the mouse position on the grid, further change the colour of each cell.
Could someone give me some advices on how to implement this grid on JPanel, and change the colour of a chosen cell.
There are any number of ways to get this to work, depending on what it is you want to achieve.
This first example simply uses the 2D Graphics API to render the cells and a MouseMotionListener to monitor which cell is highlighted.
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.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestGrid01 {
public static void main(String[] args) {
new TestGrid01();
}
public TestGrid01() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int columnCount = 5;
private int rowCount = 5;
private List<Rectangle> cells;
private Point selectedCell;
public TestPane() {
cells = new ArrayList<>(columnCount * rowCount);
MouseAdapter mouseHandler;
mouseHandler = new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
Point point = e.getPoint();
int width = getWidth();
int height = getHeight();
int cellWidth = width / columnCount;
int cellHeight = height / rowCount;
selectedCell = null;
if (e.getX() >= xOffset && e.getY() >= yOffset) {
int column = (e.getX() - xOffset) / cellWidth;
int row = (e.getY() - yOffset) / cellHeight;
if (column >= 0 && row >= 0 && column < columnCount && row < rowCount) {
selectedCell = new Point(column, row);
}
}
repaint();
}
};
addMouseMotionListener(mouseHandler);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
public void invalidate() {
cells.clear();
selectedCell = null;
super.invalidate();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
int cellWidth = width / columnCount;
int cellHeight = height / rowCount;
int xOffset = (width - (columnCount * cellWidth)) / 2;
int yOffset = (height - (rowCount * cellHeight)) / 2;
if (cells.isEmpty()) {
for (int row = 0; row < rowCount; row++) {
for (int col = 0; col < columnCount; col++) {
Rectangle cell = new Rectangle(
xOffset + (col * cellWidth),
yOffset + (row * cellHeight),
cellWidth,
cellHeight);
cells.add(cell);
}
}
}
if (selectedCell != null) {
int index = selectedCell.x + (selectedCell.y * columnCount);
Rectangle cell = cells.get(index);
g2d.setColor(Color.BLUE);
g2d.fill(cell);
}
g2d.setColor(Color.GRAY);
for (Rectangle cell : cells) {
g2d.draw(cell);
}
g2d.dispose();
}
}
}
This example does resize the grid with the window, but it would be a trivial change to make the cells fixed size.
Check out 2D Graphics for more details
Update with component example
This example uses a series of JPanels to represent each cell.
Each cell is defined with a fixed width and height and do not resize with the main window.
In this example, each cell panel has it's own mouse listener. It wouldn't be overly difficult to re-code it so that the main panel had a single mouse listener and managed the work load itself instead.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.MatteBorder;
public class TestGrid02 {
public static void main(String[] args) {
new TestGrid02();
}
public TestGrid02() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
gbc.gridx = col;
gbc.gridy = row;
CellPane cellPane = new CellPane();
Border border = null;
if (row < 4) {
if (col < 4) {
border = new MatteBorder(1, 1, 0, 0, Color.GRAY);
} else {
border = new MatteBorder(1, 1, 0, 1, Color.GRAY);
}
} else {
if (col < 4) {
border = new MatteBorder(1, 1, 1, 0, Color.GRAY);
} else {
border = new MatteBorder(1, 1, 1, 1, Color.GRAY);
}
}
cellPane.setBorder(border);
add(cellPane, gbc);
}
}
}
}
public class CellPane extends JPanel {
private Color defaultBackground;
public CellPane() {
addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
defaultBackground = getBackground();
setBackground(Color.BLUE);
}
#Override
public void mouseExited(MouseEvent e) {
setBackground(defaultBackground);
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
}
}
I did not like rendering of borders since inside the grid some were duplicated if there were more than the example. I think that this solution is better:
private int width;
private int height;
// ...
for (int row = 0; row <= this.height; row++) {
for (int col = 0; col <= this.width; col++) {
gbc.gridx = col;
gbc.gridy = row;
CellPane cellPane = new CellPane();
Border border = new MatteBorder(1, 1, (row == this.height ? 1 : 0), (col == this.width ? 1 : 0), Color.GRAY);
cellPane.setBorder(border);
this.add(cellPane, gbc);
}
}
Edit:
My solution is better, because if the original code will be 5x5 cells, but more, such as 10x10 ... inner edges of some cells will be in contact and to create some places thick grid. It's nice to see on the screenshot
thick grid
In the MouseListener example in the mouseMoved method, you might want to consider the xOffset/yOffset though for a smoother cell recognition.
int column = (x - xOffset) / cellWidth;
int row = (y - yOffset) / cellHeight;
I need help with drawing the grids to the GUI as well as the program later letting me change the colour of the boxes drawn. I know i will have to use paintComponent(Graphics g), but i have no idea how or where.
So here is a copy of the code i have got so far ( even though i have been told it can be quite daunting just being given code i think it is the best way for people to help and not just do it for me). From the top it sets values, creates the GUI, calls the GUI, fills a 2d array with boxes( i think). Then in the Boxes class setting values the boxes class will need, then the start of how to draw them (didn't know how to work it out), then some seta methods for the x and y coordinates.
what i would like you to do is show how to have the boxes be drawn to the Jpanel, to make a grid and then to show me how to change the colour to different shades of blue, depending on a external value.
import java.awt.*;
import java.awt.Graphics;
import java.util.*;
import javax.swing.*;
public class NewGrid {
Boxes[][] Boxs;
int BoxesX;
int BoxesY;
NewGrid() {
buildtheGUI();
}
JFrame frame = new JFrame();
JPanel panel = new JPanel();
public void buildtheGUI() {
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new NewGrid();
}
public void addboxes() {
Boxs = new Boxes[panel.getWidth() / 10][panel.getHeight() / 10];
for (int i = 0; i < panel.getWidth() / 10; i++) {
for (int j = 0; j < panel.getHeight() / 10; j++) {
Boxs[i][j] = new Boxes();
Boxs[i][j].setx(i * (panel.getWidth() / 10));
Boxs[i][j].sety(j * (panel.getHeight() / 10));
Boxs[i][j].draw(null);
}
}
}
}
public class Boxes extends JPanel {
int x;
int y;
int width = 10;
int hieight = 10;
Color colour = Color.BLACK;
public void draw(Graphics g) {
g.setColor(colour);
g.fillRect(x, y, width, hieight);
}
public void setx(int i ){
x = i;
}
public void sety(int i ){
y = i;
}
}
I can't comment something, to try to make things easier,
I code there box.putClientProperty(unique_identifier, value_for_identifier), you can to multiple this method as you want
from every Swing Listener you can to get this and proper coordinated defined in putClientProperty
.
JComponent comp = event.getComponent();
String strRow = (String) comp.getClientProperty("row");
String strColumn = (String) comp.getClientProperty("column");
simple code
import java.awt.*;
import java.awt.Graphics;
import java.util.*;
import javax.swing.*;
public class NewGrid {
private int row = 10;
private int column = 10;
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private NewGrid() {
addboxes();
panel.setLayout(new GridLayout(row, column));
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void addboxes() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
Boxes box = new Boxes();
box.putClientProperty("row", row);
box.putClientProperty("column", column);
panel.add(box);
}
}
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
#Override
public void run() {
new NewGrid();
}
};
SwingUtilities.invokeLater(doRun);
}
}
class Boxes extends JPanel {
private static final long serialVersionUID = 1L;
#Override
public Dimension getMinimumSize() {
return new Dimension(20, 20);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(20, 20);
}
#Override
public void paintComponent(Graphics g) {
int margin = 2;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2,
dim.height - margin * 2);
}
}