I am trying to create a DFS generated maze. I started by making a Cell object that has 4 lines (Top, Right, Bottom and Left). I then drew these lines on to a Maze JPanel. My problem is that most of the cells look fine but the left and top side of the JPanel have thick lines and I can't figure out how to make it just a regular grid.
Here is my Cell where I create the lines:
boolean[] walls = {true, true, true, true};
// Draw the lines of one cell with w width and h height
void drawCell(Graphics g, int w, int h){
// Set the color of the lines to white
g.setColor(Color.WHITE);
// If the top wall exists draw a top line
if (walls[0]) {
g.drawLine(TopLeftX(), TopLeftY(), TopRightX(w), TopRightY());
}
// If a right wall exists draw a right line
if (walls[1]) {
g.drawLine(TopRightX(w), TopRightY(), BotRightX(w), BotRightY(h));
}
// If a bottom wall exists draw a bottom line
if (walls[2]) {
g.drawLine(BotRightX(w), BotRightY(h), BotLeftX(), BotLeftY(h));
}
// If a left wall exists draw a left line
if (walls[3]) {
g.drawLine(BotLeftX(), BotLeftY(h), TopLeftX(), TopLeftY());
}
}
// Set each coordinate for the lines, these will make a square that
// is w wide and h high
private int TopLeftX() { return i; }
private int TopLeftY() { return j; }
private int TopRightX(int w){ return i * w; }
private int TopRightY() { return j; }
private int BotRightX(int w){ return i * w; }
private int BotRightY(int h){ return j * h; }
private int BotLeftX() { return i; }
private int BotLeftY(int h) { return j * h; }
w is the width of a cell and h is the height.
And here is my MazeView JPanel where I draw the lines:
class MazeView extends JPanel{
private Cell grid[][];
private Cell cell;
private int row;
private int col;
private int width = 600;
private int height = 580;
// Create a maze view JPanel that is rows tall and cols wide
MazeView(int rows, int cols){
super.setBackground(Color.BLACK);
super.setLayout(new GridLayout(rows, cols));
newGrid(rows, cols);
}
// Paint all the cells
public void paintComponent(Graphics g){
super.paintComponent(g);
// Get the height and width of each cell
int h = height / getRows();
int w = width / getCols();
// Loop to draw each cell
for (int i = 0; i <= getRows(); i++){
for (int j = 0; j <= getCols(); j++){
grid[i][j].drawCell(g, w, h);
}
}
}
}
I appreciate any help I can get.
When this is run my grid looks like this:
Have a look at g.drawLine(TopLeftX(), TopLeftY(), TopRightX(w), TopRightY()); - resolving the values of those methods you get coordinates i, j, i*w, j. Assuming that i and j are the cell positions you'll draw a line
for cell 0/0 from 0/0 to 0/0
for cell 1/0 from 1/0 to w/0
for cell 0/1 from 0/1 to 0/1
for cell 2/2 from 2/2 to 2*w/2
etc.
Thus you'll want to correct your coordinate calculation for all 4 draw commands.
Assuming i andj are the cell's grid coordinates and w and h are the dimensions of the cell the coordinates for the top left corner would then be i * w and j * h and for the bottom right corner (i + 1) * w and (j + 1) * h.
Example:
0 3 6 9
--------------> x
0 | +---+---+---+
| |0/0|1/0|2/0|
3 | +---+---+---+
| |0/1|1/1|2/1|
6 | +---o---+---+
| |0/2|1/2|2/2|
9 | +---+---O---+
V
y
Let's assume each cell has a width and hight of 3 pixels. Thus the coordinates for the bottom center cell are:
top left (o): x = i * w = 1 * 3 = 3 and y = j * h = 2 * 3 = 6
bottom right (O): x = (i + 1) * w = (1 + 1) * 3 = 6 and y = (j + 1) * h = (2 + 1) * 3 = 9.
Well it isn't a maze yet. Im starting by drawing each cell
Don't fully grasp what you are attempting, but I would think a cell needs to be different colors, not lines. So for example a white cell is a place a player can move to. A black cell is a wall. I'm not sure how drawing individual line will make a maze?
I am trying to create a DFS generated maze.
Don't know what that is, but here is some old code that might give you some ideas.
This is designed to be a maze and you paint icons (instead of colors as I suggested above) for each cell. In this basic implementation you only have two types of icons:
a floor
a wall
A file containing 0/1 is used to identify each cell and therefore the icon of the cell
You then have a playing piece that can move from floor to floor and is blocked when it hits a wall.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SmallWorld extends JPanel implements KeyListener, ActionListener
{
//WORLD
String[][] worldArray = new String[30][30];
//Block colors
private static Color redBlock = new Color(255,0,0,255);
private static Color whiteBlock = new Color(255,255,255,255);
private static Color blackBlock = new Color(0,0,0,150);
//World images
// JLabel wall = new JLabel( new ImageIcon("wall.gif") );
// JLabel floor = new JLabel( new ImageIcon("floor.gif") );
ImageIcon wallIcon = new ImageIcon("dukewavered.gif");
ImageIcon floorIcon = new ImageIcon("copy16.gif");
//Starting coordinates
int blockPositionX = 1;
int blockPositionY = 1;
//Typing area to capture keyEvent
JTextField typingArea;
//Viewable area
JViewport viewable;
String type = "";
JLayeredPane layeredPane;
JPanel worldBack;
JPanel panel;
JPanel player;
Dimension worldSize = new Dimension(1500, 1500);
public SmallWorld() {
super( );
createWorld();
layeredPane = new JLayeredPane();
add(layeredPane);
layeredPane.setPreferredSize( worldSize );
worldBack = new JPanel();
layeredPane.add(worldBack, JLayeredPane.DEFAULT_LAYER);
worldBack.setLayout( new GridLayout(30, 30) );
worldBack.setPreferredSize( worldSize );
worldBack.setBounds(0, 0, worldSize.width, worldSize.height);
worldBack.setBackground( whiteBlock );
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 30; j++) {
JPanel square = new JPanel( new BorderLayout() );
worldBack.add( square );
type = worldArray[i][j];
if ( type.equals("1") )
{
square.add( new JLabel(wallIcon) );
}
else
{
square.add( new JLabel(floorIcon) );
}
}
}
//Draw the player
player = new JPanel();
player.setBounds(50, 50, 50, 50);
player.setBackground( Color.black );
player.setLocation(50, 50);
layeredPane.add(player, JLayeredPane.DRAG_LAYER);
//set where the player starts
// panel = (JPanel)worldBack.getComponent( 31 );
// panel.add( player );
//Create the typing area with keyListener, add to window
typingArea = new JTextField(20);
typingArea.addKeyListener(this);
typingArea.setEditable( false );
add(typingArea);
}
//Get the world from the DAT file and translate it into
//a 2d array to be used by paintComponent
public void createWorld() {
String getData = null;
int countRow = 0;
try {
//Get file
FileReader fr = new FileReader("world.dat");
BufferedReader br = new BufferedReader(fr);
getData = new String();
//read each line from file, store to 2d array
while ((getData = br.readLine()) != null) {
if(countRow < 30) {
for (int i = 0; i < 30; i++) {
String temp = "" + getData.charAt(i);
worldArray[countRow][i] = temp;
}
countRow++;
}
}
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}
}
//Move Block around the world
public void moveBlock() {
Point pt = new Point();
pt.x = blockPositionX * 50;
pt.y = blockPositionY * 50;
int x = Math.max(0, pt.x - 250);
int y = Math.max(0, pt.y - 250);
Rectangle r = new Rectangle(x, y, 550, 550);
scrollRectToVisible( r );
}
//check for collisions with blocks
public boolean checkCollision(int row, int col) {
if ( worldArray[col][row].equals("1") ) {
return true;
}
else {
return false;
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
updateView( e );
e.consume();
}
public void keyReleased(KeyEvent e) {
}
public void actionPerformed(ActionEvent e) {
}
//Update the view of the window based on which button is pressed
protected void updateView( KeyEvent e ) {
//if UP
if ( e.getKeyCode() == 38 ) {
if ( checkCollision( blockPositionX, blockPositionY - 1 ) == false ) {
blockPositionY = blockPositionY - 1;
moveBlock();
player.setLocation(blockPositionX *50, blockPositionY*50);
}
}
//if DOWN
if ( e.getKeyCode() == 40 ) {
if ( checkCollision( blockPositionX, blockPositionY + 1 ) == false ) {
blockPositionY = blockPositionY + 1;
moveBlock();
player.setLocation(blockPositionX *50, blockPositionY*50);
}
}
//if LEFT
if ( e.getKeyCode() == 37 ) {
if ( checkCollision( blockPositionX - 1, blockPositionY ) == false ) {
blockPositionX = blockPositionX - 1;
moveBlock();
player.setLocation(blockPositionX *50, blockPositionY*50);
}
}
//if RIGHT
if ( e.getKeyCode() == 39 ) {
if ( checkCollision( blockPositionX + 1, blockPositionY ) == false ) {
blockPositionX = blockPositionX + 1;
moveBlock();
player.setLocation(blockPositionX *50, blockPositionY*50);
}
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("SmallWorld");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new SmallWorld();
newContentPane.setPreferredSize( new Dimension(1500, 1500) );
JScrollPane scrollPane = new JScrollPane( newContentPane );
scrollPane.setPreferredSize( new Dimension(568, 568) );
frame.getContentPane().add( scrollPane );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setResizable( false );
//frame.setSize(500,520);
frame.setVisible( true );
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater( new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You will need a couple of small icons to represent the floor/wall.
You will also need a file to represent the maze. Here is an example "world.dat" file:
111111111111111111111111111111
100010001010001000101000100011
100010001010001000101000100011
100011101010000000001000000001
100010000010000000001000000001
100110000010000000001000000001
100000000010000000001000000001
111100011110000000001000000001
100000000110001110111000111011
100000000000001110111000111011
100000000000000000000000000001
100010001110000000000000000001
100010001110001110111000111011
100011101100000000000000000011
100010000110001110111000111011
100110000100000000000000000011
100000000110000000001000000001
111100011100000000000000000011
100000000100000000000000000011
100000000010000000000000000001
100000000010000000000000000001
100010000000000000000000000001
100010000000001110111000111011
100011101110000000011000000001
100010000110000000011000000001
100110000110000000001000000001
100000000110001110111000111011
111100011110000000011000000001
100000000110000000011000000001
111111111111111111111111111111
Related
I have the weirdest bug ever.
I have this puzzle game that moves puzzle pieces (which really are buttons with images attached to them).
Everything worked fine until I tried to change the text of some label (to indicate how many steps the player has done).
Everytime I call someControl.setText("text");, the puzzle pieces that moved are set back to the their first position. I have no idea why, but they just do.
Here's my window:
It consists of two panels, each uses a GridBagLayout.
The main frame uses a gridBagLayout as well, which consists of the two panels.
I know it's weird as hell, but I can't figure out what may cause this GUI bug. Any idea?
The pieces of code:
increaseSteps which is called everytime I click a puzzle button
void increaseSteps() {
_steps++;
_lblSteps.setText("Steps: " + _steps);
}
Creation of the puzzle panel (the left panel)
private JPanel puzzlePanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int i = 0; i < _splitImage.getSize(); i++)
for (int j = 0; j < _splitImage.getSize(); j++) {
int valueAtPos = _board.getMatrix()[i][j];
if (valueAtPos == 0)
continue;
int imageRow = _board.getImageRowFromValue(valueAtPos);
int imageCol = _board.getImageColFromValue(valueAtPos);
ImageIcon imageIcon = new ImageIcon(_splitImage.getImages()[imageRow][imageCol]);
JButton btn = new JButton(imageIcon);
_tileButtons[i][j] = new TileButton(btn, i, j);
btn.setPreferredSize(new Dimension(_splitImage.getImages()[i][j].getWidth(null),
_splitImage.getImages()[i][j].getHeight(null)));
// add action listener
btn.addActionListener(this);
btn.addKeyListener(this);
gbc.gridx = j;
gbc.gridy = i;
panel.add(_tileButtons[i][j].getButton(), gbc);
}
return panel;
}
actionPerformed:
#Override
public void actionPerformed(ActionEvent e) {
if (!(e.getSource() instanceof JButton))
return;
JButton btn = (JButton) e.getSource();
TileButton tile = getTileButtonFromBtn(btn);
if (tile == null)
return;
// check if we can move the tile
String moveDir = _board.canMoveTile(tile.getRow(), tile.getCol());
if (moveDir.equals("no"))
return;
increaseSteps();
int dirx = 0;
int diry = 0;
if (moveDir.equals("left")) {
dirx = -1;
_board.move("left", true);
tile.setCol(tile.getCol() - 1);
} else if (moveDir.equals("right")) {
dirx = 1;
_board.move("right", true);
tile.setCol(tile.getCol() + 1);
} else if (moveDir.equals("up")) {
diry = -1;
_board.move("up", true);
tile.setRow(tile.getRow() - 1);
} else { // down
diry = 1;
_board.move("down", true);
tile.setRow(tile.getRow() + 1);
}
moveButton(btn, dirx, diry, MOVE_SPEED);
if (_board.hasWon())
win();
}
moveButton: (moves the button in a seperate thread, calling btn.setLocation())
private void moveButton(JButton btn, int dirx, int diry, int speed) {
Point loc = btn.getLocation();
// get start ticks, calculate distance etc...
StopWatch stopper = new StopWatch();
int distance;
if (dirx != 0)
distance = _splitImage.getImages()[0][0].getWidth(null) * dirx;
else
distance = _splitImage.getImages()[0][0].getHeight(null) * diry;
if (speed > 0) {
// run the animation in a new thread
Thread thread = new Thread() {
public void run() {
int currentTicks;
int elapsed;
do {
int newX = loc.x;
int newY = loc.y;
elapsed = stopper.getElapsed();
int moved = (int) ((double) distance * (double) (elapsed / (double) speed));
if (dirx != 0)
newX += moved;
else
newY += moved;
btn.setLocation(newX, newY);
} while (elapsed <= MOVE_SPEED);
// make sure the last location is exact
btn.setLocation(loc.x + (dirx == 0 ? 0 : distance), loc.y + (diry == 0 ? 0 : distance));
}
};
thread.start();
}
else
btn.setLocation(loc.x + (dirx == 0 ? 0 : distance), loc.y + (diry == 0 ? 0 : distance));
}
You're trying to set the absolute position of a component via setLocation(...) or setBounds(...), one that is held by a container that uses a layout manager. This may work temporarily, but will fail if the container's layout manager is triggered to re-do the layout of its contained components. When that happens, the GridBagConstraints will take over and the components will move to their gridbag constraints assigned location.
The solution is to not do this, and instead to place the location of your components in concert with the layout managers used.
Another problem is that your current code is not Swing thread-safe since you're making Swing state changes from within a background thread. This won't always cause problems, but since it's a threading issue, risks causing intermittent hard to debug problems (ones that usually only occur when your boss or instructor are trying to run your code).
Possible solutions:
For a grid of images, you could use a grid of JLabels (or JButtons if you must) held in a container that uses GridLayout. When you need to reposition components, remove all components held by that JPanel, and then re-add, using the order of addition to help you position the components.
Easiest though would be to use a grid of non-moving JLabels, give them MouseListeners, and instead of moving the JLabels, remove and add Icons to them, including a blank Icon.
If you need to do Swing animation, use a Swing Timer to drive the animation. This will allow your code to make repetitive calls with delay between the calls, and with these calls being made on the Swing event thread, the EDT (event dispatch thread).
Demo proof of concept example code that shows swapping icons, but without animation, and without test of solution yet:
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class ImageShuffle extends JPanel {
private static final int SIDES = 3;
public static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia/commons/"
+ "thumb/5/5a/Hurricane_Kiko_Sep_3_1983_1915Z.jpg/"
+ "600px-Hurricane_Kiko_Sep_3_1983_1915Z.jpg";
private List<Icon> iconList = new ArrayList<>(); // shuffled icons
private List<Icon> solutionList = new ArrayList<>(); // in order
private List<JLabel> labelList = new ArrayList<>(); // holds JLabel grid
private Icon blankIcon;
public ImageShuffle(BufferedImage img) {
setLayout(new GridLayout(SIDES, SIDES, 1, 1));
fillIconList(img); // fill array list with icons and one blank one
Collections.shuffle(iconList);
MyMouseListener myMouse = new MyMouseListener();
for (Icon icon : iconList) {
JLabel label = new JLabel(icon);
label.addMouseListener(myMouse);
add(label);
labelList.add(label);
}
}
private class MyMouseListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
JLabel selectedLabel = (JLabel) e.getSource();
if (selectedLabel.getIcon() == blankIcon) {
return; // don't want to move the blank icon
}
// index variables to hold selected and blank JLabel's index location
int selectedIndex = -1;
int blankIndex = -1;
for (int i = 0; i < labelList.size(); i++) {
if (selectedLabel == labelList.get(i)) {
selectedIndex = i;
} else if (labelList.get(i).getIcon() == blankIcon) {
blankIndex = i;
}
}
// get row and column of selected JLabel
int row = selectedIndex / SIDES;
int col = selectedIndex % SIDES;
// get row and column of blank JLabel
int blankRow = blankIndex / SIDES;
int blankCol = blankIndex % SIDES;
if (isMoveValid(row, col, blankRow, blankCol)) {
Icon selectedIcon = selectedLabel.getIcon();
labelList.get(selectedIndex).setIcon(blankIcon);
labelList.get(blankIndex).setIcon(selectedIcon);
// test for win here by comparing icons held by labelList
// with the solutionList
}
}
private boolean isMoveValid(int row, int col, int blankRow, int blankCol) {
// has to be on either same row or same column
if (row != blankRow && col != blankCol) {
return false;
}
// if same row
if (row == blankRow) {
// then columns must be off by 1 -- they're next to each other
return Math.abs(col - blankCol) == 1;
} else {
// or else rows off by 1 -- above or below each other
return Math.abs(row - blankRow) == 1;
}
}
public void shuffle() {
Collections.shuffle(iconList);
for (int i = 0; i < labelList.size(); i++) {
labelList.get(i).setIcon(iconList.get(i));
}
}
}
private void fillIconList(BufferedImage img) {
// get the width and height of each individual icon
// which is 1/3 the image width and height
int w = img.getWidth() / SIDES;
int h = img.getHeight() / SIDES;
for (int row = 0; row < SIDES; row++) {
int y = (row * img.getWidth()) / SIDES;
for (int col = 0; col < SIDES; col++) {
int x = (col * img.getHeight()) / SIDES;
// create a sub image
BufferedImage subImg = img.getSubimage(x, y, w, h);
// create icon from the image
Icon icon = new ImageIcon(subImg);
// add to both icon lists
iconList.add(icon);
solutionList.add(icon);
}
}
// create a blank image and corresponding icon as well.
BufferedImage blankImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
blankIcon = new ImageIcon(blankImg);
iconList.remove(iconList.size() - 1); // remove last icon from list
iconList.add(blankIcon); // and swap in the blank one
solutionList.remove(iconList.size() - 1); // same for the solution list
solutionList.add(blankIcon);
}
private static void createAndShowGui(BufferedImage img) {
JFrame frame = new JFrame("ImageShuffle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ImageShuffle(img));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
URL imgUrl = null;
BufferedImage img;
try {
imgUrl = new URL(IMG_PATH);
img = ImageIO.read(imgUrl);
SwingUtilities.invokeLater(() -> createAndShowGui(img));
} catch (IOException e) {
e.printStackTrace();
}
}
}
If I wanted animation, again, I'd raise the icon into the JFrame's glasspane, animate it to the new position using a Swing Timer, and then place the icon into the new JLabel. I'd also disable the MouseListener using a boolean field, a "flag", until the animation had completed its move.
I have a Board 14x14 which has JButtons and every Jbutton has a different color. When you click one of those buttons, it checks the neighbors with the same color and removes them. When it removes them, theres a blank space between the board so the above buttons, should move down to fill the blank space. I tried with GridLayout but I don't know how to move the above buttons.
This actually is a case where you can hardly use a layout manager at all.
A LayoutManager is supposed to compute the layout of all components at once. It is triggered by certain events (e.g. when the parent component is resized). Then it computes the layout and arranges the child components accordingly.
In your case, the situation is quite different. There is no layout manager that can sensibly represent the "intermediate" state that appears while the upper buttons are falling down. While the components are animated, they cannot be part of a proper layout.
The animation itself may also be a bit tricky, but can fortunately be solved generically. But you still have to keep track of the information about where each component (i.e. each button) is currently located in the grid. When one button is removed, you have to compute the buttons that are affected by that (namely, the ones directly above it). These have to be animated. After the animation, you have to assign the new grid coordinates to these buttons.
The following is a MCVE that shows one basic approach. It simply removes the button that was clicked, but it should be easy to generalize it to remove other buttons, based on other conditions.
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class FallingButtons
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int rows = 8;
int cols = 8;
GridPanel gridPanel = new GridPanel(rows, cols);
for (int r=0; r<rows; r++)
{
for (int c=0; c<cols; c++)
{
JButton button = new JButton(r+","+c);
gridPanel.addComponentInGrid(r, c, button);
button.addActionListener(e ->
{
Point coordinates = gridPanel.getCoordinatesInGrid(button);
if (coordinates != null)
{
gridPanel.removeComponentInGrid(
coordinates.x, coordinates.y);
}
});
}
}
f.getContentPane().add(gridPanel);
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class GridPanel extends JPanel
{
private final int rows;
private final int cols;
private final JComponent components[][];
GridPanel(int rows, int cols)
{
super(null);
this.rows = rows;
this.cols = cols;
this.components = new JComponent[rows][cols];
addComponentListener(new ComponentAdapter()
{
#Override
public void componentResized(ComponentEvent e)
{
layoutGrid();
}
});
}
private void layoutGrid()
{
int cellWidth = getWidth() / cols;
int cellHeight = getHeight() / rows;
for (int r=0; r<rows; r++)
{
for (int c=0; c<cols; c++)
{
JComponent component = components[r][c];
if (component != null)
{
component.setBounds(
c * cellWidth, r * cellHeight, cellWidth, cellHeight);
}
}
}
}
Point getCoordinatesInGrid(JComponent component)
{
for (int r=0; r<rows; r++)
{
for (int c=0; c<cols; c++)
{
if (components[r][c] == component)
{
return new Point(r, c);
}
}
}
return null;
}
void addComponentInGrid(int row, int col, JComponent component)
{
add(component);
components[row][col] = component;
layoutGrid();
}
JComponent getComponentInGrid(int row, int col)
{
return components[row][col];
}
void removeComponentInGrid(int row, int col)
{
remove(components[row][col]);
components[row][col] = null;
List<Runnable> animations = new ArrayList<Runnable>();
for (int r=row-1; r>=0; r--)
{
JComponent component = components[r][col];
if (component != null)
{
Runnable animation =
createAnimation(component, r, col, r + 1, col);
animations.add(animation);
}
}
for (Runnable animation : animations)
{
Thread t = new Thread(animation);
t.setDaemon(true);
t.start();
}
repaint();
}
private Runnable createAnimation(JComponent component,
int sourceRow, int sourceCol, int targetRow, int targetCol)
{
int cellWidth = getWidth() / cols;
int cellHeight = getHeight() / rows;
Rectangle sourceBounds = new Rectangle(
sourceCol * cellWidth, sourceRow * cellHeight,
cellWidth, cellHeight);
Rectangle targetBounds = new Rectangle(
targetCol * cellWidth, targetRow * cellHeight,
cellWidth, cellHeight);
Runnable movement = createAnimation(
component, sourceBounds, targetBounds);
return () ->
{
components[sourceRow][sourceCol] = null;
movement.run();
components[targetRow][targetCol] = component;
repaint();
};
}
private static Runnable createAnimation(JComponent component,
Rectangle sourceBounds, Rectangle targetBounds)
{
int delayMs = 10;
int steps = 20;
Runnable r = () ->
{
int x0 = sourceBounds.x;
int y0 = sourceBounds.y;
int w0 = sourceBounds.width;
int h0 = sourceBounds.height;
int x1 = targetBounds.x;
int y1 = targetBounds.y;
int w1 = targetBounds.width;
int h1 = targetBounds.height;
int dx = x1 - x0;
int dy = y1 - y0;
int dw = w1 - w0;
int dh = h1 - h0;
for (int i=0; i<steps; i++)
{
double alpha = (double)i / (steps - 1);
int x = (int)(x0 + dx * alpha);
int y = (int)(y0 + dy * alpha);
int w = (int)(w0 + dw * alpha);
int h = (int)(h0 + dh * alpha);
SwingUtilities.invokeLater(() ->
{
component.setBounds(x, y, w, h);
});
try
{
Thread.sleep(delayMs);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
return;
}
}
SwingUtilities.invokeLater(() ->
{
component.setBounds(x1, y1, w1, h1);
});
};
return r;
}
}
You could try using a 2-dimensional array of JButtons
JButton[][] buttons = new JButton[14][14];
for (int i=0; i < buttons.length; i++) {
for (int j=0; j < buttons[i].length; j++) {
buttons[i][j] = new JButton("Button [" + i + "][" + j + "]");
}
}
// Then do whatever,remove,change color,check next element in array
// and compare colors etc
buttons[2][3].setText("changed text");
If you want the above buttons to take more space to fill the empty space when you remove a component well, this is not possible using GridLayout, but you can add some empty components like JLabels to fill the space.
You can add a component in a container at a specific index for this purpose, by using Container's add (Component comp, int index) method.
This code snippet will replace a button at a specified index (45, just for example) with a blank component in a panel which has a GridLayout set:
JPanel boardPanel = new JPanel (new GridLayout (14, 14));
// ... add your buttons ...
// This code could be invoked inside an ActionListener ...
boardPanel.remove (45);
boardPanel.add (new JLabel (""), 45);
boardPanel.revalidate ();
boardPanel.repaint ();
This way, the rest of the components will not move, and you will just see a blank space replacing your button.
You can achieve more: if you add the empty label at index = 0, all the buttons will move to the right (remember that the number of components should not change, else the components will resize and you could obtain bad behaviour), and so on, you can "move" a single component by simply removing it and adding it at a different index.
Another way to go would be to store a 2-dimensional array of objects representing your model logic (you can store color and all the stuff you need), and painting them on your own by overriding paintComponent method.
For an example of a custom painting approach, take a look at this MadProgrammer's answer, where he shows how to highlight a specific cell in a grid (in this case he uses a List to store objects, but a 2d array will work as well).
I have a chessboard, made by overriding the paint() method of a class extending Panel. I highlight all the possible squares a chess piece can go to on the board, and store the pixel values of the upper left corners of the highlighted squares in the:
private ArrayList<Integer> highlightedSquares = new ArrayList<Integer>();
topLeftVal is an array with all of the top left corner values of the squares. In the mouseClicked method of the mouseAdapter, I want to know when a highlighted square (and only a highlighted square) is clicked, and then call repaint(). However, for some reason the program also accepts many squares that are not highlighted.
Here is the code (I apologize for the formatting):
public void mouseClicked(MouseEvent e){
clickPointX = e.getX();
clickPointY = e.getY();
//iterate through highlightedSquares and if the clicked pt is in one of them, repaint
int q = 0;
int xCoor = 0, yCoor = 0;
for(int a : highlightedSquares){
if(q % 2 == 0)
xCoor = a;
else{
yCoor = a;
if((xCoor <= clickPointX) && (clickPointX <= (xCoor + 80)) && (yCoor <= clickPointY) && (clickPointY <= (yCoor + 80))){ //I think this line is causing the problem?
_pixX=xCoor;
_pixY=yCoor;
for(int i = 0; i < topLeftVal.length;i++){
if(topLeftVal[i] == _pixX)
_x = i;
if(topLeftVal[i] == _pixY)
_y = i;
}
repaint();
break;
} //end of if inside else
} //end of else
q++;
} //end of foreach
} //end of mouseClicked
Here is an example implementation where I defined two classes -- Board and Square. Board is derived from JPanel. Square represents a single square on the board. My mouse click listener displays a message which indicates whether or not the clicked upon square is highlighted. Hopefully this will give you a good idea of how to modify your code to achieve the desired result.
public class TestMain {
public static void main(String[] args) throws Exception {
new TestMain().run();
}
public void run() {
// create and show a JFrame containing a chess board
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Board board = new Board();
board.getSquare(2, 4).setHighlighted(true);
board.getSquare(3, 4).setHighlighted(true);
window.getContentPane().add(board, BorderLayout.NORTH);
window.pack();
window.setVisible(true);
}
// *** Board represents the chess board
private class Board extends JPanel {
// *** the constructor creates the squares and adds a mouse click listener
public Board() {
setPreferredSize(new Dimension(squareSize * 8, squareSize * 8));
// create the squares
boolean rowStartRedFlag = true;
for (int row = 0; row < 8; row++) {
boolean redFlag = rowStartRedFlag;
for (int column = 0; column < 8; column++) {
squares [row] [column] = new Square(this, row, column, redFlag);
redFlag = !redFlag;
}
rowStartRedFlag = !rowStartRedFlag;
}
// add mouse click listener
this.addMouseListener(new MouseClickListener());
}
// *** mouse click listener
private class MouseClickListener extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
Square square = getSquareAt(e.getX(), e.getY());
String msg = square.isHighlighted() ? "Square is highlighted" : "Square is not highlighted";
JOptionPane.showMessageDialog(null, msg);
}
}
// ** override paint
#Override
public void paint(Graphics g) {
draw ((Graphics2D) g);
}
// *** draw every square on the board
public void draw(Graphics2D g) {
for (int row = 0; row < squares.length; row++) {
for (int column = 0; column < squares [row].length; column++) {
squares [row] [column].draw(g);
}
}
}
// *** get square given row and column
public Square getSquare(int row, int column) {
return squares [row] [column];
}
// *** get square from coords
public Square getSquareAt(int x, int y) {
int column = getColumnAtX(x);
int row = getRowAtY(y);
return squares [row] [column];
}
// *** get column # given x
public int getColumnAtX(int x) {
int column = x / squareSize;
return Math.min(Math.max(column, 0), 7);
}
// *** get row # given x
public int getRowAtY(int y) {
int row = y / squareSize;
return Math.min(Math.max(row, 0), 7);
}
// ** get left x given column
public int getLeftFromColumn(int column) {
return column * squareSize;
}
// ** get top y give row
public int getTopFromRow(int row) {
return row * squareSize;
}
// *** get size of square side
public int getSquareSize() {
return squareSize;
}
private int squareSize = 25; // length of square side
private Square [][] squares = new Square [8][8];
}
// *** Squalre represents one square on the board
private class Square {
// ** constructor creates the square
public Square(Board board, int row, int column, boolean redFlag) {
this.board = board;
this.column = column;
this.row = row;
if (redFlag) {
color = Color.RED;
colorHighlighted = Color.PINK;
} else {
color = Color.BLACK;
colorHighlighted = Color.LIGHT_GRAY;
}
}
// ** set highlight flag
public void setHighlighted(boolean value) {
highlighted = value;
}
// *** see if square is highlighted
public boolean isHighlighted() {
return highlighted;
}
// *** draw the square
public void draw(Graphics2D g) {
Color fillColor = highlighted ? colorHighlighted : color;
g.setColor(fillColor);
int x = board.getLeftFromColumn(column);
int y = board.getTopFromRow(row);
int size = board.getSquareSize();
g.fillRect(x, y, size, size);
}
private Board board;
private Color color;
private Color colorHighlighted;
private int column;
private boolean highlighted = false;
private int row;
}
}
I'm begining a little project to create a simple checkers game. However it's been a long time since I've used the java GUI tools. The goal of the code at this point is to draw the initial board (red pieces at top, black at bottom). However all I get when I run the code is a blank frame. I'm also a little uncertain if my circle drawing code will do what I want (ie create solid red or black circles inside certain squares) Here is the code. Thanks in advance for any help/suggestions
EDIT: I should probably alternate drawing blue and gray squares or else the thing will probably just be a giant blue blob, however I'll settle for a giant blue blob at this point :p
import javax.swing.*;
import java.awt.*;
public class CheckersServer
{
public static class Board
{
private JFrame frame = new JFrame();
private JPanel backBoard = new JPanel();
Board()
{
frame.setSize(905,905);
backBoard.setSize(900,900);
frame.setTitle("Checkers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
backBoard.setVisible(true);
boardSquare bs;
String type = null;
//Filling in Red Side
for (int i = 0; i <=1; i++)
{
for(int j = 0; j < 9; j++)
{
if(j % 2 == 0)
{
type = "Red";
}
else
{
type = "Blank";
}
bs = new boardSquare(100*j,100*i,type);
backBoard.add(bs);
}
}
//Filling in empty middle
type = "Blank";
for (int i = 2; i < 7; i++)
{
for(int j = 0; j < 9; j++)
{
bs = new boardSquare(100*j,100*i,type);
backBoard.add(bs);
}
}
//Filling in Black side
for (int i = 7; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
if(j % 2 != 0)
{
type = "Black";
}
else
{
type = "Blank";
}
bs = new boardSquare(100*j,100*i,type);
backBoard.add(bs);
}
}
backBoard.repaint();
frame.add(backBoard);
frame.repaint();
}
private class boardSquare extends JComponent
{
private int x; //x position of the rectangle measured from top left corner
private int y; //y position of the rectangle measured from top left corner
private boolean isBlack = false;
private boolean isRed = false;
public boardSquare(int p, int q, String type)
{
x = p;
y = q;
if (type.equals("Black"))
{
isBlack = true;
isRed = false;
}
else if (type.equals("Red"))
{
isRed = true;
isBlack = false;
}
else if (type.equals("Blank"))
{
isBlack = false;
isRed = false;
}
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle box = new Rectangle(x,y,100,100);
g2.draw(box);
g2.setPaint(Color.BLUE);
g2.fill(box);
if(isBlack)
{
g2.fillOval(x, y,100 ,100 );
g2.setColor(Color.black);
g2.drawOval(x, y, 100, 100);
}
else if(isRed)
{
g2.fillOval(x, y,100 ,100 );
g2.setColor(Color.red);
g2.drawOval(x, y, 100, 100);
}
}
}
}
public static void main(String[] args)
{
Board game = new Board();
}
}
You have several issues.
Java UI is layout-based, which means that when you add a component to a parent, the parent's layout determines where the child component will be placed. You don't have any code to set up the layout, and so your application is using the defaults (FlowLayout is the default, and this may work in your case, as long as your JFrame and children are the appropriate size).
The bigger problems are in your boardSquare class. By default, JPanels have a dimension of 10x10. You aren't specifying the size, and so all your squares are 10x10. You need to tell the squares how big they are. You can do this in the boardSquare constructor:
setPreferredSize(new Dimension(100, 100));
Finally, in your drawing code, you are doing an offset of x,y when drawing the squares and circles. This is an offset from the top-left corner of the component. Your components (after setting the size) will be 100x100 pixels. But if your x,y are greater than these values, you will be drawing outside of the bounds of the component. Instead, these values should be set to 0,0 because that is the top-left corner of the component you are drawing in.
By just setting the preferred size of the squares and setting x,y to 0, I was able to get the squares drawing in the frame, though it wasn't pretty. You will need to work on setting the correct layout before it will be laid out correctly.
Here are some hints:
Your BoardSquares have dimension 0x0. Not a good size for something you want to be visible to the user.
To help visualize what's going on, cause each BoardSquare to be 100x100 pixels in size, and give them a border. Now you can see where they are showing up in your GUI. Your GUI code still needs significant changes, but this will at least let you start seeing what you're dealing with.
public BoardSquare(int p, int q, String type)
{
this.setBorder(new LineBorder(Color.CYAN, 2));
this.setPreferredSize(new Dimension(100, 100));
// ... etc ...
BoardSquare seems to be coded to draw its contents based on coordinates from the absolute topmost leftmost point in the window, but they should be coded to draw themselves from the topmost leftmost point of the BoardSquare itself. That is, components should only draw within their own boundaries, and they should use coordinates that assume 0,0 designates the top,left of the component, not of the window.
If you want to use BoardSquares (JComponents) and add them to the frame, you probably should use a different layout manager, like GridLayout. FlowLayout won't give you the kind of precise positioning you want.
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
public class CheckersServer2
{
public static String type_BLANK = "BLANK";
public static String type_RED = "RED";
public static String type_BLACK = "BLACK";
public static int width = 100;
public static int height = 100;
public static class Board
{
private JFrame frame = new JFrame();
private JPanel backBoard = new JPanel();
Board()
{
int numRows = 8;
int numCols = 8;
frame.setSize(905,905);
backBoard.setSize(900,900);
frame.setTitle("Checkers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
backBoard.setVisible(true);
String type;
for(int r=0; r<numRows; r++){
for(int c=0; c<numCols; c++){
//
type = type_BLANK;
if(c%2==0){
if(r==0 || r==2) {
type = type_RED;
}else if(r==6){
type = type_BLACK;
}
}else{
if(r==1){
type = type_RED;
} else if(r==5 || r==7) {
type = type_BLACK;
}
}
backBoard.add(new BoardSquare(r,c,type));
}
}
backBoard.repaint();
frame.add(backBoard);
frame.repaint();
}
private class BoardSquare extends JComponent
{
/**
*
*/
private static final long serialVersionUID = 1L;
private int x; //x position of the rectangle measured from top left corner
private int y; //y position of the rectangle measured from top left corner
private boolean isBlack = false;
private boolean isRed = false;
public BoardSquare(int p, int q, String type)
{
//this.setBorder(new LineBorder(Color.CYAN, 2));
this.setPreferredSize(new Dimension(width, height));
x = p;
y = q;
if (type.equals(type_BLACK))
{
isBlack = true;
isRed = false;
}
else if (type.equals(type_RED))
{
isRed = true;
isBlack = false;
}
else if (type.equals(type_BLANK))
{
isBlack = false;
isRed = false;
}
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle box = new Rectangle(x,y,width,height);
g2.draw(box);
g2.setPaint(Color.BLUE);
g2.fill(box);
int ovalWidth = width - 15;
int ovalHeight = ovalWidth;
if(isBlack)
{
g2.setColor(Color.black);
g2.fillOval(x, y, ovalWidth, ovalHeight);
g2.drawOval(x, y, ovalWidth, ovalHeight);
}
else if(isRed)
{
g2.setColor(Color.red);
g2.fillOval(x, y, ovalWidth, ovalHeight);
g2.drawOval(x, y, ovalWidth, ovalHeight);
}
}
}
}
public static void main(String[] args)
{
Board game = new Board();
}
}
I've just started Java and we have been asked to produce pong (or a twist on it). I am currently working on the collision between the ball and the players bat. I've got this code.
Rectangle2D.Double player;
Ellipse2D.Double ball;
public void drawActualPicture( Graphics2D g )
{
// Players Bat
g.setPaint( Color.green ); // Paint Colour
player = new Rectangle2D.Double( playerX, playerY, PW, PH );
g.fill(player);
// The ball at the current x, y position (width, height)
g.setPaint( Color.red );
ball = new Ellipse2D.Double( x-HALF_BALL_SIZE, y-HALF_BALL_SIZE, BALL_SIZE, BALL_SIZE );
g.fill( ball );
}
Some irrelevant code has been removed.
Then to detect my collision I've used
if ( ball.getBounds2D() == player.getBounds2D() )
{
System.out.println("true");
//x_inc = -1*ballS;
}
When the code is used the game simple freezes. When commented out the game runs fine.
Any ideas? Am I using the correct method in the correct way? Would it be better to use intersects?
Thanks
EDIT: It appears that anything involving .getBounds2D(); causes the game to crash. Any ideas?
EDIT2: Adding all of code-completly not needed parts
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* Note If you change S (Speed) collision detection will be more complex
* as the ball edge may be within the bat.
* Ignores concurrency issues (x,y access)
*/
class Main
{
public static void main( String args[] ) //
{ //
System.out.println("Application");
Application app = new Application();
app.setVisible(true);
app.run();
} //
}
class Application extends JFrame // So graphical
{
private static final int H = 600; // Height of window
private static final int W = 800; // Width of window
public Application()
{
setSize( W, H ); // Size of application
addKeyListener( new Transaction() ); // Called when key press
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void update( Graphics g ) // Called by repaint
{ //
drawPicture( (Graphics2D) g ); // Draw Picture
}
public void paint( Graphics g ) // When 'Window' is first
{ // shown or damaged
drawPicture( (Graphics2D) g ); // Draw Picture
}
private Dimension theAD; // Alternate Dimension
private BufferedImage theAI; // Alternate Image
private Graphics2D theAG; // Alternate Graphics
public void drawPicture( Graphics2D g ) // Double buffer
{ // allow re-size
Dimension d = getSize(); // Size of curr. image
if ( ( theAG == null ) ||
( d.width != theAD.width ) ||
( d.height != theAD.height ) )
{ // New size
theAD = d;
theAI = (BufferedImage) createImage( d.width, d.height );
theAG = theAI.createGraphics();
AffineTransform at = new AffineTransform();
at.setToIdentity();
at.scale( ((double)d.width)/W, ((double)d.height)/H );
theAG.transform(at);
}
drawActualPicture( theAG ); // Draw Actual Picture
g.drawImage( theAI, 0, 0, this ); // Display on screen
}
// The ball position and how to increment to next position
private int x = W/2, x_inc = 1;
private int y = H/2, y_inc = 1;
// The bat position and how to increment to next position
private int playerX = 60;
private int playerY = PH/2, playerY_inc = 1;
double count = 0.00;
// Called on key press
class Transaction implements KeyListener // When character typed
{
public void keyPressed(KeyEvent e) // Obey this method
{
// Key typed includes specials
switch ( e.getKeyCode() ) // Character is
{
/*
case KeyEvent.VK_LEFT: // Left Arrow
x_inc = -1;
break;
case KeyEvent.VK_RIGHT: // Right arrow
x_inc = 1;
break;
*/
case KeyEvent.VK_UP: // Up arrow
playerY_inc = -1;
break;
case KeyEvent.VK_DOWN: // Down arrow
playerY_inc = 1;
break;
}
// x,y could send to a server instead of calling
repaint(); // Call update method
}
public void keyReleased(KeyEvent e)
{
switch ( e.getKeyCode() ) // Character is
{
/*
case KeyEvent.VK_UP: // Up arrow
playerY_inc = playerY_inc;
break;
case KeyEvent.VK_DOWN: // Down arrow
playerY_inc = playerY_inc;
break;
*/
}
}
public void keyTyped(KeyEvent e)
{
// Normal key typed
char c = e.getKeyChar(); // Typed
repaint(); // Redraw screen
}
}
private static final int B = 6; // Border offset
private static final int M = 26; // Menu offset
private static final int BALL_SIZE = 10; // Ball diameter
private static final int HALF_BALL_SIZE = BALL_SIZE/2;
//Players Bat
private static final int PW = 20;
private static final int PH = 100;
private static final int HALF_PLAYER = PH/2;
// Code called to draw the current state of the game
Rectangle2D.Double player;
Ellipse2D.Double ball;
public void drawActualPicture( Graphics2D g )
{
// White background
g.setPaint( Color.white );
g.fill( new Rectangle2D.Double( 0, 0, W, H ) );
Font font = new Font("Monospaced",Font.PLAIN,24);
g.setFont( font );
// Blue playing border
g.setPaint( Color.blue ); // Paint Colour
g.draw( new Rectangle2D.Double( B, M, W-B*2, H-M-B ) );
// Players Bat
g.setPaint( Color.green ); // Paint Colour
player = new Rectangle2D.Double( playerX, playerY, PW, PH );
g.fill(player);
// Display state of game
g.setPaint( Color.blue );
FontMetrics fm = getFontMetrics( font );
String fmt = "Score/ Time lasted = %3f";
String text = String.format( fmt, count );
g.drawString( text, W/2-fm.stringWidth(text)/2, M*2 );
// The ball at the current x, y position (width, height)
g.setPaint( Color.red );
ball = new Ellipse2D.Double( x-HALF_BALL_SIZE, y-HALF_BALL_SIZE, BALL_SIZE, BALL_SIZE );
g.fill( ball );
}
// Main program loop
public void run()
{
int ballS = 1; // Speed 1 - 5
int playerS = 1;
try
{
while ( true )
{
count = count + 0.015;
//Ball hitting walls
//Right wall
if ( x >= W-B-HALF_BALL_SIZE )
{
x_inc = -1*ballS;
}
//Left wall
if ( x <= 0+B+HALF_BALL_SIZE )
{
count = count;
break;
}
//Bottom Wall
if ( y >= H-B-HALF_BALL_SIZE )
{
y_inc = -1*ballS;
}
//Top Wall
if ( y <= 0+M+HALF_BALL_SIZE )
{
y_inc = 1*ballS;
}
//Player Hiting Wall
//Bottom Wall
if ( playerY >= H-B-100 )
{
playerY_inc = -1*playerS;
}
//Top Wall
if ( playerY <= 0+M )
{
playerY_inc = 1*playerS;
}
//Player
Rectangle2D ballB = ball.getBounds2D();
if ( ball.getBounds2D().intersects(player.getBounds2D() ))
{
System.out.println("true");
//x_inc = -1*ballS;
}
//Wall
x += x_inc;
y += y_inc;
playerY += playerY_inc;
repaint(); // Now display
Thread.sleep( 10 ); // 100 Hz
}
} catch ( Exception e ) {};
}
}
Edit: Solved it, I used math and x-y coords to work out if it was inside the other shape. Thanks the help.
ball.getBounds2D() == player.getBounds2D()
Is a reference check as they are objects; not primitives. You are checking if the Rectangle2D returned by both the game objects are one in the same (which they aren't).
To check if a Rectangle2D object intersects another Rectangle2D object you should do:
ball.getBounds2D().intersects(player.getBounds2D())