In my Springbreak holiday I started to write Checkers Game. I have created my CheckersBoard but I couldn't write MouseListener part. Can you help me with this part? I'm not pretty sure how to implement this part? Is MouseListener correct? Or should I choose another Listener? I have googled but couldn't any clue.
Thank you so much.
public class CheckersGUI {
private final JPanel gui = new JPanel(new BorderLayout(3, 3));
private JButton[][] Squares = new JButton[8][8];
private JPanel Board;
private final JLabel message = new JLabel(
"Ready to play!");
private static final String COLS = "ABCDEFGH";
private ImageIcon brown = new ImageIcon("brown.jpg");
private ImageIcon red = new ImageIcon("red.png");
CheckersGUI() {
create();
//create ButtonHandler
/* ButtonHandler handler = new ButtonHandler();
for (int i=0; i<Squares.length; i++){
for (int j=0; i<Squares[0].length; i++){
Squares[i][j].addMouseListener(handler);
}
}
}
private class ButtonHandler implements MouseListener{
public void MouseClicked ( MouseEvent event){
}*/
}
public final void create() {
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
JToolBar tools = new JToolBar();
tools.setFloatable(false);
gui.add(tools, BorderLayout.PAGE_START);
Action newGameAction = new AbstractAction("New") {
#Override
public void actionPerformed(ActionEvent e) {
setupNewGame();
}
};
tools.add(newGameAction);
// TODO - add functionality!
tools.addSeparator();
tools.add(message);
gui.add(new JLabel(""), BorderLayout.LINE_START);
Board = new JPanel(new GridLayout(0, 9)) ;
Board.setBorder(new CompoundBorder(
new EmptyBorder(8,8,8,8),
new LineBorder(Color.BLACK)
));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(Board);
gui.add(boardConstrain);
// create the chess board squares
Insets buttonMargin = new Insets(0, 0, 0, 0);
for (int ii = 0; ii < Squares.length; ii++) {
for (int jj = 0; jj < Squares[ii].length; jj++) {
JButton b = new JButton();
b.setMargin(buttonMargin);
ImageIcon icon = new ImageIcon(
new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB));
b.setIcon(icon);
if ((jj % 2 == 1 && ii % 2 == 1)
|| (jj % 2 == 0 && ii % 2 == 0)) {
b.setBackground(Color.WHITE);
} else {
b.setBackground(Color.BLACK);
}
Squares[jj][ii] = b;
}
}
/*
* fill the chess board
*/
Board.add(new JLabel(""));
// fill the top row
for (int ii = 0; ii < 8; ii++) {
Board.add(
new JLabel(COLS.substring(ii, ii + 1),
SwingConstants.CENTER));
}
// fill the black non-pawn piece row
for (int ii = 0; ii < 8; ii++) {
for (int jj = 0; jj < 8; jj++) {
switch (jj) {
case 0:
Board.add(new JLabel("" + (9-(ii + 1)),
SwingConstants.CENTER));
default:
Board.add(Squares[jj][ii]);
}
}
}
}
public final JComponent getGui() {
return gui;
}
/**
* Initializes the icons of the initial chess board piece places
*/
private final void setupNewGame() {
message.setText("Make your move!");
for (int ii = 0; ii < 8; ii++) {
Squares[ii][1].setIcon(red);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][2].setIcon(red);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][5].setIcon(brown);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][6].setIcon(brown);
}
}
public static void main(String[] args) {
CheckersGUI cg = new CheckersGUI();
JFrame f = new JFrame("Checkers");
f.add(cg.getGui());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
f.setResizable(false);
f.setVisible(true);
}
}
You can add an ActionListener to each button. If the button is pressed (actually, when it is released) the actionPerformed method will be called.
Add the following to your code, to make each square red after it has been clicked:
public static class ButtonHandler implements ActionListener {
private JButton b;
public ButtonHandler(JButton b) {
this.b = b;
}
#Override
public void actionPerformed(ActionEvent e) {
b.setBackground(Color.red);
}
}
This is the handler. Notice that each handler instance will be associated with a button.
Now, create and add a new ButtonHandler to each button after it has been created:
JButton b = new JButton();
...
b.addActionListener(new ButtonHandler(b));
You can change the implementation of actionPerformed.
Example: Add a method getCurrentPlayer() to actionPerformed, then, if the current player is player one, change the color to blue, else, change the color to red.
I trust this will help you to achieve what you need.
Related
I am trying to make a method that disables JButtons.
The JButtons are in an array in the form of a grid, JButton [int][int] and the integers are supposed to be coordinates.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class BS {
public static JFrame f = new JFrame("BS");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
initializeGui();
}
});
}
static void initializeGui() {
JPanel gui = new JPanel(new BorderLayout(3,1));
//This is the array of the JButtons in the form of a grid
final JButton[][] coordinates = new JButton[15][15];
JPanel field;
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
field = new JPanel(new GridLayout(0, 15));
field.setBorder(new CompoundBorder(new EmptyBorder(15,15,15,15),new LineBorder(Color.BLACK)));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(field);
gui.add(boardConstrain);
//The making of the grid
for (int ii = 0; ii < coordinates.length; ii++) {
for (int jj = 0; jj < coordinates[ii].length; jj++) {
JButton b = new JButton();
ImageIcon icon = new ImageIcon(
new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
b.setIcon(icon);
coordinates[jj][ii] = b;
field.add(coordinates[jj][ii]);
}
}
f.add(gui);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
}
I did some changes in your code:
public static JFrame f = new JFrame("BS"); JFrame shouldn't be static and should have a more meaningful name (like frame for example).
final JButton[][] coordinates = new JButton[15][15]; moved this array as a class member and made it non final and also changed the name to buttons as it's easier to know what it is (coordinates to me, sounds more like an array of Point or int)
After that I added an ActionListener, see How to use Actions tutorial.
private ActionListener listener = e -> {
//Loops through the whole array in both dimensions
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) { //Find the JButton that was clicked
if (isStartButton) { //startButton is a boolean variable that tells us if this is the first button clicked or not
startXCoord = i;
startYCoord = j;
} else {
endXCoord = i;
endYCoord = j;
disableButtons(); //Only when we have clicked twice we disable all the buttons in between
}
isStartButton = !isStartButton; //In every button click we change the value of this variable
break; //No need to keep looking if we found our clicked button. Add another one with a condition to skip the outer loop.
}
}
}
};
And a method called disableButtons() which disables all the buttons between the 2 clicked buttons:
private void disableButtons() {
compareCoords(); //This method checks if first button clicked is after 2nd one.
for (int i = startXCoord; i <= endXCoord; i++) {
for (int j = startYCoord; j <= endYCoord; j++) {
buttons[i][j].setEnabled(false); //We disable all buttons in between
}
}
}
At the end our code ends like this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class DisableButtonsInBetween {
private JFrame frame = new JFrame(getClass().getSimpleName());
private JButton[][] buttons;
private int startXCoord = -1;
private int startYCoord = -1;
private int endXCoord = -1;
private int endYCoord = -1;
private boolean isStartButton = true;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisableButtonsInBetween().initializeGui();
}
});
}
void initializeGui() {
JPanel gui = new JPanel(new BorderLayout(3, 1));
// This is the array of the JButtons in the form of a grid
JPanel pane;
buttons = new JButton[15][15];
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
pane = new JPanel(new GridLayout(0, 15));
pane.setBorder(new CompoundBorder(new EmptyBorder(15, 15, 15, 15), new LineBorder(Color.BLACK)));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(pane);
gui.add(boardConstrain);
// The making of the grid
for (int ii = 0; ii < buttons.length; ii++) {
for (int jj = 0; jj < buttons[ii].length; jj++) {
buttons[jj][ii] = new JButton();
ImageIcon icon = new ImageIcon(new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
buttons[jj][ii].setIcon(icon);
buttons[jj][ii].addActionListener(listener);
pane.add(buttons[jj][ii]);
}
}
frame.add(gui);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
}
//The ActionListener is what gets called when you click a JButton
private ActionListener listener = e -> {
//These for loops are done to identify which button was clicked.
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) {
if (isStartButton) {
//We save the coords of the 1st button clicked
startXCoord = i;
startYCoord = j;
} else {
//We save the coords of the 2nd button clicked and call the disableButtons method
endXCoord = i;
endYCoord = j;
disableButtons();
}
isStartButton = !isStartButton;
break;
}
}
}
};
//This method disables all the buttons between the 2 that were clicked
private void disableButtons() {
compareCoords();
for (int i = startXCoord; i <= endXCoord; i++) {
for (int j = startYCoord; j <= endYCoord; j++) {
buttons[i][j].setEnabled(false);
}
}
}
//This method compares the coords if the 2nd button was before (in its coords) than the 1st one it switched their coords
private void compareCoords() {
if (endXCoord < startXCoord) {
int aux = startXCoord;
startXCoord = endXCoord;
endXCoord = aux;
}
if (endYCoord < startYCoord) {
int aux = startYCoord;
startYCoord = endYCoord;
endYCoord = aux;
}
}
}
I hope this is what you were trying to do... if not please clarify.
I do not have the arrow operator, " -> ". I think it requires a higher Java. Is there a way to replace this?
For Java 7 and lower use this for the ActionListener:
private ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) {
if (isStartButton) {
startXCoord = i;
startYCoord = j;
} else {
endXCoord = i;
endYCoord = j;
disableButtons();
}
isStartButton = !isStartButton;
break;
}
}
}
}
};
Please some one can told me why I don't have the JTextField in the same line with my JComboBox ?
I need to have like that:
myJComboBox1 JTextField1
JTextField2
myJComboBox2 JTextField1
JTextField2
following this example
public class DisplayPanel extends JFrame {
private JComboBox[] box;
JTextField[] field1, field2;
public DisplayPanel(){
super(BorderLayoutTest.class.getName());
setTitle("Simulation");
setSize(1000,500);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createComponents();
initComponents();
}
private void createComponents(){
box = new JComboBox[3];
field1 = new JTextField[4];
field2 = new JTextField[5];
}
private void initComponents(){
setLayout(new GridLayout(0, 2));
for(int i = 0; i < 3; i++) {
JPanel panel = new JPanel(new BorderLayout());
box[i] =new JComboBox<>(new String[] { "field1", "field2"});
panel.add(box[i], BorderLayout.NORTH);
add(panel);
add(createPanelWithTextFields(panel));
box[i].setSelectedIndex(-1);
box[i].addActionListener(new CustomActionListener(box[i]));
}
}
private Component createPanelWithTextFields(JPanel panel) {
//need to keep the same layout as JComboBox
panel.setLayout(new GridLayout(0, 1));
for(int x=0; x<4; x++){
field1[x] = new JTextField("field1 Name " + (x+1));
field1[x].setVisible(false);
panel.add(field1[x]);
}
for(int x=0; x<5; x++){
field2[x] = new JTextField("field2 Name " + (x+1));
field2[x].setVisible(false);
panel.add(field2[x]);
}
return panel;
}
class CustomActionListener implements ActionListener {
JComboBox b;
public CustomActionListener(JComboBox u) {
super();
this.b = u;
}
public void actionPerformed(ActionEvent e) {
int numChosen = b.getSelectedIndex() + 1;
switch (numChosen){
case 1:
for(int x=0; x<4; x++)
field1[x].setVisible(true);
break;
case 2:
for(int x=0; x<5; x++)
field2[x].setVisible(true);
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
new DisplayPanel().setVisible(true);
}
});
}
you are assigning new textfield to textfield array.but it contain only 4 textfields.but you call assigning more than 4 times.so what happening is last rextfield references get reassigning and you can't use them again.at the end of the the loop your field array contain reference to textfields of last panel.and that's why your see textfields on last panel even you select from combobox1.
how to fix ?
change this
field1 = new JTextField[4];
to this
field1 = new JTextField[4 * 3];
and then you don't need to reassign jtextfields .you have 3 panels and you have 4 textfields for each panel.
same for field2
here is an example .
public class DisplayPanel extends JFrame {
private JComboBox[] box;
JTextField[] field1, field2;
Color col[] = {Color.red, Color.GREEN, Color.blue};
int i = 0;
int counter = 0;
private int boxcount;
int field1counter = 0;
int field2counter = 0;
public DisplayPanel() {
//super(BorderLayoutTest.class.getName());
setTitle("Simulation");
setSize(1000, 500);
//setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createComponents();
initComponents();
}
private void createComponents() {
boxcount = 3;
box = new JComboBox[1 * boxcount];
field1 = new JTextField[4 * boxcount];
field2 = new JTextField[5 * boxcount];
}
private void initComponents() {
setLayout(new GridLayout(0, 2));
for (int i = 0; i < 3; i++) {
JPanel panel = new JPanel(new BorderLayout());
box[i] = new JComboBox<>(new String[]{"field1", "field2"});
panel.add(box[i], BorderLayout.NORTH);
add(panel);
add(createPanelWithTextFields(panel));
box[i].setSelectedIndex(-1);
box[i].addActionListener(new CustomActionListener());
}
}
private Component createPanelWithTextFields(JPanel panelc) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.setBackground(col[i]);
System.out.println("......................");
for (int x = 0; x < 4; x++) {
System.out.println("iterating .." + (field1counter) + " counter " + counter);
field1[field1counter] = new JTextField("field1 Name " + (x + 1));
field1[field1counter].setVisible(false);
panel.add(field1[field1counter]);
field1counter++;
}
for (int x = 0; x < 5; x++) {
field2[field2counter] = new JTextField("field2 Name " + (x + 1));
field2[field2counter].setVisible(false);
panel.add(field2[field2counter]);
field2counter++;
}
i++;
counter++;
return panel;
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox b = (JComboBox) e.getSource();
int comboidenty = 0;
for (int k = 0; k < box.length; k++) {
if (box[k] == b) {
break;
}
comboidenty++;
}
System.out.println(((JPanel) (b.getParent())).getBackground());
int numChosen = b.getSelectedIndex() + 1;
System.out.println("hi " + comboidenty);
switch (numChosen) {
case 1:
for (int x = 0; x < 4; x++) {
System.out.println("field1 " + (comboidenty * 4 + x));
field1[comboidenty * 4 + x].setVisible(true);
}
break;
case 2:
for (int x = 0; x < 5; x++) {
System.out.println("field2 " + (comboidenty * 5 + x));
field2[comboidenty * 5 + x].setVisible(true);
}
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DisplayPanel().setVisible(true);
}
});
}
}
The first image shows what the GUI looks like when I just start it, the second shows what happens when I click around the board. The chess pieces show up at the top row after I click a piece and then click on a button on the top row. What is happening here?!
The code is below; this class is where I have most of my code. The rest of the classes are just loading images at this point. The Board constructor is called in the main to build the GUI.
public class BoardPanel extends JPanel {
public BoardPanel() {
createBoard();
}
private void createBoard(){
setLayout(new GridLayout(10, 10));
// Makes a 10 x 10 grid of black and white colors
for (int i = 0; i<10; i++){
for (int j = 0; j<10; j++){
square[i][j] = new JButton();
square[i][j].setRolloverEnabled(false);
if ((i+j)%2 == 0)
square[i][j].setBackground(Color.WHITE);
else
square[i][j].setBackground(Color.LIGHT_GRAY);
add(square[i][j]);
}
}
addLabels();
//Colors the corner squares
square[0][0].setBackground(new Color(155, 234, 242, 100));
square[0][9].setBackground(new Color(155, 234, 242, 100));
square[9][0].setBackground(new Color(155, 234, 242, 100));
square[9][9].setBackground(new Color(155, 234, 242, 100));
}
private void addLabels(){
//Adds labels to the ranks
for (int i =1 ; i< 9; i++){
square[i][0].setBackground(new Color(155, 234, 242, 100));
square[i][0].setText(rank[8-i]);
square[i][0].setHorizontalTextPosition(SwingConstants.RIGHT);
square[i][9].setBackground(new Color(155, 234, 242, 100));
square[i][9].setText(rank[8-i]);
square[i][9].setHorizontalTextPosition(SwingConstants.LEFT);
}
//Adds labels to the files
for (int j = 1; j<9;j++){
square[0][j].setBackground(new Color(155, 234, 242, 100));
square[0][j].setText(file[j-1]);
square[0][j].setVerticalTextPosition(SwingConstants.BOTTOM);
square[9][j].setBackground(new Color(155, 234, 242, 100));
square[9][j].setText(file[j-1]);
square[9][j].setVerticalTextPosition(SwingConstants.TOP);
}
JButton square[][] = new JButton[10][10];
String[] rank = {"1","2","3","4","5","6","7","8"};
String[] file = {"a","b","c","d","e","f","g","h"};
}
}
The main class
public class Board {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new BoardPanel());
frame.setVisible(true);
frame.setSize(900, 700);
}
}
Your problem is with the button thinking that it is fully opaque when it is in fact not opaque. As per Kleopatra in this answer, you must make the button non-opaque and take over the painting mechanisms
square[i][j] = new JButton() {
#Override // !! add this:
protected void paintComponent(Graphics g) {
if (!isOpaque() && getBackground().getAlpha() < 255) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g);
}
};
square[i][j].setRolloverEnabled(false);
square[i][j].setOpaque(false); // !! and also add this *******
As a side note, I wouldn't be using JButtons for this type of problem, but rather I'd be using JPanels, and would place my chess pieces as ImageIcons displayed in JLabels, labels that are added to or removed from the appropriate chess-board squares.
A board without buttons and without use of alpha colors:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class Board2 extends JPanel {
private static final int SIDE_LEN = 80;
private static final Dimension SQUARE_SZ = new Dimension(SIDE_LEN, SIDE_LEN);
private static final Color EDGE_COLOR = new Color(165, 245, 250);
private static final Color DARK_SQR_COLOR = Color.LIGHT_GRAY;
private static final Color LIGHT_SQR_COLOR = Color.WHITE;
private JPanel[][] chessSquares = new JPanel[8][8];
public Board2() {
setLayout(new GridLayout(10, 10)); // sorry for magic numbers
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if ((i == 0 || i == 9) && (j == 0 || j == 9)) {
add(createEdgePanel(""));
} else if (i == 0 || i == 9) {
String text = String.valueOf((char) (j + 'a' - 1));
add(createEdgePanel(text));
} else if (j == 0 || j == 9) {
String text = String.valueOf(8 - i + 1);
add(createEdgePanel(text));
} else {
JPanel panel = createSquare(i, j);
add(panel);
}
}
}
}
private JPanel createSquare(int i, int j) {
JPanel panel = new JPanel(new GridBagLayout());
Color c = (i % 2 == j % 2) ? LIGHT_SQR_COLOR : DARK_SQR_COLOR;
panel.setBackground(c);
panel.setPreferredSize(SQUARE_SZ);
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return panel;
}
private JPanel createEdgePanel(String text) {
JLabel label = new JLabel(text, SwingConstants.CENTER);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setBackground(EDGE_COLOR);
panel.setPreferredSize(SQUARE_SZ);
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return panel;
}
private static void createAndShowGui() {
Board2 mainPanel = new Board2();
JFrame frame = new JFrame("Board2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
}
});
}
}
Which on my system looks like:
Now with some pieces added:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class Board2 extends JPanel {
private static final int SIDE_LEN = 80;
private static final Dimension SQUARE_SZ = new Dimension(SIDE_LEN, SIDE_LEN);
private static final String SPRITE_PATH = "http://i.stack.imgur.com/memI0.png";
private static final int SPRITE_ROWS = 2;
private static final int SPRITE_COLS = 6;
private static final Color EDGE_COLOR = new Color(165, 245, 250);
private static final Color DARK_SQR_COLOR = Color.LIGHT_GRAY;
private static final Color LIGHT_SQR_COLOR = Color.WHITE;
private static final int ROWS = 8;
private JLabel[][] chessSquares = new JLabel[ROWS][ROWS];
private BufferedImage bigImage;
private List<Icon> icons = new ArrayList<>();
public Board2() throws IOException {
URL imgUrl = new URL(SPRITE_PATH);
bigImage = ImageIO.read(imgUrl);
int w = bigImage.getWidth() / SPRITE_COLS;
int h = bigImage.getHeight() / SPRITE_ROWS;
for (int i = 0; i < SPRITE_ROWS; i++) {
for (int j = 0; j < SPRITE_COLS; j++) {
int x = (j * bigImage.getWidth()) / SPRITE_COLS;
int y = (i * bigImage.getHeight()) / SPRITE_ROWS;
BufferedImage spriteImg = bigImage.getSubimage(x, y, w, h);
Icon spriteIcon = new ImageIcon(spriteImg);
icons.add(spriteIcon);
}
}
for (int i = 0; i < chessSquares.length; i++) {
for (int j = 0; j < chessSquares[i].length; j++) {
chessSquares[i][j] = new JLabel();
}
}
setLayout(new GridLayout(ROWS + 2, ROWS + 2)); // sorry for magic numbers
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if ((i == 0 || i == ROWS + 1) && (j == 0 || j == ROWS + 1)) {
add(createEdgePanel(""));
} else if (i == 0 || i == ROWS + 1) {
String text = String.valueOf((char) (j + 'a' - 1));
add(createEdgePanel(text));
} else if (j == 0 || j == ROWS + 1) {
String text = String.valueOf(ROWS - i + 1);
add(createEdgePanel(text));
} else {
JPanel panel = createSquare(i, j);
panel.add(chessSquares[i - 1][j - 1]);
add(panel);
}
}
}
setPieces(0, 0, 2); // rooks
setPieces(1, 0, 3); // knights
setPieces(2, 0, 4); // bishops
// kings and queens
chessSquares[0][3].setIcon(icons.get(1));
chessSquares[7][3].setIcon(icons.get(6 + 1));
chessSquares[0][4].setIcon(icons.get(0));
chessSquares[7][4].setIcon(icons.get(6 + 0));
// pawns
for (int i = 0; i < ROWS / 2; i++) {
setPieces(i, 1, 5);
}
}
private void setPieces(int colPos, int rowPos, int pieceIndex) {
chessSquares[rowPos][colPos].setIcon(icons.get(pieceIndex));
chessSquares[rowPos][ROWS - 1 - colPos].setIcon(icons.get(pieceIndex));
chessSquares[ROWS - 1 - rowPos][colPos].setIcon(icons.get(6 + pieceIndex));
chessSquares[ROWS - 1 - rowPos][ROWS - 1 - colPos].setIcon(icons
.get(6 + pieceIndex));
}
private void setPiece(int colPos, int pieceIndex) {
chessSquares[0][colPos].setIcon(icons.get(pieceIndex));
chessSquares[ROWS - 1][ROWS - 1 - colPos].setIcon(icons.get(6 + pieceIndex));
}
private JPanel createSquare(int i, int j) {
JPanel panel = new JPanel(new GridBagLayout());
Color c = (i % 2 == j % 2) ? LIGHT_SQR_COLOR : DARK_SQR_COLOR;
panel.setBackground(c);
panel.setPreferredSize(SQUARE_SZ);
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return panel;
}
private JPanel createEdgePanel(String text) {
JLabel label = new JLabel(text, SwingConstants.CENTER);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setBackground(EDGE_COLOR);
panel.setPreferredSize(SQUARE_SZ);
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return panel;
}
private static void createAndShowGui() {
Board2 mainPanel = null;
try {
mainPanel = new Board2();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("Board2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
}
});
}
}
I added listeners to my JButtons for the popup menu but when the popup menu appears the JButtons disappear and I would need to hover my cursor on the buttons to make them appear again. Why is it like this?
(all the methods here are in the same class)
public Inventory() {
setLayout(null);
setBounds(0, 0, 175, 210);
initPopupMenu(); // this just sets what is inside the popup menu
int x;
// 30 buttons
for(x = 0; x < 30; x++) {
button[x] = new JButton();
add(button[x]);
button[x].addMouseListener(this);
}
x = 0;
// it's a grid of buttons
for(int i = 0; i < 5; i++)
for(int j = 0; j < 6; j++) {
button[x].setBounds(i*35+1,j*35+1, 33,33);
x++;
}
}
public void mouseClicked(MouseEvent e) {
for(int j = 0; j < 30; j++) // i tried this one but it still disappears
button[j].repaint();
for(int i = 0; i < 30; i++) {
if(e.getSource() == button[i]) {
System.out.println("You pressed Button "+i);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
This is what happens,
Stop using null Layout, seems like that can be one of the issues regarding this. Your JFrame appears sort of BLACK to me, is this some THEME or a new LOOK AND FEEL you are using, that can be the cause of this thing too. Here check this out, it's working flawlessly here with this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonPopUp
{
private static final int SIZE = 30;
private JButton[] button = new JButton[SIZE];
private JPopupMenu popup = new JPopupMenu("Hello World");
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Button POP UP Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
final JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 5));
JMenuItem menuItem1 = new JMenuItem("Menu Item 1");
JMenuItem menuItem2 = new JMenuItem("Menu Item 2");
//popup.add(greetings);
popup.insert(menuItem1, 0);
popup.insert(menuItem2, 1);
for (int i = 0; i < SIZE; i++)
{
button[i] = new JButton();
button[i].setBorder(BorderFactory.createEtchedBorder());
button[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
System.out.println("I am WORKING!!");
popup.show((JComponent)me.getSource(), me.getX(), me.getY());
}
});
contentPane.add(button[i]);
}
frame.getContentPane().add(contentPane);
frame.setSize(175, 250);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ButtonPopUp().createAndDisplayGUI();
}
});
}
}
Here is the output :
I believe I have got most of the MVC part down for this program - Game Of Life. However I can't get the MouseListener to work properly. How can I change this match the MVC design pattern?
View
package lifepreparation;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import javax.swing.*;
import java.awt.event.MouseListener;
public class LifeView extends JFrame {
//Label used to house cells
private LifeModel[][] cellHouse;
private LifeModel model;
//Timer used to fire the next generation
private Timer timer;
//Generation counter - used to count the number of generations
private int generationCount = 0;
private JLabel generationLabel = new JLabel("Generation: 0");
//Declare action buttons
private JButton startB = new JButton("Start");
private JButton pauseB = new JButton("Pause");
private JButton clearB = new JButton("Clear");
//Slider to adjust the time interval between generations
private static final int minSpeed = 0;
private static final int maxSpeed = 1000;
private static final int speedMajorTicks = (maxSpeed-minSpeed)/5;
private static final int speedMinorTicks = (maxSpeed-minSpeed)/20;
JSlider generationS = new JSlider(minSpeed,maxSpeed);
//Identifies game status: false=pause, true=running
private boolean runStatus = false;
//Panel for the city
private JPanel panel;
public LifeView(int boardRow, int boardCol, LifeModel model) {
super("Game Of Life");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//**START Create labels to house cells, +2 more
cellHouse = new LifeModel[boardRow+2][boardCol+2];
for(int r = 0; r < boardRow+2; r++) {
for(int c = 0; c < boardCol+2; c++) {
cellHouse[r][c] = new LifeModel();
}
}
//--END Create Labels
//Panel to hold cell houses
panel = new JPanel(new GridLayout(boardRow, boardCol, 1, 1));
panel.setBackground(Color.BLACK);
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
//Add cellHouses to the panel
for(int r = 1; r < boardRow+1; r++) {
for(int c = 1; c < boardCol+1; c++) {
panel.add(cellHouse[r][c]);
cellHouse[r][c].addNeighbor(cellHouse[r-1][c]); //Add to TOP ^
cellHouse[r][c].addNeighbor(cellHouse[r+1][c]); //Add to BOTTOM _
cellHouse[r][c].addNeighbor(cellHouse[r][c-1]); //Add to left <-
cellHouse[r][c].addNeighbor(cellHouse[r][c+1]); //Add to right ->
cellHouse[r][c].addNeighbor(cellHouse[r-1][c-1]); //Add to top left ^<-
cellHouse[r][c].addNeighbor(cellHouse[r-1][c+1]); //Add to top right ^->
cellHouse[r][c].addNeighbor(cellHouse[r+1][c-1]); //Add to bottom left _<-
cellHouse[r][c].addNeighbor(cellHouse[r+1][c+1]); //Add to bottom right _->
}
}
//Panel with cellHouses added to the container
add(panel, BorderLayout.CENTER);
//South Panel to hold buttons and widgets with extra features
JPanel panelBottom = new JPanel();
//buttonPanel to hold start, pause, clear features
JPanel buttonPanel = new JPanel();
buttonPanel.add(clearB);
pauseB.setEnabled(false);
buttonPanel.add(pauseB);
buttonPanel.add(startB);
//speedPanel to hold slider to adjust the time interval
JPanel speedPanel = new JPanel();
JLabel speedText = new JLabel("Set Speed:");
generationS.setMajorTickSpacing(speedMajorTicks);
generationS.setMinorTickSpacing(speedMinorTicks);
generationS.setPaintTicks(true);
// the labels for the Slider
Hashtable<Integer, JLabel> speedLabel = new Hashtable<Integer, JLabel>();
for(int i = 0; i <= maxSpeed; i++) {
speedLabel.put( new Integer( i * speedMajorTicks ), new JLabel("" + i) );
}
generationS.setLabelTable(speedLabel);
generationS.setPaintLabels(true);
generationLabel.setHorizontalAlignment(SwingConstants.CENTER);
speedPanel.add(speedText);
speedPanel.add(generationS);
panelBottom.add(buttonPanel);
panelBottom.add(speedPanel);
panelBottom.add(generationLabel);
// add bottom panel to the JFrame
add(panelBottom, BorderLayout.SOUTH);
// put the frame on
setLocation(20, 20);
pack();
setVisible(true);
}
//Action to take dependent on the action referenced by the JButton and Timer
public void startPauseClear(ActionEvent e) {
//Get action reference
Object o = e.getSource();
//Action reference is to clear
if(o == clearB) {
timer.stop(); //Stop the timer
runStatus = false; //Set game as not running
pauseB.setEnabled(false); //Disable the pause button
startB.setEnabled(true); //Enable the start button
//Remove/Clear all cells from the cellHouse
for(int r = 1; r < cellHouse.length -1; r++) {
for(int c = 1; c < cellHouse[r].length -1; c++) {
cellHouse[r][c].clear();
}
}
//Reset the generation count
generationCount = 0;
generationLabel.setText("Generation: 0");
return;
}
//Action reference is to pause
if(o == pauseB) {
timer.stop(); //Stop the timer
runStatus = false; //Set game as not running
pauseB.setEnabled(false); //Disable the pause button
startB.setEnabled(true); //Enable the start button
return;
}
//Action reference is to start
if(o == startB) {
pauseB.setEnabled(true); //Enable the pause button
startB.setEnabled(false); //Disable the start button
runStatus = true; //Set game as running
timer.setDelay(maxSpeed - generationS.getValue()); //Adjust the speed
timer.start();
return;
}
//If the action is set by timer, set speed
timer.setDelay(maxSpeed - generationS.getValue());
//If the game is not running, exit and do nothing more
if(!runStatus) return;
//Update generation count and display
++generationCount;
generationLabel.setText("Generation: " + generationCount);
//Check to see if the cell should be buried
for(int r = 0; r < cellHouse.length; r++) {
for(int c = 0; c < cellHouse[r].length; c++) {
cellHouse[r][c].checkGeneration();
}
}
//Update to the next generation
for(int r = 0; r < cellHouse.length; r++) {
for(int c = 0; c < cellHouse[r].length; c++) {
cellHouse[r][c].updateGeneration();
}
}
}
public void addActionListener(ActionListener e) {
clearB.addActionListener(e);
pauseB.addActionListener(e);
startB.addActionListener(e);
timer = new Timer(maxSpeed - generationS.getValue(), e);
}
}
Controller
package lifepreparation;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class LifeController {
//Run App
LifeModel model;
LifeView view;
//Constructor
public LifeController(LifeModel model, LifeView view) {
this.model = model;
this.view = view;
//Add Listeners
view.addActionListener(new LifeActionListener());
view.addMouseListener(new LifeMouseListener());
}
class LifeActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
view.startPauseClear(e);
}
}
class LifeMouseListener implements MouseListener {
public void mouseClicked(MouseEvent arg0) {
model.unselectCell();
}
//If the mouse is in a cellHouse while being pressed, cell becomes alive
public void mouseEntered(MouseEvent arg0) {
model.selectCells();
}
public void mouseExited(MouseEvent arg0) {
}
//If the mouse is clicked on a cellHouse, cell comes to life
public void mousePressed(MouseEvent arg0) {
model.selectACell();
}
//Set mouse as not being held anymore
public void mouseReleased(MouseEvent arg0) {
model.setMouseHold();
}
}
}
Model
package lifepreparation;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//LifeModel to handle cell life and death algorithm
public class LifeModel extends JLabel {
//Cell Color: cell[0] = dead cell, cell[1] = live cell.
private static final Color[] color = {Color.LIGHT_GRAY, Color.GREEN};
//Size of cells
private static final int cellSize = 15;
private static final Dimension citySize = new Dimension(cellSize, cellSize);
//checks if the mouse is still pressed or not
private boolean mouseHold = false;
private int currentStatus, newStatus;
private int nbNeighbor;
private LifeModel[] Neighbor = new LifeModel[8];
LifeModel() {
currentStatus = newStatus = 0; //Currently Dead
setOpaque(true); //Show color
setBackground(color[0]); //Light Gray color
this.setPreferredSize(citySize); //Set the dimension of the board
}
//Add a neighbor
void addNeighbor(LifeModel n) {
Neighbor[nbNeighbor++] = n;
}
//Check to see if a cell should live or not
void checkGeneration() {
//Number of neighbors that are alive
int nbAlive = 0;
//Check the status of the neighbors
for(int i = 0; i < nbNeighbor; i++)
nbAlive += Neighbor[i].currentStatus;
//If status of cell is alive
if(currentStatus == 1) {
//Bury cell if it has less than two neighbors
if(nbAlive < 2)
newStatus = 0;
//Bury cell if it has more than three live neighbors
if(nbAlive > 3)
newStatus = 0;
}
else {
//Dead cells with three live neighbors get reborn
if(nbAlive == 3)
newStatus = 1;
}
}
//Switch to next generation
void updateGeneration() {
if(currentStatus != newStatus) { //Adjust color for the new generation
currentStatus = newStatus;
setBackground(color[currentStatus]);
}
}
//Bury all cells in the city
void clear() {
if(currentStatus == 1 || newStatus == 1) {
currentStatus = newStatus = 0;
setBackground(color[currentStatus]);
}
}
public void unselectCell() {
if(currentStatus == 1 || newStatus == 1) {
currentStatus = newStatus = 0;
setBackground(color[currentStatus]);
}
}
//If the mouse is in a cellHouse while being pressed, cell becomes alive
public void selectCells() {
if(mouseHold) {
currentStatus = newStatus = 1;
setBackground(color[1]);
}
}
//If the mouse is clicked on a cellHouse, cell comes to life
public void selectACell() {
mouseHold = true;
currentStatus = newStatus = 1;
setBackground(color[1]);
}
//Set mouse as not being held anymore
public void setMouseHold() {
mouseHold = false;
}
}
Program without MVC implementation
package lifepreparation;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import javax.swing.*;
public class LifeView extends JFrame implements ActionListener {
//Cell Color: cell[0] = dead cell, cell[1] = live cell.
private static final Color[] color = {Color.LIGHT_GRAY, Color.GREEN};
//Size of cells
private static final int cellSize = 15;
private static final Dimension citySize = new Dimension(cellSize, cellSize);
//Label used to house cells
private LifeLabel[][] cellHouse;
//Timer used to fire the next generation
private Timer timer;
//Generation counter - used to count the number of generations
private int generationCount = 0;
private JLabel generationLabel = new JLabel("Generation: 0");
//Declare default buttons
private JButton startB = new JButton("Start");
private JButton pauseB = new JButton("Pause");
private JButton clearB = new JButton("Clear");
//Slider to adjust the time interval between generations
private static final int minSpeed = 0;
private static final int maxSpeed = 1000;
private static final int speedMajorTicks = (maxSpeed-minSpeed)/5;
private static final int speedMinorTicks = (maxSpeed-minSpeed)/20;
JSlider generationS = new JSlider(minSpeed,maxSpeed);
//Identifies game status: false=pause, true=running
private boolean runStatus = false;
// if the mouse is down or not
private boolean mouseHold = false;
public LifeView(int boardRow, int boardCol) {
super("Game Of Life");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//**START Create labels to house cells, +2 more to calculate cells that are out of bounds
cellHouse = new LifeLabel[boardRow+2][boardCol+2];
for(int r = 0; r < boardRow+2; r++) {
for(int c = 0; c < boardCol+2; c++) {
cellHouse[r][c] = new LifeLabel();
}
}
//--END Create Labels
//Panel to hold cell houses
JPanel panel = new JPanel(new GridLayout(boardRow, boardCol, 1, 1));
panel.setBackground(Color.BLACK);
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
//Add cellHouses to the panel
for(int r = 1; r < boardRow+1; r++) {
for(int c = 1; c < boardCol+1; c++) {
panel.add(cellHouse[r][c]);
cellHouse[r][c].addNeighbor(cellHouse[r-1][c]); //Add to TOP ^
cellHouse[r][c].addNeighbor(cellHouse[r+1][c]); //Add to BOTTOM _
cellHouse[r][c].addNeighbor(cellHouse[r][c-1]); //Add to left <-
cellHouse[r][c].addNeighbor(cellHouse[r][c+1]); //Add to right ->
cellHouse[r][c].addNeighbor(cellHouse[r-1][c-1]); //Add to top left ^<-
cellHouse[r][c].addNeighbor(cellHouse[r-1][c+1]); //Add to top right ^->
cellHouse[r][c].addNeighbor(cellHouse[r+1][c-1]); //Add to bottom left _<-
cellHouse[r][c].addNeighbor(cellHouse[r+1][c+1]); //Add to bottom right _->
}
}
//Panel with cellHouses added to the container
add(panel, BorderLayout.CENTER);
//South Panel to hold buttons and widgets with extra features
JPanel panelBottom = new JPanel();
//buttonPanel to hold start, pause, clear features
JPanel buttonPanel = new JPanel();
clearB.addActionListener(this);
buttonPanel.add(clearB);
pauseB.addActionListener(this);
pauseB.setEnabled(false);
buttonPanel.add(pauseB);
startB.addActionListener(this);
buttonPanel.add(startB);
//speedPanel to hold slider to adjust the time interval
JPanel speedPanel = new JPanel();
JLabel speedText = new JLabel("Set Speed:");
generationS.setMajorTickSpacing(speedMajorTicks);
generationS.setMinorTickSpacing(speedMinorTicks);
generationS.setPaintTicks(true);
// the labels for the Slider
Hashtable<Integer, JLabel> speedLabel = new Hashtable<Integer, JLabel>();
for(int i = 0; i <= maxSpeed; i++) {
speedLabel.put( new Integer( i * speedMajorTicks ), new JLabel("" + i) );
}
generationS.setLabelTable(speedLabel);
generationS.setPaintLabels(true);
generationLabel.setHorizontalAlignment(SwingConstants.CENTER);
speedPanel.add(speedText);
speedPanel.add(generationS);
panelBottom.add(buttonPanel);
panelBottom.add(speedPanel);
panelBottom.add(generationLabel);
// add bottom panel to the JFrame
add(panelBottom, BorderLayout.SOUTH);
// put the frame on
setLocation(20, 20);
pack();
setVisible(true);
// start the thread that run the cycles of life
timer = new Timer(maxSpeed - generationS.getValue(), this);
}
//Action to take dependent on the action referenced by the JButton and Timer
public void actionPerformed(ActionEvent e) {
//Get action reference
Object o = e.getSource();
//Action reference is to clear
if(o == clearB) {
timer.stop(); //Stop the timer
runStatus = false; //Set game as not running
pauseB.setEnabled(false); //Disable the pause button
startB.setEnabled(true); //Enable the start button
//Remove/Clear all cells from the cellHouse
for(int r = 1; r < cellHouse.length -1; r++) {
for(int c = 1; c < cellHouse[r].length -1; c++) {
cellHouse[r][c].clear();
}
}
//Reset the generation count
generationCount = 0;
generationLabel.setText("Generation: 0");
return;
}
//Action reference is to pause
if(o == pauseB) {
timer.stop(); //Stop the timer
runStatus = false; //Set game as not running
pauseB.setEnabled(false); //Disable the pause button
startB.setEnabled(true); //Enable the start button
return;
}
//Action reference is to start
if(o == startB) {
pauseB.setEnabled(true); //Enable the pause button
startB.setEnabled(false); //Disable the start button
runStatus = true; //Set game as running
timer.setDelay(maxSpeed - generationS.getValue()); //Adjust the speed
timer.start();
return;
}
//If the action is set by timer, set speed
timer.setDelay(maxSpeed - generationS.getValue());
//If the game is not running, exit and do nothing more
if(!runStatus) return;
//Update generation count and display
++generationCount;
generationLabel.setText("Generation: " + generationCount);
//Check to see if the cell should be buried
for(int r = 0; r < cellHouse.length; r++) {
for(int c = 0; c < cellHouse[r].length; c++) {
cellHouse[r][c].checkGeneration();
}
}
//Update to the next generation
for(int r = 0; r < cellHouse.length; r++) {
for(int c = 0; c < cellHouse[r].length; c++) {
cellHouse[r][c].updateGeneration();
}
}
}
//Run App
public static void main(String[] arg) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LifeView(30, 50);
}
});
}
//LifeModel to handle cell life and death algorithm
class LifeLabel extends JLabel implements MouseListener {
private int currentGen, newGen;
private int nbNeighbor;
private LifeLabel[] Neighbor = new LifeLabel[8];
LifeLabel() {
currentGen = newGen = 0; //Currently Dead
setOpaque(true); //Show color
setBackground(color[0]); //Light Gray color
addMouseListener(this); //Add mouseListener
this.setPreferredSize(citySize); //Set the dimension of the board
}
//Add a neighbor
void addNeighbor(LifeLabel n) {
Neighbor[nbNeighbor++] = n;
}
//Check to see if a cell should live or not
void checkGeneration() {
//Number of neighbors that are alive
int nbAlive = 0;
//Check the status of the neighbors
for(int i = 0; i < nbNeighbor; i++)
nbAlive += Neighbor[i].currentGen;
//If status of cell is alive
if(currentGen == 1) {
//Bury cell if it has less than two neighbors
if(nbAlive < 2)
newGen = 0;
//Bury cell if it has more than three live neighbors
if(nbAlive > 3)
newGen = 0;
}
else {
//Dead cells with three live neighbors get reborn
if(nbAlive == 3)
newGen = 1;
}
}
//Switch to next generation
void updateGeneration() {
if(currentGen != newGen) { //Adjust color for the new generation
currentGen = newGen;
setBackground(color[currentGen]);
}
}
//Bury all cells in the city
void clear() {
if(currentGen == 1 || newGen == 1) {
currentGen = newGen = 0;
setBackground(color[currentGen]);
}
}
public void mouseClicked(MouseEvent arg0) {
if(currentGen == 1 || newGen == 1) {
currentGen = newGen = 0;
setBackground(color[currentGen]);
}
}
//If the mouse is in a cellHouse while being pressed, cell becomes alive
public void mouseEntered(MouseEvent arg0) {
if(mouseHold) {
currentGen = newGen = 1;
setBackground(color[1]);
}
}
public void mouseExited(MouseEvent arg0) {
}
//If the mouse is clicked on a cellHouse, cell comes to life
public void mousePressed(MouseEvent arg0) {
mouseHold = true;
currentGen = newGen = 1;
setBackground(color[1]);
}
//Set mouse as not being held anymore
public void mouseReleased(MouseEvent arg0) {
mouseHold = false;
}
}
}
Your code it too hard to follow, but I have done an application using mvc in swing.
My advice is to have something like this in a Main class:
MainModel model = new MainModel();
MainView view = new MainView(model);
MainController controller = new MainController(model, view);
Your controller is ok.
The view looks ok, but you should have separate addActionListener methods for clearB, startB, pauseB (perhaps that's the problem).
The model is where the brain should be. Do not extend JLabel, doesn't make sense at all.
Hope this helps.