I am currently working on a Java class that produces a simple JFrame/JButton layout of Tic-Tac-Toe. Implementing ActionListener, I intended on having the selected JButton set its title to "X" or "O" (based on a boolean statement of whether or not it is X's turn to pick a JButton) and become disabled (so it cannot be played on top of in following turns). The current application I have created does this, but it will sometimes not change the JButton text or disable the button until I click another button. There does not seem to be any kind of cohesive order at which this happens when I click one of the JButtons. I have spent hours trying to fix this issue with no avail. Is there an issue with how I coded my actionPerformed method or how I added it to my JButtons?
Here is the code to my class:
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;
public class TTT extends JFrame implements ActionListener{
// private fields
private JButton[] buttonArray;
private JLabel prompt;
private boolean turnX;
private String letter;
public TTT() {
// Instantiates JFrame window and adds lines to board
super.setSize(235, 280);
super.setTitle("Tic-Tac-Toe");
// Instantiates JButton array
buttonArray = new JButton[9];
// Loop that creates the JButton squares
for(int y = 30; y <= 140; y += 55) {
for(int x = 30; x <= 140; x += 55) {
for(int index = 0; index < buttonArray.length; index++) {
buttonArray[index] = new JButton();
buttonArray[index].setSize(50, 50);
buttonArray[index].setLocation(x, y);
buttonArray[index].addActionListener(this);
super.add(buttonArray[index]);
}
}
}
prompt = new javax.swing.JLabel("X's TURN");
prompt.setVerticalAlignment(JLabel.BOTTOM);
super.add(prompt);
turnX = true;
super.setVisible(true);
}
public void actionPerformed(java.awt.event.ActionEvent a) {
// Calculate whose turn it is
if(turnX){
letter = "X";
prompt.setText("O's TURN");
turnX = false;
} else if(!turnX){
letter = "O";
prompt.setText("X's TURN");
turnX = true;
}
JButton pressedButton = (JButton)a.getSource();
pressedButton.setText(letter);
pressedButton.setEnabled(false);
super.repaint();
}
public static void main(String[] args) {
new TTT();
}
}
With this code:
for(int y = 30; y <= 140; y += 55) {
for(int x = 30; x <= 140; x += 55) {
for(int index = 0; index < buttonArray.length; index++) {
You are adding 82(!) JButtons (one on top of the other in groups of 9). So, what was actually happening was that one was changed (disabled etc), but on calling repaint, the order of painting them might change, so the one whose ActionListener was triggered was painted underneath one of the 8 that were still enabled and blank.
You can correct it like this:
...
int index = 0; // <-- Add this line
for(int y = 30; y <= 140; y += 55) {
for(int x = 30; x <= 140; x += 55) {
// <-- remove the third for-loop
buttonArray[index] = new JButton();
buttonArray[index].setSize(50, 50);
buttonArray[index].setLocation(x, y);
buttonArray[index].addActionListener(this);
super.add(buttonArray[index]);
index++; // <-- increment 'index'
}
}
...
You could also remove the super.repaint() line, since it is redundant.
Not directly related to your problem, but Swing related stuff should (for various reasons) be called from the Event Dispatching Thread (EDT). One way to achieve this, is by using SwingUtilities.invokeLater(), so it might be a good idea to replace new TTT(); with this:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TTT();
}
});
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 am creating a TicTacToe game with 2 boards, only one is playable to the user. If a user clicks on cell[2][3] on grid 1 a token will be drawn on grid 1 and on cells[2][3] on grid 2. I was thinking of using a HashMap to assign indexes to each cell. Like cell[2][3] and cells[2][3] would each be assigned to index 9. How would I implement this is my code? Would I even use a Hashmap for what I am trying to do? I am unfamiliar with this concept so I might just be overthinking this.
Note: Cell[][] is the cells for grid 1 and Cells[][] are for grid 2. Cells[][] have randomized indexes in it so it can be randomly assigned to the board.
Edit: If I want to link cell(2)(3) and cells(2)(3) I would change integer to Cell when I initialize hashmap. Then I would do HMap. put(cell[2][3], cells[2][3]) right?
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.border.LineBorder;
import java.util.Random;
import java.util.HashMap;
public class Bull extends JFrame{
private char currentPlayer = ' ';
// Creates array of cells called Cell[][] cell
private Cell[][] cell = new Cell[3][3];
// Creates array of cells called Sale[][] cells
private Cells[][] cells = new Cells[3][3];
// Creates a boolean array
private boolean t[][] = new boolean[3][3];
// Creates index array
private int z[] = new int[8];
//Initializes Random
Random rand = new Random();
// Initializes variables which will be used to create random ints
int f;
int g;
// Initializes JlblStatus
private JLabel jlblStatus = new JLabel(" ");
private JLabel jlblIndex = new JLabel(" ");
// Method that builds the JFrame and JPanels
public Bull(){
// Do I change Integer to array?
HashMap<Integer, Integer> HMap = new HashMap<Integer, Integer>();
// Title of the JFrame
JFrame frame = new JFrame("Shadow Tic Tac Toe Game");
// Makes the JFrame full screen
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
// If x button is clicked than the JFrame closes
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Initializes JPanel1
JPanel panel1 = new JPanel();
// Initializes JPanel2
JPanel panel2 = new JPanel();
// Adds panel1 which will hold the first TicTacToe game.
panel1.setLayout(new GridLayout(3,3,0,0));
for(int d = 0; d < 3; d++){
for(int c = 0; c < 3; c++){
panel1.add(cell[d][c] = new Cell());
// Sets size of the cells in JPanel1
cell[d][c].setPreferredSize(new Dimension(250,250));
}
}
panel2.setLayout(new GridLayout(3,3,0,0));
int n = 0;
while(n < 9){
f=rand.nextInt(3);
g=rand.nextInt(3);
while(t[f][g] == false){
t[f][g] = true;
panel2.add(cells[f][g] = new Cells());
cells[f][g].setPreferredSize(new Dimension(250,250));
System.out.println(f);
System.out.println("\t" + g);
n++;
}
}
// Adds Panel1 to the JFrame
frame.add(panel1, BorderLayout.WEST);
// Adds Panel2 to the JFrame
frame.add(panel2, BorderLayout.EAST);
// Updates the status of the game here (win/lose/draw/whose turn it is
frame.add(jlblStatus, BorderLayout.SOUTH);
// Sets size of the message area at the bottom of the frame
jlblStatus.setPreferredSize(new Dimension(100,100));
// Shows the Instructions of the game
Instructions();
// Calls method Chose() which allows the player to chose which token they will play as
Chose();
frame.pack();
// Sets it so the JFrame is visible to the user
frame.setVisible(true);
}
// Method that creates the Instructions for the game. Will be shown to the user prior to the user picking his token
public void Instructions(){
JOptionPane.showMessageDialog(null,"INSTRUCTIONS" + "\nThis game is called a 'Shadow Tic Tac Toe Game'. In this game there will be two Tic Tac Toe game boards, though only one is playable. \nBut you can win on either board. Lets say you place your token on the center tile at cell(2,3). \nAn X will be drawn on that spot on board 1 and on a randomized spot on the second game board at cell(2,3). \nYou will be able to see the cell indexes before you click on a cell so you can form a strategy");
}
// Method that lets the user chose his/her token
public void Chose(){
int f = 2;
// While f == 2 the loop will run
while(f == 2){
String input = JOptionPane.showInputDialog("CHOSE" + "\nPlease select your token. \nPress 1 for X and 2 for O.");
// Reads in the user input. Input put into a variable called pawn
int pawn = Integer.parseInt(input);
// If user input 1 his/her token will be X. F will equal 3 so the loop does not run again
if(input.equals("1")){
currentPlayer = 'X';
f = 3;
// If user input 2 his/her token will be O. F will equal 3 so the loop does not run again
}else if(input.equals("2")){
currentPlayer = 'O';
f = 3;
// If user does not enter in either a 1 or 2 an error message will appear. f wil equal 2 so the loop runs again and asks the user to chose his/her token again
}else{
JOptionPane.showMessageDialog(null,"ERROR INVALID RESPONSE");
f = 2;
}
}
}
public class Cells extends JPanel{
private char tok = ' ';
public Cells(){
// Sets the border for the cells to the color black
setBorder(new LineBorder(Color.black,1));
}
public void setTok(char d){
tok = d;
repaint();
}
public char getTok(){
return tok;
}
protected void Paint(Graphics g){
super.paint(g);
if(tok == 'X'){
g.drawLine(10,10,getWidth() - 10, getHeight()-10);
g.drawLine(getWidth()-10,10,10,getHeight()-10);
}else if (tok == 'O'){
g.drawOval(10,10,getWidth()-20, getHeight()-20);
}
}
}
public class Cell extends JPanel{
private char token = ' ';
public void setToken(char c){
token = c;
repaint();
}
public char getToken(){
return token;
}
public Cell(){
// Sets the border for the cells to the color black
setBorder(new LineBorder(Color.black, 1));
addMouseListener(new MyMouseListener());
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (token == 'X') {
g.drawLine(10,10, getWidth() - 10, getHeight() - 10);
g.drawLine(getWidth() - 10,10,10, getHeight() - 10);
}
else if (token == 'O') {
g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
}
}
private class MyMouseListener extends MouseAdapter{
public void mouseClicked(MouseEvent e){
// If cell is empty and game is not over
if (token == ' ' && currentPlayer != ' ') {
setToken(currentPlayer); // Set token in the cell
for(int d = 0; d < 3; d++){
for(int c = 0; c < 3; c++){
if(cell[d][c].getToken() == 'X'){
cells[d][c].setTok('X');
}else if(cell[d][c].getToken() == 'O'){
cells[d][c].setTok('O');
}else if(cell[d][c].getToken() == ' '){
cells[d][c].setTok(' ');
}
}
}
//setTok(currentPlayer);
if(Won(currentPlayer)){
jlblStatus.setText("The game is over! " + currentPlayer + " won the game! Congragulations " + currentPlayer + " !");
currentPlayer = ' ';
}else if(Full()){
jlblStatus.setText("The game is over, it ends in a draw!");
currentPlayer = ' ';
}else{
if(currentPlayer == 'X'){
currentPlayer = 'O';
}else{
currentPlayer = 'X';
}
jlblStatus.setText("It is " + currentPlayer + " 's turn");
}
}
}
}
}
public boolean Full(){
for(int d = 0; d < 3; d++)
for(int c = 0; c < 3; c++)
if(cell[d][c].getToken() == ' ')
return false;
return true;
}
public boolean Won(char token){
for(int d = 0; d < 3; d++){
if(cell[d][0].getToken() == token && cell[d][1].getToken() == token && cell[d][2].getToken() == token){
return true;
}
}
for(int c = 0; c < 3; c++){
if(cell[0][c].getToken() == token && cell[1][c].getToken() == token && cell[2][c].getToken() == token){
return true;
}
}
if(cell[0][0].getToken() == token && cell[1][1].getToken() == token && cell[2][2].getToken() == token){
return true;
}
if(cell[0][2].getToken() == token && cell[1][1].getToken() == token && cell[2][0].getToken() == token){
return true;
}
return false;
}
public static void main(String [] args){
new Bull();
}
}
So essentially you want to map a cell on one grid (that the player can play on) to some cell on another grid (the shadow grid)?
You could do this just using another 2D array that stores what indices a cell maps to in the other grid, but you would need to return a point object containing x and y coordinates. But that method is sorta annoying to keep track of and has its limitations.
If you want to do it with a HashMap<Point, Point> of one Point in one grid to a Point in another grid, then you would have to override hashCode() and equals() of Point and do something like this:
HashMap<Point, Point> mapPointToPoint = new HashMap<>();
// (0,0) maps to shadow grid (1,2)
mapPointToPoint.put(new Point(0,0), new Point(1,2));
mapPointToPoint.put(new Point(0,1), new Point(2,1));
// ... more mappings for all the cells
// to get
Point pointInPlayableGrid = new Point(0,0);
Point pointInShadowGrid = mapPointToPoint.get(pointInPlayableGrid);
// pointInShadowGrid == (1,2) since that's what it was mapped to
However, if you wanted to have multiple shadow grids then you'd need to have a map from points in the playable grid to the points in the shadow grids for each shadow grid.
So instead, since you already have the Cell class, why not just have each Cell store a List<Cell> of all the cells that it maps to. This is also very flexible because you could even have a single playable Cell map to multiple cells in a single shadow grid, and on hover of the playable Cell you could just go through the list of shadow Cells it maps to and highlight them too.
public class Cell extends JPanel{
private Cell shadowCell;
public void setCellThisMapsTo(Cell otherCell){ this.shadowCell = otherCell; }
public Cell getCellThisMapsTo(){ return shadowCell; }
// ... all the other stuff
}
// ... wherever you initialize the playable and shadow grid
// get a list of the shadow Cells, randomized order
Cell[][] shadowGrid; // however you init this
Cell[][] playableGrid; // however you init this
LinkedList<Cell> shadowCells = new LinkedList<>();
for(int x = 0; x < 3; x++){
for(int y = 0; y < 3; y++){
shadowCells.add(shadowGrid[x][y]);
}
}
Collections.shuffle(shadowCells);
for(int x = 0; x < 3; x++){
for(int y = 0; y < 3; y++){
Cell playableCell = playableGrid[x][y];
Cell shadowCell = shadowCells.removeFirst();
playableCell.setCellThisMapsTo(shadowCell );
}
}
// Now all the playable cells map to a random shadow cell
Cell playableCell = playableGrid[0][0];
Cell shadowCell = playableCell.getCellThisMapsTo();
The shadow Cells will not map to any other cells, so shadowCell.getCellThisMapsTo() would return null. But this method would makes it easy to map playable cells to shadow cells and keep track of them, without even using a HashMap nor having to keep track of Points mapping to Points.
Here is my definition for Point. If you want to put something in a hash map based on its values (rather than its object reference), then it is important to override hashCode() and equals():
class Point {
public final int x;
public final int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
// !!! OVERRIDE hashCode() and equals() so you can use this properly in a HashMap !!!
#Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + this.x;
hash = 71 * hash + this.y;
return hash;
}
#Override
public int equals(Object o) {
if (obj == null)
return false;
if (this == obj)
return true;
if (getClass() != o.getClass())
return false;
Point p = (Point) o;
return this.x == p.x && this.y == p.y;
}
}
I'm not really keen on Java GUI, but am learning as I go. I am in the process of making a very simple and basic Sudoku puzzle. Right now I am just on the basic layout of it.
I wanted to see if there was a simple way of adding a text field to each little rectangle that I have drawn out (81 total rectangles - 9x9 puzzle). So that a user can type something in there.
I am delving into it, but wanted to get the code up here to see if anyone had any tips, cause truth be told, I am mega lost with this.
Here is what I have so far...
import java.awt.*;
import javax.swing.*;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
int coordinateX = 0;
int coordinateY = 0;
// maximum 9 rows
int rows = 9;
int columns = 1;
// make a 9x9 puzzle
while (columns <= rows) {
//for loop to increment the boxes
for (int j = 1; j <= rows; j++) {
// add and assign coordinte x... equivalent to x = x + 30
coordinateX += 30;
// where x and y determine start of the box and 30 determines the size
g.drawRect(coordinateX, coordinateY, 30, 30);
} //end of for loop
//reset the value of x to start a new row
coordinateX = 0;
coordinateY += 30;
columns++;
} //end of while loop
} //end of void paint
} //end of class
public class DrawRect {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(100, 100, 500, 500);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
} // end of void main
} // end of class
Hopefully someone has some pointers that could help me out, cause boy oh boy do I need it. Was kinda thrown into the lion's den without prior knowledge or practice, but I'm trying hard.
Thanks guys!!
You could use a GridLayout(9,9) and an array of arrays of JTextField's
This is, of course, just an example of how I would do it. There are other ways to do this.
Find below a generic example.
Solution
public static void main(String[] args) {
JTextField[][] boxes = new JTextField[9][9];
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(9,9));
frame.setSize(500, 500);
for (int i = 0 ; i < 9 ; i++){
for (int j = 0 ; j < 9 ; j++){
boxes[i][j] = new JTextField("0");
frame.add(boxes[i][j]);
}
}
frame.setVisible(true);
}
Output
My program is consist of two classes(test and paintClass) in different files. In the paintClass class I draw a 5x5 square board by using paintComponent method. I want to add buttons in each small square in the big square. When I run the code I don't get any buttons. I want to have 25(5x5) buttons by using jpanel on a shape drawn by paintComponent. Is this possible? If it is, how I can do it?
EDIT : The problem was the loop. Number had a default value of 0 so the loop didn't work. I defined number at the beginning. It solved the problem. Also one of the invervals were wrong. I changed j = 0 with j = 1.
import javax.swing.*;
import java.awt.*;
public class test
{
public static void main(String[] args)
{
JFrame frame = new JFrame("buttons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250,250);
PaintClass paint = new PaintClass();
paint.repaint();
f1.getContentPane().add(paint);
frame.pack();
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
public class PaintClass extends JPanel
{
private Graphics g;
private int interval,side,number;
private JButton button;
public PaintClass()
{
number = 5;
button = new JButton();
setLayout(new GridLayout(5,5));
for(int i = 0; i <= number - 1; i++)
{
for(int j = 1; j <= number - 1; j++)
{
button = new JButton();//ADDED
button.setBounds(i * interval, 0, interval, interval);
add(button);
}
button = new JButton();//ADDED
button.setBounds(0, i * interval, interval, interval);
add(button);
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.repaint();
side = 250;
number = 5;
interval = side / number;
g.drawRect(0,0, side, side);
for(int i = 0; i <= number - 1; i++)
{
for(int j = 0; j <= number - 1; j++)
{
g.drawLine(i * interval, 0, i * interval, side);
}
g.drawLine(0, i * interval, side, i * interval);
}
}
}
Choose one or the other: either add the buttons using the GridLayout, or paint the buttons using paintComponent. If the former, you should a) define the loop constraint (right now it is 0) b) create a new JButton for every loop (your code currently reuses the instance) and c) register the appropriate ActionListener to respond to events. If the latter, you need to register the appropriate listener (like MouseListener) to respond to user generated events.
private int interval,side,number;
Number has a default value of 0.
for(int i = 0; i <= number - 1; i++)
Since number is 0, your loop will never execute.
Once you do this the buttons will be added to the panel but they will cover your custom painting. To see background lines you just need to set the background of the panel to Color.BLACK and then create your GridLayout with a gap between the components. Read the API for the method to use.
So I am working on a game where an actor is moved by the user in a grid, and if the space the user is trying to move the actor to of a certain type, then it can be moved to. The grid is made up of a class that I know works called PGrid, so the grid is made of PGrids. The problem is the keyListener does not function at all, not even print out 'hi.' Below is the code for PGame and moveGrid, where PGame handles moveGrid stuff but moveGrid draws out the grid (as it is the JPanel). I tried moving the keylistener from PGame to moveGrid, but it did not work.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
//where all the different classes are put together
public class PGame implements KeyListener{ //may want to move the listener to moveGrid
private static moveGrid panel = new moveGrid(8,8); //taking something from moveGrid
private static PActor pguy = new PActor("Bill", 2, 2);
private boolean shallmove = false;
private int newx, newy;
public static void main(String[] args){
//create a new frame
JFrame frame = new JFrame("PGame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//moveGrid panel = new moveGrid(8,8); //taking something from moveGrid
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
panel.requestFocus();
//creating a "path" of places able to move to
moveGrid.pgrids.get(0).changeType(1);
moveGrid.pgrids.get(1).changeType(1);
moveGrid.pgrids.get(2).changeType(1);
moveGrid.pgrids.get(3).changeType(1);
moveGrid.pgrids.get(10).changeType(1);
moveGrid.pgrids.get(11).changeType(1);
moveGrid.pgrids.get(19).changeType(1);
moveGrid.pgrids.get(27).changeType(1);
//moveGrid.pgrids.get(4).changeType(2);
//start our pguy out in a position
PGrid pguystart = new PGrid(2,0,0);
moveGrid.pgrids.set(0,pguystart);
panel.repaint();
}
public void keyPressed(KeyEvent e) {
//here test if the grid can be updated
//Test:
pguy.canMove(3,3);
pguy.Move(4,3,3);
if(e.getKeyCode() == KeyEvent.VK_UP){
newx = pguy.getx();
newy = pguy.gety() - 1;
shallmove = pguy.canMove(newx,newy);
System.out.println("Hi");
}else if(e.getKeyCode() == KeyEvent.VK_DOWN){
newx = pguy.getx();
newy = pguy.gety() + 1;
shallmove = pguy.canMove(newx,newy);
} else if(e.getKeyCode() == KeyEvent.VK_LEFT){
newx = pguy.getx() - 1;
newy = pguy.gety();
shallmove = pguy.canMove(newx,newy);
}else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
newx = pguy.getx() + 1;
newy = pguy.gety();
shallmove = pguy.canMove(newx,newy);
}
}
public void keyReleased(KeyEvent e) {
System.out.println("Hi");
//update the grid if it can here
//somewhere in here add this:
//moveGrid.repaint(); //tell movegrid to repaint
if(shallmove = true){
//change a certain spot to the actor
PGrid temp = new PGrid(2,newx,newy);
moveGrid.pgrids.set(pguy.getplace(),temp);
//need to also change to old space to be back to what it was....
//*here*
pguy.Move(pguy.newPos,newx, newy);
panel.repaint();
}
}
public void keyTyped(KeyEvent e) { }
}
moveGrid:
//a grid in which stuff can move
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class moveGrid extends JPanel {
private int height;
private int width;
private int newx, newy;
private static PActor pguy = new PActor("Bill", 2, 2);
private boolean shallmove = false;
public static ArrayList<PGrid> pgrids = new ArrayList<PGrid>(); //an array full of grid boxes with type PGrid
public moveGrid(int height, int width){
this.height = height;
this.width = width;
setPreferredSize(new Dimension(800, 800));
//make all the values in pgrids equal to "Water" and give them locations
int i = 0;
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
PGrid pnull = new PGrid(0, x, y);
pgrids.add(i, pnull);
i++;
}
}
//drawGrid();
}
/*public void drawGrid(Graphics g){
g.drawRect(x,y,20,20);
} */
public void addNotify() {
super.addNotify();
requestFocus();
}
public void paintComponent(Graphics g){
//PGrid curLoc = new PGrid(height, height, height);
//go through and draw out the grid
int q = 0;
int midx = 0; //need to make these somehow so the squares get drawn at the center
int midy = 0;
for(int qh = 0; qh < height; qh++){
for(int qw = 0; qw < width; qw++){
PGrid pcur = pgrids.get(q); //
int p = pcur.getType();
if(p == 0){
//may want to import a water looking image
g.setColor(Color.BLUE);
g.fillRect((40*qw)+midx,(40*qh)+midy,40,40);
g.setColor(Color.BLACK);
g.drawRect((40*qw)+midx,(40*qh)+midy,40,40);
}else if(p == 1){
//may want to import a better image
g.setColor(Color.GREEN);
g.fillRect((40*qw)+midx,(40*qh)+midy,40,40);
}else if(p == 2){
//draws the "character"
g.setColor(Color.ORANGE);
g.fillRect((40*qw)+midx,(40*qh)+midy,40,40);
}
q++;
}
}
//here draw the character in the proper position
//so like multiply the x and y by 40
}
}
I also may have an error in the PActor class, which is supposedly the Actor that moves.
public class PActor {
private String name;
private int curx, cury;
int newPos;
public PActor(String name, int curx, int cury){
this.name = name;
this.curx = curx;
this.cury = cury;
}
public boolean canMove(int x, int y){
boolean abletomove = false;
//test if the space that the user is trying to moveto can be moved to
//use indexOf(a temp variable with values x and y also with type 1) to test
PGrid togo = new PGrid(1,x,y);
//now scan through pgrids in moveGrid to see the desired spot can be moved to
for(int s = 0; s <= moveGrid.pgrids.size(); s++){
PGrid temp = moveGrid.pgrids.get(s);
//test if the temp space is equal
if((togo.getType() == temp.getType()) && (togo.getx() == temp.getx()) && (togo.gety() == temp.gety())){
abletomove = true;
newPos = s;
break; //stop scanning, as it is now unnecessary
}
else{ //do nothing
}
}
//now test pgrids to see if there is a spot like such that is moveable
return abletomove;
}
public int getplace(){
return newPos;
}
public int getx(){
return curx;
}
public int gety(){
return cury;
}
public void Move(int pos, int x, int y){
PGrid temp = new PGrid(2,x,y);
moveGrid.pgrids.set(pos,temp);
}
public String toString(){
return name + " ";
}
}
Suggestions:
Again, for any Java Swing listener to work, the listener must be added to a component. For instance for a KeyListener to work, you first need to add it to the component that you wish to have listened to by calling addKeyListener(myKeyListener) on that component.
For a KeyListener to work, the component being listened to must have the keyboard focus. This means that if your'e listening to a JPanel, you first have to make it focusable by calling setFocusable(true) on the JPanel and then you need to request focus, such as by calling requestFocusInWindow() on it.
If something later steals the focus, such as a JButton that has been pushed or a text component, then the KeyListener will no longer work.
To get around this, we usually recommend that you use Key Bindings in place of KeyListeners, but note that the set up of these is completely different from that of KeyListeners, and you would need to throw all assumptions to the side and study the tutorial on use of these first.
If still stuck, then you will want to create and post a minimal example program, a small program that has a lot less code than the program you've posted, yet that compiles for us, runs, and that shows us directly your problem.
Links:
KeyListener Tutorial
Key Bindings tutorial