I keep getting a null pointer exception at the line between the * lines when I click. I've been looking at it for about an hour and cant seem to figure out why. Any help would be greatly appreciated. Thanks.
private Color currentColor;
private char currentChar;
private Letter letter;
private JComboBox comboBox;
private JPanel controlPanel;
private Color[] colorArray = {Color.black,Color.blue,Color.cyan,Color.orange,Color.white,Color.yellow};
private String[] colorStringArray = {"black","blue","cyan","orange","white","yellow"};
private ArrayList<Letter> letterList;
private JButton button1;
private Canvas canvas;
public WholePanel()
{
comboBox = new JComboBox(colorStringArray);
// here we use black to draw a letter
currentColor = colorArray[Color.black];
// set the default character to 'A'
currentChar = 'A';
button1 = new JButton("Undo");
controlPanel = new JPanel();
controlPanel.add(button1);
controlPanel.add(comboBox);
canvas = new Canvas();
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, controlPanel, canvas);
canvas.addMouseListener(new PointListener());
add(sp);
// make this panel listen to mouse
addMouseListener(new PointListener());
setBackground(Color.white);
//This method needs to be called for this panel to listen to keys
//When panel listens to other things, and go back to listen
//to keys, this method needs to be called again.
requestFocus();
}
private class PointListener implements MouseListener
{
int x;
int y;
// when a user clicks the panel (applet),
// KeyListener is focused in it.
public void mousePressed(MouseEvent event)
{
x = event.getX();
y = event.getY();
letter = new Letter(x,y,currentChar,colorArray[comboBox.getSelectedIndex()]);
//******************************
letterList.add(letter);
//******************************
for(Letter letter1 : letterList)
{
letter1.Draw(getGraphics());
}
x=y=0;
requestFocus();
}
}
}
You didn't initialize letterList.
Add the following line to your constructor for WholePanel:
letterList = new ArrayList<Letter>();
Related
I am trying to create a small tic tac toe game using a 2D array of JToggleButtons, I got the general layout and have a 3x3 grid of JToggleButtons and added an ActionListener to each button when they are added to the window. However whatever I try I cant seem to get an Icon change on any of the JToggleButtons at all. How exactly can I change the icon and check that it was selected? I have 1 class Board.java, a main class that init's the Board, and a class ButtonListener that implements ActionListener.
Board.java:
public class Board extends JPanel{
private JToggleButton[][] grid = new JToggleButton[3][3];
private final int BOARD_WIDTH = 800;
private final int BOARD_HEIGHT = 600;
static Icon oIcon = new ImageIcon("src/TicTacToeBoard/assets/16894.png");
static Icon xIcon = new ImageIcon("src/TicTacToeBoard/assets/1828778.png");
JFrame board;
JPanel panel;
public Board(){
initBoard();
}
private void makePanel(){
panel.setBackground(Color.lightGray);
panel.setLayout(new GridLayout(3,3));
setBoard();
board.add(panel);
}
private void initBoard(){
board = new JFrame();
panel = new JPanel();
board.setTitle("JTicTacToe");
board.setSize(BOARD_WIDTH, BOARD_HEIGHT);
board.setResizable(false);
board.setLocationRelativeTo(null);
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
makePanel();
board.setVisible(true);
}
private void setBoard(){
//Loop through 2D array
for(int row = 0; row < grid.length; row++){
for(int col = 0; col < grid[row].length; col++){
grid[row][col] = new JToggleButton();
grid[row][col].setBackground(Color.BLACK);
grid[row][col].setForeground(Color.white);
grid[row][col].putClientProperty("row", row);
grid[row][col].putClientProperty("column",col);
grid[row][col].addActionListener(new ButtonListener());
panel.add(grid[row][col]);
}
}
}
protected class ButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
JToggleButton button = (JToggleButton) e.getSource();
//Just to see if I can set the icon after click
if(button.isSelected()){
button.setIcon(Board.oIcon);
}
//Test to see if I can get some sort of output in console after each toggle button is clicked
//But for some reason I can't change the icons? why?
System.out.println("clicked column " + button.getClientProperty("column")
+ ", row " + button.getClientProperty("row"));
}
}
}
The assignment asks for a super class Shape and two subclasses Circle and Square.
I am to create an applet for selecting a shape (circle or square), size, and color from three separate JComboBox.
Every time the user clicks on the canvas, an object of the Shape class should be created according to the selections in the ComboBoxes and stored in an ArrayList to be printed out.
There is some sort of "lag" on the updating of the color variable. Every time I make a selection from the ComboBox associated with updating the color and go back to click on the canvas, a shape is printed with the previously selected color and THEN the next shape printed is the appropriately updated color.
Here is a look at the code:
public class WholePanel extends JPanel
{
private Color currentColor;
private int size = 10;
private Shape shape;
private String SHAPE = "Circle";
private String SIZE, CURRENTCOLOR;
private CanvasPanel canvas;
private JPanel topPanel, topSplitPanel;
private JButton undo;
private ArrayList <Shape>shapeList;
private JComboBox shapeCombo, sizeCombo, colorCombo;
public WholePanel()
{
//default color to draw is black
shapeList = new ArrayList();
// label for displaying what to input
Label label1 = new Label("Choose Circle or Square, its size, and its color.");
// new button to undo last task
undo = new JButton ("Undo");
// combo box for selecting shape
String[] circleSquare = {"Circle", "Square"};
shapeCombo = new JComboBox(circleSquare);
//combo box for selecting size
String[] sizezzz = {"10","20","30","40","50"};
sizeCombo = new JComboBox(sizezzz);
//combo box for selecting color
String[] colores = {"black","red","blue","green","orange"};
colorCombo = new JComboBox(colores);
// panel for displaying the three combo boxes and the undo button
topPanel = new JPanel(new FlowLayout());
topPanel.add(shapeCombo);
topPanel.add(sizeCombo);
topPanel.add(colorCombo);
topPanel.add(undo);
// new panel with grid layout for displaying label above panel including combo boxes
topSplitPanel = new JPanel(new GridLayout(2,1));
topSplitPanel.add(label1);
topSplitPanel.add(topPanel);
// creates new object of CanvasPanel
canvas = new CanvasPanel();
// add ActionListeners to the undo button and each of JComboBox
undo.addActionListener (new ButtonListener());
shapeCombo.addActionListener (new ComboListener());
sizeCombo.addActionListener (new ComboListener());
colorCombo.addActionListener (new ComboListener());
//adds mouse listener to the canvas
MouseListener pointListener = new PointListener();
canvas.addMouseListener(pointListener);
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topSplitPanel, canvas);
setLayout(new BorderLayout());
add(sp);
}
//CanvasPanel is the panel where shapes will be drawn
private class CanvasPanel extends JPanel
{
//this method draws all shapes
public void paintComponent(Graphics page)
{
super.paintComponent(page);
setBackground(Color.WHITE);
/*for(int i=0; i<shapeList.size(); i++)
{
shape = shapeList.get(i);
shape.draw(page);
}*/
for (Shape shapee : shapeList)
{
shapee.draw(page);
}
}
} //end of CanvasPanel class
//ButtonListener defined actions to take in case
//"Undo" is chosen.
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
shapeList.remove(shapeList.size()-1);
}
} // end of ButtonListener
// listener class to set the color chosen by a user using
// color combo box, set the size chosen using size combo box
// or set the shape (circle or square) using shape combo box
private class ComboListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==shapeCombo)
{
SHAPE = (String) shapeCombo.getSelectedItem();
}
if(event.getSource()==sizeCombo)
{
SIZE = (String) sizeCombo.getSelectedItem();
if (SIZE.equals("10")){ size =10;}
if (SIZE.equals("20")){ size =20;}
if (SIZE.equals("30")){ size =30;}
if (SIZE.equals("40")){ size =40;}
if (SIZE.equals("50")){ size =50;}
}
if(event.getSource()==colorCombo)
{
CURRENTCOLOR = (String) colorCombo.getSelectedItem();
if(CURRENTCOLOR.equals("black")){currentColor = Color.black;}
if(CURRENTCOLOR.equals("red")){currentColor = Color.red;}
if(CURRENTCOLOR.equals("blue")){currentColor = Color.blue;}
if(CURRENTCOLOR.equals("green")){currentColor = Color.green;}
if(CURRENTCOLOR.equals("orange")){currentColor = Color.orange;}
}
}
} // end of ComboListener
// listener class that listens to the mouse
public class PointListener implements MouseListener
{
//in case that a user presses using a mouse,
//record the point where it was pressed.
public void mousePressed (MouseEvent event)
{
int X = event.getX();
int Y = event.getY();
if (SHAPE.equals("Square"))
{
shapeList.add(new Square(X-(size/2),Y-(size/2),size,currentColor));
}
if (SHAPE.equals("Circle"))
{
shapeList.add(new Circle(X-(size/2),Y-(size/2),size,currentColor));
}
}
public void mouseReleased (MouseEvent event) {}
public void mouseClicked (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
} // end of PointListener
} // end of Whole Panel Class
I am dragging a JLabel around the screen, and when I release above the JPanel it is supposed to snap to where it completely covers the JPanel. Also, if I release anywhere else it is supposed to snap to its original position. I have the snap part, but I don't know how to tell if it is over the JPanel. I have my code below.
import java.awt.Color;
java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.event.MouseEvent;
public class Main {
public static final int CARD_HEIGHT = 97;
public static final int CARD_WIDTH = 73;
/**
* Mouse Handler components
* Changes the location of the JLabel with the mouse
*/
public static MouseInputAdapter mouseHandler = new MouseInputAdapter(){
public int labelDisX;
public int labelDisY;
public void mousePressed(MouseEvent e) {
labelDisX = e.getX();
labelDisY = e.getY();
//move the card above all others
e.getComponent().getParent().setComponentZOrder(e.getComponent(), 0);
e.getComponent().getParent().repaint();
}
public void mouseReleased(MouseEvent e) {
//if not above panel, then move to original spot
if(!abovePanel()) {
e.getComponent().setLocation(labelDisX, labelDisY);
}
}
public void mouseDragged (MouseEvent e) {
JPanel panel = (JPanel) e.getComponent().getParent();
//get preliminary new X coordinate
int newX = e.getComponent().getX() + e.getX() - labelDisX;
//get preliminary new Y coordinate
int newY = e.getComponent().getY() + e.getY() - labelDisY;
//Not moved off edges of JFrame
if(newX > panel.getWidth() - CARD_WIDTH) {
newX = panel.getWidth() - CARD_WIDTH;
}
if(newY > panel.getHeight() - CARD_HEIGHT) {
newY = panel.getHeight() - CARD_HEIGHT;
}
if(newX < 0) { newX = 0; }
if(newY < 0) { newY = 0; }
e.getComponent().setLocation(newX, newY);
}
};
/**
* check to see if the JLabel is above the JPanel
* #return
*/
public static boolean abovePanel() {
return false;
}
/**
* Adds ability to drag to JLabel
* #param label
*/
public static void addDrag( JLabel label) {
System.out.println("Adding drag");
label.addMouseMotionListener(mouseHandler);
label.addMouseListener(mouseHandler);
}
public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("Example Frame");
// JPanel to add JLabels to
JPanel panel = new JPanel();
// Add a drop target text area in the center of the frame
DropTargetArea dropPanel = new DropTargetArea();
dropPanel.setPreferredSize(new Dimension(CARD_WIDTH, CARD_HEIGHT));
dropPanel.setBackground(Color.gray);
panel.add(dropPanel);
// Add several draggable labels to the container
JLabel blue = new JLabel();
blue.setOpaque(true);
blue.setPreferredSize(new Dimension(CARD_WIDTH, CARD_HEIGHT));
blue.setBackground(Color.blue);
addDrag(blue);
panel.add(blue);
// Add the container to the frame
frame.add(panel);
// Display the frame
frame.setPreferredSize(new Dimension(400,400));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
I've done this using a JLayeredPane that holds a JPanel that itself holds a grid of JPanels using BorderLayout, with each smaller JPanel representing a chess square, and each smaller JPanel can accept a single JLabel. I added the MouseAdapter to the JLayeredPane itself, and when clicked, it checks to see if a moveable JLabel is located below the click. If so, the JLabel is raised up to the JLayeredPane's DRAG_LAYER, and then when released, check which JPanel the mouse cursor is over, and drop the JLabel if it is a valid square, otherwise return it to its original position. You can see my code here.
So I am working on a GUI project for my class and I am a bit stuck. My problem has to do with my GUI aspect so I guess you could ignore the other methods having to do with the sorting. As of now, my main concern is just getting the GUI working. However, I keep running into an error, a null pointer exception to be exact:
Java.lang.NullPointerException
at SortDriver$SortCanvas.paint(SortDriver.java:253)
at SortDriver.init(SortDriver.java:197)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:679)
After reading though my code, I think I narrowed it down to the my SortCanvas class. I never used it before but it was part of the stub my professor gave to us. That is to say that it works correctly and displays the image correctly but it looks like my implementation is incorrect however. Could someone help me figure out how to implement my SortCanvas "picture" correctly please? I read over the Java Docs for Canvas and I still don't understand what I am doing wrong. Here is my code:
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
import java.awt.event.*;
public class SortDriver extends Applet {
private int array[]; // array to be sorted
private int limit = 1000; // size of array to be sorted - you may have to make
// this bigger for faster sorts
private int largestNum; // need to know for color scaling purposes in paint()
// flag to tell paint() whether to paint a single location or the whole array
private enum PaintType {ALL, SINGLE};
private PaintType doPaint = PaintType.ALL;
private int index = -1; // index of single array location to be painted
//this listener object responds to button events
private ButtonActionListener buttonListener;
//button to start the sort
private JButton sortButton;
//basic window frame
private JFrame mainFrame;
//layouts
private BorderLayout initialLayout;
private FlowLayout northLayout;
private BorderLayout centerLayout;
private BorderLayout southLayout;
//basic panel for window frame
private JPanel initialPanel;
//panels for window layout
private JPanel northPanel;
private JPanel centerPanel;
private JPanel southPanel;
//panels for radio buttons
private JPanel radioOrderPanel;
private JPanel radioSortPanel;
private JPanel radioColorPanel;
//north panel header labels
private JLabel topTitleLabel;
private JLabel bottomTitleLabel;
private JLabel arraySizeLabel;
//radio buttons for list order (radioOrderButton)
//random set, ordered set, reverse set
private JRadioButton rOB1, rOB2, rOB3;
//radio buttons for sort type (radioSortButton)
//bubblesort, insertionsort, mergesort, quicksort
private JRadioButton rSB1, rSB2, rSB3, rSB4;
//radio buttons for color choice (radioColorButton)
//green, red, white, blue
private JRadioButton rCB1, rCB2, rCB3, rCB4;
//radio button groups for each radio panel
private ButtonGroup orderGroup, sortGroup, colorGroup;
//text field for size of the array
private JTextField arraySizeTextField;
// the picture of the sort will appear on this canvas
private SortCanvas picture;
private final int pictureWidth = 500; // size of the sort bar 1001
private final int pictureHeight = 50;
public void init() {
buttonListener = new ButtonActionListener();
array = new int[limit];
// load the array
largestNum = array[0] = (int) (Math.random()*1000000.0);
for (int i=1; i<limit; i++) {
array[i] = (int) (Math.random()*1000000.0);
// also keep track of the largest so that we can scale by it in paint()
if (array[i] > largestNum) largestNum = array[i];
}
//set up the main frame
mainFrame = new JFrame();
initialPanel = (JPanel) mainFrame.getContentPane();
initialLayout = new BorderLayout();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(650, 750);
initialPanel.setLayout(initialLayout);
//set up north panel
northPanel = new JPanel();
northLayout = new FlowLayout();
topTitleLabel = new JLabel("SortIt!");
bottomTitleLabel = new JLabel("A program by Mike Sevilla");
northPanel.setLayout(northLayout);
northPanel.add(topTitleLabel, BorderLayout.NORTH);
northPanel.add(bottomTitleLabel, BorderLayout.NORTH);
initialPanel.add(northPanel, BorderLayout.NORTH);
//set up center panel
centerPanel = new JPanel();
centerLayout = new BorderLayout();
centerPanel.setLayout(centerLayout);
//place array size label
arraySizeLabel = new JLabel("Size:");
//place array size text field w/ space for 5 chars
arraySizeTextField = new JTextField("", 5);
//place sort button
sortButton = new JButton("Sort it!");
// the listener is triggered when the button is clicked
sortButton.addActionListener(buttonListener);
centerPanel.setLayout(centerLayout);
//place sort bar on top of center layout
picture = new SortCanvas();
centerPanel.add(picture, BorderLayout.CENTER);
centerPanel.add(arraySizeLabel, BorderLayout.CENTER);
centerPanel.add(arraySizeTextField, BorderLayout.CENTER);
centerPanel.add(sortButton, BorderLayout.CENTER);
initialPanel.add(centerPanel, BorderLayout.CENTER);
//set up south panel
southPanel = new JPanel();
southLayout = new BorderLayout();
southPanel.setLayout(southLayout);
//set radio buttons and format layouts
radioOrderPanel = new JPanel();
radioOrderPanel.setLayout(new BoxLayout(radioOrderPanel, BoxLayout.Y_AXIS));
radioSortPanel = new JPanel();
radioSortPanel.setLayout(new BoxLayout(radioSortPanel, BoxLayout.Y_AXIS));
radioColorPanel = new JPanel();
radioColorPanel.setLayout(new BoxLayout(radioColorPanel, BoxLayout.Y_AXIS));
//define radio buttons
rOB1 = new JRadioButton("Random Order", true);
rOB1.addActionListener(buttonListener);
radioOrderPanel.add(rOB1);
rOB2 = new JRadioButton("In Order", false);
rOB2.addActionListener(buttonListener);
radioOrderPanel.add(rOB2);
rOB3 = new JRadioButton("In Reverse", false);
rOB3.addActionListener(buttonListener);
radioOrderPanel.add(rOB3);
rSB1 = new JRadioButton("Bubble Sort", true);
rSB1.addActionListener(buttonListener);
radioSortPanel.add(rSB1);
rSB2 = new JRadioButton("Insertion Sort", false);
rSB2.addActionListener(buttonListener);
radioSortPanel.add(rSB2);
rSB3 = new JRadioButton("Merge Sort", false);
rSB3.addActionListener(buttonListener);
radioSortPanel.add(rSB3);
rSB4 = new JRadioButton("Quick Sort", false);
rSB4.addActionListener(buttonListener);
radioSortPanel.add(rSB4);
rCB1 = new JRadioButton("Green", true);
rCB1.addActionListener(buttonListener);
radioColorPanel.add(rCB1);
rCB2 = new JRadioButton("Red", false);
rCB2.addActionListener(buttonListener);
radioColorPanel.add(rCB2);
rCB3 = new JRadioButton("White", false);
rCB3.addActionListener(buttonListener);
radioColorPanel.add(rCB3);
rCB4 = new JRadioButton("Blue", false);
rCB4.addActionListener(buttonListener);
radioColorPanel.add(rCB4);
//add radio buttons to a button group
orderGroup = new ButtonGroup();
orderGroup.add(rOB1);
orderGroup.add(rOB2);
orderGroup.add(rOB3);
sortGroup = new ButtonGroup();
sortGroup.add(rSB1);
sortGroup.add(rSB2);
sortGroup.add(rSB3);
sortGroup.add(rSB4);
colorGroup = new ButtonGroup();
colorGroup.add(rCB1);
colorGroup.add(rCB2);
colorGroup.add(rCB3);
colorGroup.add(rCB4);
initialPanel.add(southPanel, BorderLayout.NORTH);
picture.paint(picture.getGraphics());
mainFrame.setVisible(true);
}
// this object is triggered whenever a button is clicked
private class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// find out which button was clicked
Object source = event.getSource();
// start sort button was clicked
if (source == sortButton) {
// call the sort
doBubblesort();
}
// called when user hits return in text field
if (source == arraySizeTextField) {
int size = Integer.parseInt(arraySizeTextField.getText());
}
}
}
private void doBubblesort() {
int temp;
// this is just bubblesort
for (int i=0; i<limit-1; i++) {
for (int j=0; j<limit-1-i; j++) {
if (array[j]>array[j+1]) {
temp = array[j]; array[j] = array[j+1]; array[j+1] = temp;
// redraw only locations j and j+1
doPaint = PaintType.SINGLE; // try changing this to ALL and see what happens
index = j;
picture.paint(picture.getGraphics());
index = j+1;
picture.paint(picture.getGraphics());
}
}
}
}
class SortCanvas extends Canvas {
// this class paints the sort bar
SortCanvas() {
setSize(pictureWidth, pictureHeight);
setBackground(Color.white);
}
public void paint(Graphics g) {
if (doPaint == PaintType.ALL) {
// paint whole array - this takes time so it shouldn't be done too frequently
setBackground(Color.white);
g.setColor(Color.white);
g.fillRect(0, 0, pictureWidth, pictureHeight);
for (int i=0; i<limit; i++) {
// the larger the number, the brighter green it is
// green is between 0.0 and 1.0
// divide by the largest number to get a value between 0 and 1
float green = (float)(array[i]/(float)largestNum);
// clamp if necessary - it shouldn't be
if (green<0f) green = 0f;
if (green>1f) green = 1f;
g.setColor(new Color(0.0f, green, 0.0f));
// array location 0 is painted at left;
// array location limit-1 is painted to right
//this is a single vertical line in the bar
g.drawLine((int)(i*pictureWidth/limit), 0,
(int)(i*pictureWidth/limit), pictureHeight);
}
}
else {
// just paint one location on the bar
float green = (float)(array[index]/(float)largestNum);
if (green<0f) green = 0f;
if (green>1f) green = 1f;
g.setColor(new Color(0.0f, green, 0.0f));
g.drawLine((int)(index*pictureWidth/limit), 0,
(int)(index*pictureWidth/limit), pictureHeight);
}
}
}
}
This is not required;
picture.paint(picture.getGraphics());
getGraphics will return null if the component has not yet being painted itself. You should avoid using this method, it is simply a snap shot of the current components graphical state (which in your case is nothing)
You don't control the paint process, that's down to the repaint manager. You can request updates via the repaint methods. Have a read through Painting in AWT and Swing
You should avoid mixing heavy weight (Canvas) & light weight components (JFrame) together, where possible, you should stick with Swing components
Calling paint() directly can lead to unexpected behavior as you are see from this, use repaint() instead:
picture.repaint();
Hi I am new to java and I thought I'd try produce a game where the user actually tries solving the 8 queens problem themselves. However, It increases in difficulty starting 8 rooks, up to 14 bishops then 8 queens.
I have created the chessboard successfully. I have a problem with my mouselistener... each square on the board is a button and when clicked my intention is that that square will change colour to indicate its been clicked, then all squares that cant be clicked on again will also change to indicate squares out of the game.
When the square is clicked it doesn't seem to perform any action.
Sorry, I know its trivial.
Thanks.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class rooks extends JFrame implements MouseListener{
private final int BOARD_SIZE = 8;
private final int BOARD_SIZE_COLS = 8;
private final int BOARD_SIZE_ROWS = 8;
// private JTextField bottom = new JTextField("") ");
// private JLabel bannerl = new JLabel("The game");
// private JButton queens = new JButton(" Play Queens ");
private JButton rooks = new JButton(" Play Rooks ");
// private JButton bishops = new JButton(" Play Knights ");
private JButton[][] cboard = new JButton[BOARD_SIZE][BOARD_SIZE];
private JTextArea bottomtextarea = new JTextArea();
// constructor creating the chessboard
public rooks(){
this.setSize(500, 500);
this.setTitle("rooks");
// this.setIconImage();
// create JPanels and add JComponents
JPanel main = new JPanel(new BorderLayout());
this.setContentPane(main);
JPanel north = new JPanel();
north.setLayout(new GridLayout(1,3));
main.add(north, BorderLayout.NORTH);
// north.add(queens);
north.add(rooks);
// north.add(bishops);
JPanel south = new JPanel();
main.add(south, BorderLayout.SOUTH);
south.add(bottomtextarea);
bottomtextarea.setEditable(false);
bottomtextarea.setVisible(true);
// create grid (actual chessboard) and initialise each button with no char
JPanel chessBoard = new JPanel(new GridLayout(BOARD_SIZE, BOARD_SIZE));
main.add(chessBoard, BorderLayout.CENTER);
for (int i=0; i<BOARD_SIZE_ROWS; i++){
for(int j=0; j<BOARD_SIZE_COLS; j++){
cboard[i][j] = new JButton("");
chessBoard.add(cboard[i][j]);
// as it loops add colour to the board, if (i+j=even then white, otherwise black)
if ((i + j) % 2 == 0) {
cboard[i][j].setBackground(Color.black);
}
else {
cboard[i][j].setBackground(Color.white);
}
}
}
cboard[7][7].addMouseListener(this);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
System.out.print("it has been clicked");
}
void saySomething(String eventDescription, MouseEvent e) {
}
}
Your code is working. I run it and when i click on the 7-7 square, (which is the one in the bottom right corner) i get the message: "it has been clicked".
Since you have added the mouse listener to only this square the code is behaving as expected.
But there are some things you should refactor:
Why do you define BOARD_SIZE, BOARD_SIZE_COLS, BOARD_SIZE_ROWS? If you only use quadratic game boards you only need BOARD_SIZE and if not then you dont need BOARD_SIZE.
Its convention to write the first letter of your classes in upper case. So it is Rooks instead of rooks
You need to add your listener to every square of the board instead of to only one
This should be enough to start with.
You are adding a MouseListener to the last button only, the JButton at cboard[7][7].
Why use a MouseListener and not an ActionListener for JButtons? This makes no sense.
Why not add an ActionListener to all JButtons inside of the for loop?