How to access a JButton from another class - java

I have two classes 'UserInterface' and a 'GameEngine' I have declared a JButton component in the UserInterface and I am trying to use one of the variables i.e use the variable 'button1' from 'UserInterface' in the 'horizontalWin' method from the class 'GameEngine'.
I got this error instead "cannot find symbol - variable button1"
Userinterface:
public class UserInterface implements ActionListener
{
private GameEngine game;
private JFrame frame;
JButton button1 = new JButton("");
JButton button2 = new JButton("");
JButton button3 = new JButton("");
JButton button4 = new JButton("");
JButton button5 = new JButton("");
JButton button6 = new JButton("");
JButton button7 = new JButton("");
JButton button8 = new JButton("");
JButton button9 = new JButton("");
/**
* Create a user interface.
* #param engine The game's engine.
*/
public UserInterface(GameEngine engine)
{
game = engine;
makeFrame();
}
//some methods
}
GameEngine:
public class GameEngine {
private String buttonName;
boolean winner = false;
byte count;
public GameEngine()
{
count = 0;
}
public void horizontalWin()
{
if(button1.getText()==button2.getText() && button2.getText()==button3.getText() && button1.getText()!="" )
{
winner=true;
playAgain(buttonName);
}
// Horizontal win row 2
else if(button4.getText()==button5.getText() && button5.getText()==button6.getText() && button4.getText()!="" )
{
winner=true;
playAgain(buttonName);
}
// horizontal win row 3
else if(button7.getText()==button8.getText() && button8.getText()==button9.getText() && button7.getText()!="")
{
winner=true;
playAgain(buttonName);
}
}

I think that you don't really want to do this, that you don't want your game engine trying to obtain variables from the view. Rather why not have your view notify the engine or "model" (usually through something called a "control", when a button has been pressed. The engine then can keep track of what has been pressed and change its state accordingly. The View can then change in response to changes in the engine's state.
For example:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
public class TicTacToe {
private static void createAndShowGui() {
View mainPanel = new View();
JFrame frame = new JFrame("TicTacToe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class View extends JPanel {
private static final int GAP = 2;
private static final Font BTN_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 42);
private JButton[][] gameGrid = new JButton[Engine.ROWS][Engine.ROWS];
private Engine engine = new Engine();
public View() {
engine.addPropertyChangeListener(Engine.GAME_OVER, new GameOverListener());
JPanel gameGridPanel = new JPanel(new GridLayout(Engine.ROWS, Engine.ROWS, GAP, GAP));
for (int i = 0; i < gameGrid.length; i++) {
for (int j = 0; j < gameGrid[i].length; j++) {
gameGrid[i][j] = createGameGridButton(i, j);
gameGridPanel.add(gameGrid[i][j]);
}
}
JButton resetBtn = new JButton(new ResetAction("Reset", KeyEvent.VK_R));
JPanel northPanel = new JPanel();
northPanel.add(resetBtn);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(gameGridPanel, BorderLayout.CENTER);
add(northPanel, BorderLayout.NORTH);
}
private JButton createGameGridButton(int i, int j) {
JButton button = new JButton();
button.setName(String.format("%d,%d", i, j));
button.setText(XO.BLANK.getText());
button.setFont(BTN_FONT);
button.addActionListener(new GridButtonListener(i, j));
return button;
}
private class GridButtonListener implements ActionListener {
private int i;
private int j;
public GridButtonListener(int i, int j) {
this.i = i;
this.j = j;
}
#Override
public void actionPerformed(ActionEvent e) {
if (engine.isGameOver()) {
return;
}
AbstractButton source = (AbstractButton) e.getSource();
String text = source.getText();
if (text.trim().isEmpty()) {
source.setText(engine.getTurn().getText());
engine.setXO(i, j);
}
}
}
private class ResetAction extends AbstractAction {
public ResetAction(String text, int mnemonic) {
super(text);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
engine.reset();
for (JButton[] row : gameGrid) {
for (JButton button : row) {
button.setText(XO.BLANK.getText());
}
}
};
}
private class GameOverListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
JOptionPane.showMessageDialog(View.this, engine.getTurn()
.getText() + " is a winner!", "We Have a Winner!",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
class Engine {
public static final int ROWS = 3;
public static final String GAME_OVER = "game over";
private XO[][] grid = new XO[ROWS][ROWS];
private XO turn = XO.X;
private boolean gameOver = false;
private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(
this);
public Engine() {
reset();
}
public XO getTurn() {
return turn;
}
public boolean isGameOver() {
return gameOver;
}
public void setXO(int row, int col) {
grid[row][col] = turn;
checkForWin(row, col);
turn = (turn == XO.X) ? XO.O : XO.X;
}
public void reset() {
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
grid[r][c] = XO.BLANK;
}
}
turn = XO.X;
gameOver = false;
}
public void checkForWin(int i, int j) {
boolean win = true;
for (int col = 0; col < grid.length; col++) {
if (grid[col][j] != turn) {
win = false;
}
}
if (!win) {
win = true;
for (int row = 0; row < grid[i].length; row++) {
if (grid[i][row] != turn) {
win = false;
}
}
}
if (!win && i == j) {
win = true;
for (int k = 0; k < grid.length; k++) {
if (grid[k][k] != turn) {
win = false;
}
}
}
if (!win && i + j == 2) {
win = true;
for (int k = 0; k < grid.length; k++) {
if (grid[k][2 - k] != turn) {
win = false;
}
}
}
if (win) {
setGameOver(true);
}
}
private void setGameOver(boolean gameOver) {
boolean oldValue = this.gameOver;
boolean newValue = gameOver;
this.gameOver = gameOver;
pcSupport.firePropertyChange(GAME_OVER, oldValue, newValue);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
public void addPropertyChangeListener(String name,
PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(name, listener);
}
public void removePropertyChangeListener(String name,
PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(name, listener);
}
}
enum XO {
X("X"), O("O"), BLANK(" ");
private String text;
private XO(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
My view's ActionListener (here an AbstractAction) notifies the Engine that a certain button has been pushed. The Engine keeps track of which button has been pushed, and when a winner has been determined, sets a gameOver field thereby notifying all listeners that the game is over.

Related

Reset Game Of Life Gui

I am making Conway's Game of Life using Java Swing. I am using a 2D arrays of buttons to paint the cells. The problem I have right now is that I implemented a button which will clear the pattern or patterns drew manually o randomly and also while the timer is running. I want to clear or restart the 2D array of buttons but when I try to draw it doesn't work.
Here I have the Action Listeners for each button
//Starts the timer
Starter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
cells = new JButton[size][size];
}
});
//Stops the timer
Stop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
//Clears de buttons which are painted
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
if(Univers[i][j]){
cells[i][j].setBackground(Color.BLACK);
}
}
}
Arrays.fill(cells, null);
}
});
All the code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class GameOfLife extends JFrame{
int size=15;
int time=0;
boolean Univers[][];
JButton cells[][];
//int countentry=0;
//List<boolean[][]> Record;
JComboBox combobox;
public GameOfLife() {
//Record = new ArrayList<>();
setPreferredSize(new Dimension(600, 600));
pack();
setLayout(null);
/*combobox= new JComboBox();
combobox.addItem("Records");
combobox.addItem(time+"s");
*/
Random rnd=new Random();
Univers=new boolean[size][size];
cells=new JButton[size][size];
JPanel UniversPanel=new JPanel();
UniversPanel.setBounds(0,0,500,500);
UniversPanel.setLayout(new GridLayout(size,size));
////////////////////////////////////////////////////////////
//manual cell adding
MouseListener mouseListener = new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) { }
#Override
public void mouseReleased(MouseEvent e) { }
#Override
public void mousePressed(MouseEvent e) { }
#Override
public void mouseExited(MouseEvent e) { }
#Override
public void mouseEntered(MouseEvent e) {
JButton ch = (JButton) e.getSource();
//System.out.println(ch.getLocation(getLocation()));
int sizegrid = UniversPanel.getSize(getSize()).width / size;
int i = (ch.getLocation(getLocation()).x) / sizegrid;
int z = (ch.getLocation(getLocation()).y) / sizegrid;
//System.out.println("x= "+i);
//System.out.println("y= "+z);
if (!Univers[z][i] && SwingUtilities.isLeftMouseButton(e)) {
Univers[z][i] = true;
cells[z][i].setBackground(Color.GREEN);
}
if(Univers[z][i] && SwingUtilities.isRightMouseButton(e)) {
Univers[z][i]=false;
cells[z][i].setBackground(Color.BLACK);
}
}
};
///////////////////////////////////////////////////////////////////
for(int x=0;x<size;x++) {
for(int y=0;y<size;y++) {
/*if((x==0 && y==1 )|| (x==1 && y==1) || (x==2 && y==1)) {
Univers[x][y]=true;
}else {
Univers[x][y]=false;
}*/
Univers[x][y]=false;
//Univers[x][y]=rnd.nextInt(100)<20;
JButton btn=new JButton();
if(Univers[x][y]) {
btn.setBackground(Color.GREEN);
}else {
btn.setBackground(Color.BLACK);
}
UniversPanel.add(btn);
cells[x][y]=btn;
}
}
//Record.add(Univers);
//countentry+=1;
//System.out.print(Record.size());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int delay=100;//milliseconds
//int Timeup=5000/delay;
Timer timer=new Timer(delay,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean[][] tempUnivers=new boolean[size][size];
//countentry+=1;
for(int x=0;x<size;x++) {
for(int y=0;y<size;y++) {
int count=Neigbours(x,y);
if(Univers[x][y]) {
if(count<2) {
tempUnivers[x][y]=false;
}
if(count==3 ||count==2) {
tempUnivers[x][y]=true;
}
if(count>3) {
tempUnivers[x][y]=false;
}
}else{
if(count==3)
tempUnivers[x][y]=true;
}
}
}
Univers=tempUnivers;
//Record.add(Univers);
//System.out.print(Record.size());
for(int x=0;x<size;x++) {
for(int y=0;y<size;y++) {
if(Univers[x][y]) {
cells[x][y].setBackground(Color.GREEN);
}else {
cells[x][y].setBackground(Color.BLACK);
}
}
}
/* if(countentry==Timeup) {
time+=5;
combobox.addItem(time+"s");
countentry=0;
}
*/
}
});
for(int x=0;x<size;x++) {
for(int y=0;y<size;y++) {
cells[x][y].addMouseListener(mouseListener);
}
}
//Slider
/*JPanel PanelSlider =new JPanel();
PanelSlider.setLayout(new GridLayout(0,2));
PanelSlider.setBounds(0,510,300,50);
JSlider slider = new JSlider(0,5,0);
slider.setPaintTrack(true);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMajorTickSpacing(1);
slider.setMinorTickSpacing(1/10);
slider.setBounds(51, 88, 277, 52);
PanelSlider.add(combobox);
PanelSlider.add(slider);
*/
//Buttons
JPanel PanelButton =new JPanel();
PanelButton.setLayout(new GridLayout(0,3));
PanelButton.setBounds(0,510,200,50);
JButton Starter=new JButton("Start");
PanelButton.add(Starter);
JButton Stop=new JButton("Stop");
PanelButton.add(Stop);
JButton clear = new JButton("Clear");
PanelButton.add(clear);
//Starts the timer
Starter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
cells = new JButton[size][size];
}
});
//Stops the timer
Stop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
//Clears de buttons which are painted
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
if(Univers[i][j]){
cells[i][j].setBackground(Color.BLACK);
}
}
}
Arrays.fill(cells, null);
}
});
//add(PanelSlider);
add(UniversPanel);
add(PanelButton);
setLocationRelativeTo(null);
setVisible(true);
}
int Neigbours(int i, int z) {
int count=0;
for(int x=i-1;x<=i+1;x++) {
for(int y=z-1;y<=z+1;y++) {
try {
if(Univers[x][y]) {
count++;
}
}catch(Exception e){
//System.out.println(e);
}
}
}
if(Univers[i][z])
count--;
return count;
}
public static void main(String[] args) {
new GameOfLife();
}
//Slider info https://docs.oracle.com/javase/tutorial/uiswing/components/slider.html
//Manual insert void ActionPerformed(ActionEvent ae){add jbutton ch = (Jbutton) ae.getSource();}
}
Please read the comment within the code to follow the changes made in the code and the recommendations:
import java.awt.*;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
public class GameOfLife extends JFrame{
//declare constants
private final int BOARD_SIZE=15,
ANIMATION_DELAY=100;//milliseconds;
private final Cell cells[][];
public GameOfLife() {
//setPreferredSize(new Dimension(600, 600)); let layout manager work out the size derived from children
//setLayout(null); avoid using null layouts and seting bounds manually
cells=new Cell[BOARD_SIZE][BOARD_SIZE];
JPanel universPanel=new JPanel();
//universPanel.setBounds(0,0,500,500); let the layout manager set bounds
universPanel.setLayout(new GridLayout(BOARD_SIZE,BOARD_SIZE));
//initialize all cells
for(int x=0;x<BOARD_SIZE;x++) {
for(int y=0;y<BOARD_SIZE;y++) {
Cell cell=new Cell();
universPanel.add(cell);
cells[x][y]=cell;
}
}
//move the animation code to a method for better readability
Timer timer=new Timer(ANIMATION_DELAY,e -> animate());
//Buttons
JPanel panelButton =new JPanel();
panelButton.setLayout(new GridLayout(0,3));
//panelButton.setBounds(0,510,200,50); let the layout manager set bounds
JButton starter=new JButton("Start");
panelButton.add(starter);
JButton stop=new JButton("Stop");
panelButton.add(stop);
JButton clear = new JButton("Clear");
panelButton.add(clear);
//Starts the timer
starter.addActionListener(e -> timer.start());
//Stops the timer
stop.addActionListener(e -> timer.stop());
//Resets all cells
clear.addActionListener(e -> {
for(int i = 0; i < BOARD_SIZE; i++){
for(int j = 0; j < BOARD_SIZE; j++){
cells[i][j].setUniverse(false);
}
}
//Arrays.fill(cells, null); no need to set to null.
});
//add(PanelSlider);
//add to appropriate BorderLayout positions
add(universPanel, BorderLayout.CENTER);
add(panelButton, BorderLayout.SOUTH);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack(); //pack after you added all components
setVisible(true);
}
private void animate(){
for(int x1=0;x1<BOARD_SIZE;x1++) {
for(int y1=0;y1<BOARD_SIZE;y1++) {
int count=numberOfNeigboursAround(x1,y1);
if(cells[x1][y1].isUniverse()) {
if(count<2) {
cells[x1][y1].setUniverse(false);
}else if//process next if only if previous one was false
(count==3 ||count==2) {
cells[x1][y1].setUniverse(true);
}else if(count>3) {
cells[x1][y1].setUniverse(false);
}
}else if(count==3) {
cells[x1][y1].setUniverse(true);
}
}
}
}
private int numberOfNeigboursAround(int x, int y) {
int count=0;
for(int xIndex=x-1;xIndex<=x+1;xIndex++) {
for(int yIndex=y-1;yIndex<=y+1;yIndex++) {
//make sure index is valid
if(xIndex >= BOARD_SIZE || xIndex < 0 || yIndex >= BOARD_SIZE || yIndex < 0) {
continue;
}
//don't process center cell
if(xIndex == x&&yIndex ==y) {
continue;
}
if(cells[xIndex][yIndex].isUniverse()) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
new GameOfLife();
}
}
//Introduce a Cell class with the needed properties. Since button functionality i snot
//use a JLabel can be used to represent a cell
class Cell extends JLabel{
private static Color BOARD = Color.BLACK, UNIVERSE = Color.GREEN, BORDER = Color.GRAY;
private static Dimension CELL_SIZE = new Dimension(30,30);
private boolean universe;
public Cell() {
super();
universe = false;
setOpaque(true);
setBorder(BorderFactory.createLineBorder(BORDER, 2));
setBackground(BOARD);
//add mouse listener. use MouseInputAdapter to implement only needed methods
addMouseListener( new MouseInputAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
mouseClicksHandler(e);
}
});
}
public boolean isUniverse() {
return universe;
}
public void setUniverse(boolean isUniverse) {
if (universe == isUniverse) return; //no change
universe = isUniverse;
setBackground(isUniverse ? UNIVERSE : BOARD);
repaint();
}
private void mouseClicksHandler(MouseEvent e){
if (SwingUtilities.isLeftMouseButton(e)) {
setUniverse(true);
}else //if first if is true no need to evaluate the second if
if( SwingUtilities.isRightMouseButton(e)) {
setUniverse(false);
}
}
//preferred size used by layout managers
#Override
public Dimension getPreferredSize() {
return CELL_SIZE;
}
}

JButton replace Image with Image different size?

First of all I programming a simple memory game. It works really fine but only one thing is broken.
When I click to a button then he changed his background to the number behind the card. After that i click another button and then if both cards are not equal they switch back to default. Now the image is moving to the left side but i dont know why. I use the same method to calculate and downscale the image as I initialize it.
Startmodul:
Method:
public void setImageWithResizeImage(ImageIcon icon, int width, int height) {
this.icon = icon;
Image img = icon.getImage();
Image newImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
this.setIcon(new ImageIcon(newImg));
}
And if i click on two buttons and it will be false then invoke this method
public void changeBGImage(boolean revealed) {
if (revealed == true) {
this.revealed = revealed;
setIcon(null);
setText(Integer.toString(id));
} else {
this.revealed = revealed;
System.out.println(this.getWidth() + " " + this.getHeight());
setImageWithResizeImage(this.icon, this.getWidth(), this.getHeight());
}
}
after that the game shows like this:
any ideas ?
Edit*
GUI Class :
enter code herepackage de.thesimplecode.marvin;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class GUI extends JFrame {
private static final long serialVersionUID = 1L;
public static int pGameMode = 3;
public static int fieldsCount;
private int pPlayerPoints = 0;
private int pKIPoints = 0;
private final int WIDTH = 800;
private final int HEIGHT = 800;
private final String rWinLabel = "Memorys";
private final String rPlayerScore = "PlayerScore: ";
private final String rKIScore = "KIScore: ";
private MemoButton[] rFields;
private JLabel playerScore, KIScore;
private JPanel rGameFields;
private final ImageIcon icon = new ImageIcon("cardBack.jpg");
public GUI() {
myFrame();
}
public void changeKIScore(int change) {
this.pKIPoints += change;
this.KIScore.setText(rKIScore + pKIPoints);
}
public void changePlayerScore(int change) {
this.pPlayerPoints += change;
this.playerScore.setText(rPlayerScore + pPlayerPoints);
}
public JPanel createFields() {
rGameFields = new JPanel();
switch (pGameMode) {
case 1:
fieldsCount = 16;
break;
case 2:
fieldsCount = 36;
break;
case 3:
fieldsCount = 64;
break;
default:
fieldsCount = 16;
break;
}
try {
rFields = new MemoButton[fieldsCount];
fieldsCount = findBestGrid(fieldsCount);
rGameFields.setLayout(new GridLayout(fieldsCount, fieldsCount));
for (int i = 0; i < fieldsCount * fieldsCount; i++) {
if (i > ((fieldsCount * fieldsCount) / 2) - 1) {
rFields[i] = new MemoButton(((fieldsCount * fieldsCount) - 1) - i);
} else {
rFields[i] = new MemoButton(i);
}
}
// Shuffle array
Collections.shuffle(Arrays.asList(rFields));
for (MemoButton button : rFields) {
rGameFields.add(button);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return rGameFields;
}
public MemoButton[] getFields() {
return this.rFields;
}
public int getKiScore() {
return pKIPoints;
}
public int getPlayerScore() {
return pPlayerPoints;
}
public boolean refreshJFrame() {
try {
remove(rGameFields);
refreshModuls();
add(createFields(), BorderLayout.CENTER);
refreshModuls();
setBGtoFields(rFields);
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
}
private JPanel createInfoTable() {
JPanel rInfoTable = new JPanel();
rInfoTable.setBackground(Color.GREEN);
rInfoTable.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
playerScore = new JLabel(rPlayerScore + " 0");
c.insets = new Insets(0, this.getWidth() / 4, 0, this.getWidth() / 4);
rInfoTable.add(playerScore, c);
KIScore = new JLabel(rKIScore + " 0");
rInfoTable.add(KIScore, c);
return rInfoTable;
}
private int findBestGrid(int count) {
for (int i = 2; i < 10; i++) {
if (i * i == count) {
return i;
}
}
return 0;
}
private JMenuBar JMenu() {
JMenuBar rMainMenu = new JMenuBar();
JMenu game = new JMenu("Game");
JMenu settings = new JMenu("Settings");
JMenuItem newGame = new JMenuItem("New Game");
JMenu tableSize = new JMenu("TableSize");
JMenu kiDifficulty = new JMenu("Ki Level");
// First MenuItems for gameoptions
JMenuItem small = new JMenuItem("4x4 - 16 cards");
JMenuItem medium = new JMenuItem("6x6 - 36 cards");
JMenuItem big = new JMenuItem("8x8 - 64 cards");
// Second
JMenuItem low = new JMenuItem("Low");
JMenuItem mediumsmart = new JMenuItem("Medium smart");
JMenuItem smart = new JMenuItem("Smart");
tableSize.add(small);
tableSize.add(medium);
tableSize.add(big);
kiDifficulty.add(low);
kiDifficulty.add(mediumsmart);
kiDifficulty.add(smart);
game.add(newGame);
game.add(tableSize);
game.add(kiDifficulty);
rMainMenu.add(game);
rMainMenu.add(settings);
return rMainMenu;
}
private void myFrame() {
setSize(WIDTH, HEIGHT);
setTitle(rWinLabel);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setJMenuBar(JMenu());
add(createInfoTable(), BorderLayout.PAGE_START);
add(createFields(), BorderLayout.CENTER);
setVisible(true);
setBGtoFields(rFields);
}
private void refreshModuls() {
validate();
repaint();
}
private void setBGtoFields(MemoButton[] buttons) {
for (MemoButton button : buttons) {
button.setImageWithResizeImage(this.icon, button.getWidth(), button.getHeight());
}
}
}
Own Button Class:
package de.thesimplecode.marvin;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class MemoButton extends JButton {
private static final long serialVersionUID = 1L;
private int id;
private boolean revealed = false;
private ImageIcon icon;
public MemoButton(int id) {
this.id = id;
}
public void changeBGImage(boolean revealed) {
if (revealed == true) {
this.revealed = revealed;
setIcon(null);
setText(Integer.toString(id));
} else {
this.revealed = revealed;
System.out.println(this.getWidth() + " " + this.getHeight());
setImageWithResizeImage(this.icon, this.getWidth(), this.getHeight());
}
}
public void getBackIcon(ImageIcon icon) {
this.icon = icon;
}
public int getID() {
return this.id;
}
public boolean getRevealed() {
return this.revealed;
}
public void revealed(boolean revealed) {
this.revealed = revealed;
}
public void setID(int id) {
this.id = id;
}
public void setImageWithResizeImage(ImageIcon icon, int width, int height) {
this.icon = icon;
Image img = icon.getImage();
Image newImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
this.setIcon(new ImageIcon(newImg));
}
public void setRevealed(boolean revealed) {
this.revealed = revealed;
}
}
Controller Class:
package de.thesimplecode.marvin;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Controller implements ActionListener {
private MemoButton[] fields;
private GUI gui;
private KI ki;
private int counter;
private MemoButton savebut, savebut2;
private boolean notMatch = false;
private boolean abwechseln = true;
private boolean player = true;
Timer t = new Timer();
public Controller(MemoButton[] fields, GUI gui) {
this.fields = fields;
this.gui = gui;
addListenerToButton(this.fields);
addListenerToMenu(this.gui);
gameLoop();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
MemoButton button = (MemoButton) e.getSource();
if (notMatch) {
savebut2.changeBGImage(false);
savebut.changeBGImage(false);
savebut2 = null;
notMatch = false;
}
if (button.getRevealed() != true) {
counter++;
button.setRevealed(true);
button.changeBGImage(true);
if (counter % 2 == 0) {
if (button.getRevealed() && savebut.getRevealed()) {
if (button.getID() == savebut.getID()) {
if (player) {
gui.changePlayerScore(gui.getPlayerScore() + 1);
} else {
gui.changeKIScore(gui.getKiScore() + 1);
}
} else {
notMatch = true;
if (player) {
player = false;
} else {
player = true;
}
}
}
}
if (abwechseln) {
savebut = button;
abwechseln = false;
} else {
savebut2 = button;
abwechseln = true;
}
} else {
System.out.println("Button würde schoin gewählt");
}
} else if (e.getSource() instanceof JMenuItem) {
JMenuItem rMenuItem = (JMenuItem) e.getSource();
switch (rMenuItem.getText()) {
case "New Game":
newGame();
break;
case "4x4 - 16 cards":
GUI.pGameMode = 1;
refreshContent();
break;
case "6x6 - 36 cards":
GUI.pGameMode = 2;
refreshContent();
break;
case "8x8 - 64 cards":
GUI.pGameMode = 3;
refreshContent();
break;
case "Low":
break;
case "Medium smart":
break;
case "Smart":
break;
}
}
}
public void gameLoop() {
t.schedule(new TimerTask() {
#Override
public void run() {
if (!player) {
ki.nextKI();
}
}
}, 0, 1000);
}
public void getKI(KI ki) {
this.ki = ki;
}
private void addListenerToButton(MemoButton[] fields) {
for (MemoButton button : fields) {
button.addActionListener(this);
}
}
private void addListenerToMenu(GUI gui) {
JMenuBar menu = gui.getJMenuBar();
for (int i = 0; i < menu.getMenuCount(); i++) {
for (int j = 0; j < menu.getMenu(i).getItemCount(); j++) {
if (menu.getMenu(i).getItem(j) instanceof JMenu) {
JMenu rJMenu = (JMenu) menu.getMenu(i).getItem(j);
for (int y = 0; y < rJMenu.getItemCount(); y++) {
JMenuItem rJMenuItem = rJMenu.getItem(y);
rJMenuItem.addActionListener(this);
}
} else if (menu.getMenu(i).getItem(j) instanceof JMenuItem) {
menu.getMenu(i).getItem(j).addActionListener(this);
}
}
}
}
private void newGame() {
refreshContent();
gui.changeKIScore(0);
gui.changePlayerScore(0);
}
private void refreshContent() {
if (gui.refreshJFrame()) {
addListenerToButton(gui.getFields());
ki.resetButton();
ki.getFields(gui.getFields());
}
}
}
KI Code :
package de.thesimplecode.marvin;
import java.awt.event.ActionEvent;
import java.util.Random;
public class KI {
private MemoButton[] button;
private Controller controll;
private Random r = new Random();
public KI(MemoButton[] button, Controller controll) {
this.button = button;
this.controll = controll;
}
public void getFields(MemoButton[] button) {
this.button = button;
}
public void nextKI() {
takeCard();
}
public void resetButton() {
this.button = null;
}
private void takeCard() {
controll.actionPerformed(new ActionEvent(button[r.nextInt((GUI.fieldsCount * GUI.fieldsCount) - 1)],
ActionEvent.ACTION_PERFORMED, null));
}
}
Main :
package de.thesimplecode.marvin;
public class Memory {
public static void main(String[] args) {
GUI gui = new GUI();
Controller cl = new Controller(gui.getFields(), gui);
KI ki = new KI(gui.getFields(), cl);
cl.getKI(ki);
}
}
SOLVED:
public void changeBGImage(ImageIcon icon, boolean revealed) {
if (revealed == true) {
this.revealed = revealed;
setIcon(null);
setText(Integer.toString(id));
} else {
this.revealed = revealed;
System.out.println(this.getWidth() + " " + this.getHeight());
setText("");
setImageWithResizeImage(icon, this.getWidth(), this.getHeight());
}
}
I have to add the method setText(""); because with setText
setText(Integer.toString(id));
i add a number oder String into the button and with setText (""); i delete it and now it works. He had a small dot on the right side therefore was the image merged on the left side.

Java swing repainting while computing: animating sorting algorithm

http://www.youtube.com/watch?v=M0cNsmjK33E
I want to develop something similar to the link above using Java Swing. I have the sorting method and did while repaint but when I triggered the sorting, instead of showing the bars slowly sorting itself, it freezes and then unfreezes when the array has been fully sorted.
How do I fix this?
Edit: sorry forgot about the codes. its a very simple gui. and another class for sorting which sorts the whole array
public class SortGUI {
JFrame frame;
int frameWidth = 1000, frameHeight = 1000;
int panelWidth, panelHeight;
DrawPanel panel;
JPanel panel2;
JScrollPane scroll;
JViewport view;
static int[] S = new int[50000];
public static void main(String[] args) throws InterruptedException {
SortGUI app = new SortGUI();
initializeArray();
app.go();
}
public static void initializeArray()
{
for (int i = 0; i < S.length; i++) {
S[i] = (int) (Math.random() * 16581375);
}
}
public void go() throws InterruptedException {
//Frame
frame = new JFrame();
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//panel
panel = new DrawPanel();
scroll = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//Layout
frame.add(scroll);
frame.addKeyListener(new keyListener());
while(true)
{
panel.repaint();
}
}
public class DrawPanel extends JPanel
{
public DrawPanel()
{
this.setPreferredSize(new Dimension(50000,930));
}
public void paintComponent(Graphics g)
{
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
for(int i = 0; i < S.length; i++)
{
int red = S[i] / 65025;
int green = (S[i] > 65025)? S[i] % 65025 : 0;
int blue = green;
blue %= 255;
green /= 255;
g.setColor(new Color(red,green,blue));
g.fillRect(i, 900 - (S[i] / 18500), 1, S[i] / 18500);
}
}
}
public class keyListener implements KeyListener{
public void keyTyped(KeyEvent ke) {
}
public void keyPressed(KeyEvent ke) {
if(ke.getKeyChar() == '1')
{
sorter.bubbleSort(S);
}
}
public void keyReleased(KeyEvent ke) {
}
}
}
Note: I started writing this before the question was deleted
Most likely your using some looping mechanism and praying that each iteration, the ui with be updated. That's a wrong assumption. The UI will not be update until the loop is finished. What you are doing is what we refer to as blocking the Event Dispatch Thread(EDT)
See How to use a Swing Timer. Make "iterative" updates in the ActionListener call back. For instance, if you want to animate a sorting algorithm, you need to determine what needs to be updated per "iteration" of the timer callback. Then each iteration repaint the ui.
So your Timer timer could look something like
Timer timer = new Timer(40, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if (sortingIsDone()) {
((Timer)e.getSource()).stop();
} else {
sortOnlyOneItem();
}
repaint();
}
});
Your sortOnlyOneItem method should only, well, perform a sort for just one item. And have some sort of flag to check if the sorting is done, then stop the timer.
Other notes:
You should be calling super.paintComponent in the paintComponent method, if you aren't going to paint the background yourself. Generally I always do though.
Here's a complete example. I'm glad you figured it out on your own. I was working on this example before I saw that you got it.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SelectionSortAnimate extends JPanel {
private static final int NUM_OF_ITEMS = 20;
private static final int DIM_W = 400;
private static final int DIM_H = 400;
private static final int HORIZON = 350;
private static final int VERT_INC = 15;
private static final int HOR_INC = DIM_W / NUM_OF_ITEMS;
private JButton startButton;
private Timer timer = null;
private JButton resetButton;
Integer[] list;
int currentIndex = NUM_OF_ITEMS - 1;
public SelectionSortAnimate() {
list = initList();
timer = new Timer(200, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isSortingDone()) {
((Timer) e.getSource()).stop();
startButton.setEnabled(false);
} else {
sortOnlyOneItem();
}
repaint();
}
});
startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
resetButton = new JButton("Reset");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
list = initList();
currentIndex = NUM_OF_ITEMS - 1;
repaint();
startButton.setEnabled(true);
}
});
add(startButton);
add(resetButton);
}
public boolean isSortingDone() {
return currentIndex == 0;
}
public Integer[] initList() {
Integer[] nums = new Integer[NUM_OF_ITEMS];
for (int i = 1; i <= nums.length; i++) {
nums[i - 1] = i;
}
Collections.shuffle(Arrays.asList(nums));
return nums;
}
public void drawItem(Graphics g, int item, int index) {
int height = item * VERT_INC;
int y = HORIZON - height;
int x = index * HOR_INC;
g.fillRect(x, y, HOR_INC, height);
}
public void sortOnlyOneItem() {
int currentMax = list[0];
int currentMaxIndex = 0;
for (int j = 1; j <= currentIndex; j++) {
if (currentMax < list[j]) {
currentMax = list[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != currentIndex) {
list[currentMaxIndex] = list[currentIndex];
list[currentIndex] = currentMax;
}
currentIndex--;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < list.length; i++) {
drawItem(g, list[i], i);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(DIM_W, DIM_H);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Sort");
frame.add(new SelectionSortAnimate());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Slider Puzzle problems

This is my slider puzzle game. So far it can only do 3x3 games. When I try and pass the variables l and w (length and width) of the board it doesn't work. It only works when i set the variables ROWS and COLS as finals. When I try and change it I get errors. I'm not sure what to do, any help would be appreciated.
Currently the user can input values that can't do anything at the moment. When the game is started, a 3x3 board is generated. The user can restart the game with a different scrambled board but the buttons that solve the board and the buttons that reset the board to the original state do not work yet.
public class SlidePuzzle {
public static void main(String[] args)
{
JFrame window = new JFrame("Slide Puzzle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String length = JOptionPane.showInputDialog("Length");
String width = JOptionPane.showInputDialog("Width");
int l = Integer.parseInt(length);
int w = Integer.parseInt(width);
window.setContentPane(new SlidePuzzleGUI());
window.pack();
window.show();
window.setResizable(false);
}
}
public class SlidePuzzleGUI extends JPanel
{
private GraphicsPanel _puzzleGraphics;
private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
This class contains the GUI for the Slider Puzzle
public SlidePuzzleGUI() {
JButton newGameButton = new JButton("New Game");
JButton resetButton = new JButton("Reset");
JButton solveButton = new JButton("I GIVE UP :(");
resetButton.addActionListener(new ResetAction());
newGameButton.addActionListener(new NewGameAction());
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(newGameButton);
controlPanel.add(resetButton);
controlPanel.add(solveButton);
_puzzleGraphics = new GraphicsPanel();
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
this.add(_puzzleGraphics, BorderLayout.CENTER);
}
This is the graphics panel
class GraphicsPanel extends JPanel implements MouseListener {
private static final int ROWS = 3;
private static final int COLS = 3;
private static final int CELL_SIZE = 80;
private Font _biggerFont;
public GraphicsPanel() {
_biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
this.setPreferredSize(
new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
this.setBackground(Color.black);
this.addMouseListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
int x = c * CELL_SIZE;
int y = r * CELL_SIZE;
String text = _puzzleModel.getFace(r, c);
if (text != null) {
g.setColor(Color.gray);
g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
g.setColor(Color.black);
g.setFont(_biggerFont);
g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
}
}
}
}
public void mousePressed(MouseEvent e) {
int col = e.getX()/CELL_SIZE;
int row = e.getY()/CELL_SIZE;
if (!_puzzleModel.moveTile(row, col)) {
Toolkit.getDefaultToolkit().beep();
}
this.repaint();
}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}
public class NewGameAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
_puzzleModel.reset();
_puzzleGraphics.repaint();
}
}
public class ResetAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
_puzzleModel.tryAgain();
_puzzleGraphics.repaint();
}
}
public class solveAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
_puzzleModel.solve();
_puzzleGraphics.repaint();
}
}
}
public class SlidePuzzleModel {
private static final int ROWS = 3;
private static final int COLS = 3;
private Tile[][] _contents;
private Tile[][] _solved;
private Tile _emptyTile;
public SlidePuzzleModel() {
_contents = new Tile[ROWS][COLS];
reset();
}
String getFace(int row, int col) {
return _contents[row][col].getFace();
}
public void reset() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
_contents[r][c] = new Tile(r, c, "" + (r*COLS+c+1));
}
}
_emptyTile = _contents[ROWS-1][COLS-1];
_emptyTile.setFace(null);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
exchangeTiles(r, c, (int)(Math.random()*ROWS)
, (int)(Math.random()*COLS));
}
}
}
public void tryAgain()
{
}
public void solve()
{
for (int i = 1; i < ROWS+1;i++)
{
for(int j = 1; j < COLS+1;j++)
{
exchangeTiles(i, j, i, j);
}
}
}
public boolean moveTile(int r, int c) {
return checkEmpty(r, c, -1, 0) || checkEmpty(r, c, 1, 0)
|| checkEmpty(r, c, 0, -1) || checkEmpty(r, c, 0, 1);
}
private boolean checkEmpty(int r, int c, int rdelta, int cdelta) {
int rNeighbor = r + rdelta;
int cNeighbor = c + cdelta;
if (isLegalRowCol(rNeighbor, cNeighbor)
&& _contents[rNeighbor][cNeighbor] == _emptyTile) {
exchangeTiles(r, c, rNeighbor, cNeighbor);
return true;
}
return false;
}
public boolean isLegalRowCol(int r, int c) {
return r>=0 && r<ROWS && c>=0 && c<COLS;
}
private void exchangeTiles(int r1, int c1, int r2, int c2) {
Tile temp = _contents[r1][c1];
_contents[r1][c1] = _contents[r2][c2];
_contents[r2][c2] = temp;
}
public boolean isGameOver() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<ROWS; c++) {
Tile trc = _contents[r][c];
return trc.isInFinalPosition(r, c);
}
}
return true;
}
}
class Tile {
private int _row;
private int _col;
private String _face;
public Tile(int row, int col, String face) {
_row = row;
_col = col;
_face = face;
}
public void setFace(String newFace) {
_face = newFace;
}
public String getFace() {
return _face;
}
public boolean isInFinalPosition(int r, int c) {
return r==_row && c==_col;
}
}
How would I make it so that the user can specify dimensions of the game board?
EDIT
public class SlidePuzzle {
public static void main(String[] args)
{
JFrame window = new JFrame("Slide Puzzle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String length = JOptionPane.showInputDialog("Length");
String width = JOptionPane.showInputDialog("Width");
int l = Integer.parseInt(length);
int w = Integer.parseInt(width);
window.setContentPane(new SlidePuzzleGUI());
window.pack();
window.show();
window.setResizable(false);
}
}
public class SlidePuzzleGUI extends JPanel
{
private GraphicsPanel _puzzleGraphics;
private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
public SlidePuzzleGUI(int l, int w) {
JButton newGameButton = new JButton("New Game");
JButton resetButton = new JButton("Reset");
JButton solveButton = new JButton("I GIVE UP :(");
resetButton.addActionListener(new ResetAction());
newGameButton.addActionListener(new NewGameAction());
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(newGameButton);
controlPanel.add(resetButton);
controlPanel.add(solveButton);
_puzzleGraphics = new GraphicsPanel(l,w);
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
this.add(_puzzleGraphics, BorderLayout.CENTER);
}
class GraphicsPanel extends JPanel implements MouseListener {
private int ROWS;
private int COLS;
private static final int CELL_SIZE = 80;
private Font _biggerFont;
public GraphicsPanel(int l, int w) {
_biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
this.setPreferredSize(
new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
this.setBackground(Color.black);
this.addMouseListener(this);
ROWS = l;
COLS = w;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
int x = c * CELL_SIZE;
int y = r * CELL_SIZE;
String text = _puzzleModel.getFace(r, c);
if (text != null) {
g.setColor(Color.gray);
g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
g.setColor(Color.black);
g.setFont(_biggerFont);
g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
}
}
}
}
public void mousePressed(MouseEvent e) {
int col = e.getX()/CELL_SIZE;
int row = e.getY()/CELL_SIZE;
if (!_puzzleModel.moveTile(row, col)) {
Toolkit.getDefaultToolkit().beep();
}
this.repaint();
}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}
public class NewGameAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
_puzzleModel.reset();
_puzzleGraphics.repaint();
}
}
public class ResetAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
_puzzleModel.tryAgain();
_puzzleGraphics.repaint();
}
}
public class solveAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
_puzzleModel.solve();
_puzzleGraphics.repaint();
}
}
}
Your key classes have no setter methods or constructor parameters that allow you to pass the length and width to them. If you want to change this aspect of their states, then they have to have a mechanism to do this. Currently your GraphicsPanel is hard-coded to use the ROWS and COLS constants, and this will be very hard to change. Instead replace all those hard-codings to variables, and sure have them default to the ROWS and COLS constants in your default constructor, but also provide a non-default constructor that will allow the programmer to pass in a different row and col setting.
Edit
You've got to
Use the constructor parameters to set class fields so that the entire class can use these values, not just the constructor.
Call the proper constructor, the one that requires the parameters!
i.e.,
public MyConstructor(int x, int y) {
this.x = x;
this.y = y;
}

How to use JCheckbox array in JPanel array

I used the code from Hovercraft Full Of Eels and manipulated it a little to get the numbering as I wanted. It looks good now and I can read the status but I can't figure out how to manipulate the individual checkboxes with my buttons on the form. Can someone help?
package and.lotto;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class NewLotto extends JPanel {
public static final int GRID_PANEL_ROWS = 3;
public static final int GRID_PANEL_COLS = 4;
public static final int PANELS = 12;
public static final int BOXES = 12;
private static final int GAP = 1;
private CheckBoxGrid[] checkBoxGrid = new CheckBoxGrid[PANELS];
public NewLotto() {
setLayout(new GridLayout(GRID_PANEL_ROWS, GRID_PANEL_COLS, GAP, GAP));
for (int rows = 0; rows < BOXES; rows++) {
checkBoxGrid[rows] = new CheckBoxGrid(rows,0);
add(checkBoxGrid[rows]);
}
}
private static void createAndShowGui() {
NewLotto mainPanel = new NewLotto();
ButtonPanel buttons = new ButtonPanel();
JFrame frame = new JFrame("Lotto");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(buttons,BorderLayout.NORTH);
frame.add(mainPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel {
JButton generate;
JButton clear;
private ActionListener actionListener = new MyButtonListener();
public ButtonPanel(){
generate = new JButton("Generate numbers");
generate.addActionListener(actionListener);
clear = new JButton("Clear All");
clear.addActionListener(actionListener);
add(generate);
add(clear);
}
private class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Testing");
}
}
}
#SuppressWarnings("serial")
class CheckBoxGrid extends JPanel {
private static final int CHECK_BOXES = 35;
private static final int CHECK_BOX_COLS = 6;
private static final int CHECK_BOX_ROWS = 6;
private static final int GAP = -5;
private JCheckBox[] checkBoxes = new JCheckBox[CHECK_BOXES];
private int gridIndex;
private ItemListener itemListener = new MyCheckBoxListener();
private int row;
private int col;
public CheckBoxGrid(int row, int col) {
this.row = row;
this.col = col;
gridIndex = row + col + 1;
setBorder(BorderFactory.createTitledBorder(String.valueOf(gridIndex)));
setLayout(new GridLayout(CHECK_BOX_ROWS, CHECK_BOX_COLS, GAP, GAP));
for (int cbRow = 0; cbRow < checkBoxes.length; cbRow++) {
JCheckBox checkBox = new JCheckBox();
checkBox.addItemListener(itemListener);
add(checkBox);
checkBox.setRolloverEnabled(false);
checkBox.setRequestFocusEnabled(false);
checkBoxes[cbRow] = checkBox;
}
checkBoxes[0].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red01.png")));
checkBoxes[0].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red01sel.png")));
checkBoxes[1].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red02.png")));
checkBoxes[1].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red02sel.png")));
checkBoxes[2].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red03.png")));
checkBoxes[2].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red03sel.png")));
checkBoxes[3].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red04.png")));
checkBoxes[3].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red04sel.png")));
checkBoxes[4].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red05.png")));
checkBoxes[4].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red05sel.png")));
checkBoxes[5].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red06.png")));
checkBoxes[5].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red06sel.png")));
checkBoxes[6].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red07.png")));
checkBoxes[6].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red07sel.png")));
checkBoxes[7].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red08.png")));
checkBoxes[7].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red08sel.png")));
checkBoxes[8].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red09.png")));
checkBoxes[8].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red09sel.png")));
checkBoxes[9].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red10.png")));
checkBoxes[9].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red10sel.png")));
checkBoxes[10].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red11.png")));
checkBoxes[10].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red11sel.png")));
checkBoxes[11].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red12.png")));
checkBoxes[11].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red12sel.png")));
checkBoxes[12].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red13.png")));
checkBoxes[12].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red13sel.png")));
checkBoxes[13].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red14.png")));
checkBoxes[13].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red14sel.png")));
checkBoxes[14].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red15.png")));
checkBoxes[14].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red15sel.png")));
checkBoxes[15].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red16.png")));
checkBoxes[15].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red16sel.png")));
checkBoxes[16].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red17.png")));
checkBoxes[16].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red17sel.png")));
checkBoxes[17].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red18.png")));
checkBoxes[17].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red18sel.png")));
checkBoxes[18].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red19.png")));
checkBoxes[18].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red19sel.png")));
checkBoxes[19].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red20.png")));
checkBoxes[19].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red20sel.png")));
checkBoxes[20].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red21.png")));
checkBoxes[20].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red21sel.png")));
checkBoxes[21].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red22.png")));
checkBoxes[21].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red22sel.png")));
checkBoxes[22].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red23.png")));
checkBoxes[22].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red23sel.png")));
checkBoxes[23].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red24.png")));
checkBoxes[23].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red24sel.png")));
checkBoxes[24].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red25.png")));
checkBoxes[24].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red25sel.png")));
checkBoxes[25].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red26.png")));
checkBoxes[25].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red26sel.png")));
checkBoxes[26].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red27.png")));
checkBoxes[26].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red27sel.png")));
checkBoxes[27].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red28.png")));
checkBoxes[27].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red28sel.png")));
checkBoxes[28].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red29.png")));
checkBoxes[28].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red29sel.png")));
checkBoxes[29].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red30.png")));
checkBoxes[29].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red30sel.png")));
checkBoxes[30].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red31.png")));
checkBoxes[30].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red31sel.png")));
checkBoxes[31].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red32.png")));
checkBoxes[31].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red32sel.png")));
checkBoxes[32].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red33.png")));
checkBoxes[32].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red33sel.png")));
checkBoxes[33].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red34.png")));
checkBoxes[33].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red34sel.png")));
checkBoxes[34].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red35.png")));
checkBoxes[34].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red35sel.png")));
}
private class MyCheckBoxListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent itemEvt) {
JCheckBox source = (JCheckBox) itemEvt.getSource();
boolean selected = source.isSelected();
int cbRow = -1;
for (int r = 0; r < checkBoxes.length; r++) {
if (source.equals(checkBoxes[r])) {
cbRow = r;
}
}
String text = String.format("Grid %d, selected: %b, at %d",
(row + col + 1), selected, cbRow);
System.out.println(text);
}
}
}
Here is the original question:
I am trying to create a layout with an array of 12 JPanels each containing an array of 35 JCheckboxes. The problem I am having is that although the panels and checkboxes all display fine on the form, I have no way of accessing the properties of the individual checkboxes.
Here is part of the code I use:
JPanel panel_south = new JPanel();
contentPane.add(panel_south, BorderLayout.SOUTH);
panel_south.setLayout(new GridLayout(3, 4, 1, 1));
for(Integer i =0; i<12;i++){
Integer title = i+1;
EtchedBorder border = new EtchedBorder(EtchedBorder.LOWERED, null, null);
TitledBorder titled = new TitledBorder(border,title.toString());
row[i] = new JPanel();
row[i].setBorder(titled);
row[i].setLayout(new GridLayout(6, 6, -6, -5));
panel_south.add(row[i]);
JCheckBox[] rad = new JCheckBox[35];
for (int j = 0;j<35;j++){
rad[j] = new JCheckBox();
row[i].add(rad[j]);
}
When I try to use a line like this in the for loop:
row[i].rad[j].setSelected(true);
I get the error: rad cannot be resolved
What am I doing wrong here?
You should refactor out the JPanel that holds a grid of JTextFields, create a separate class for this, one that accepts a number for it's index, and that holds the JCheckBox grid or a JTable.
e.g.,
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class CheckBoxGridMain extends JPanel {
public static final int GRID_PANEL_ROWS = 3;
public static final int GRID_PANEL_COLS = 4;
private static final int GAP = 1;
private CheckBoxGrid[][] checkBoxGrid = new CheckBoxGrid[GRID_PANEL_ROWS][GRID_PANEL_COLS];
public CheckBoxGridMain() {
setLayout(new GridLayout(GRID_PANEL_ROWS, GRID_PANEL_COLS, GAP, GAP));
for (int row = 0; row < checkBoxGrid.length; row++) {
for (int col = 0; col < checkBoxGrid[row].length; col++) {
checkBoxGrid[row][col] = new CheckBoxGrid(row, col);
add(checkBoxGrid[row][col]);
}
}
}
private static void createAndShowGui() {
CheckBoxGridMain mainPanel = new CheckBoxGridMain();
JFrame frame = new JFrame("CheckBox Grid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class CheckBoxGrid extends JPanel {
private static final int CHECK_BOX_ROWS = 6;
private static final int CHECK_BOX_COLS = 6;
private static final int GAP = -5;
private JCheckBox[][] checkBoxes = new JCheckBox[CHECK_BOX_ROWS][CHECK_BOX_COLS];
private int gridIndex;
private ItemListener itemListener = new MyCheckBoxListener();
private int row;
private int col;
public CheckBoxGrid(int row, int col) {
this.row = row;
this.col = col;
gridIndex = row + col + 1;
setBorder(BorderFactory.createTitledBorder(String.valueOf(gridIndex)));
setLayout(new GridLayout(CHECK_BOX_ROWS, CHECK_BOX_COLS, GAP, GAP));
for (int cbRow = 0; cbRow < checkBoxes.length; cbRow++) {
for (int cbCol = 0; cbCol < checkBoxes[cbRow].length; cbCol++) {
JCheckBox checkBox = new JCheckBox();
checkBox.addItemListener(itemListener);
add(checkBox);
checkBoxes[cbRow][cbCol] = checkBox;
}
}
}
private class MyCheckBoxListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent itemEvt) {
JCheckBox source = (JCheckBox) itemEvt.getSource();
boolean selected = source.isSelected();
int cbRow = -1;
int cbCol = -1;
for (int r = 0; r < checkBoxes.length; r++) {
for (int c = 0; c < checkBoxes[r].length; c++) {
if (source.equals(checkBoxes[r][c])) {
cbRow = r;
cbCol = c;
}
}
}
String text = String.format("Grid %d, selected: %b, at [%d, %d]",
(row + col + 1), selected, cbCol, cbRow); // corrected row/col order
System.out.println(text);
}
}
}
Which displays

Categories

Resources