I am struggling with the below assignment:
assignment q:
using methods from the string class, write a program that will count the number of words which are separated by blanks in a string. For simplicity, use strings without punctuation or other white space characters(tabs, newlines etc). Use a JTextArea to allow the user to enter the text and allow the text area to scroll if necessary. when the user clicks a button to count the words , the total number of words counted is displayed in a textbox that cannot be modified by the user.
now my problem is that i am not getting the counted number to display in the un-editable textbox.
i also have the problem where the cusrsor is showing in the middle of the input screen instead of at the top.
please can you point me in the right direction.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.*;
public class WordCounter extends JFrame implements ActionListener
{
//Construct a panel for the fields and buttons
JPanel fieldPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Construct labels and text boxes
JTextField screen = new JTextField(1);
JLabel wordCount = new JLabel(" Word Count = ");
JTextField words = new JTextField(3);
//Construct button
JButton countButton = new JButton("Count Words");
public static void main(String[] args)
{
WordCounter f = new WordCounter();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,200);
f.setTitle("Word Counter");
f.setResizable(false);
f.setLocation(200,200);
f.setVisible(true);
}
public static int getWordCount(String screen)
{
int count = 0;
for (int i = 0; i < screen.length(); i++)
{
if (screen.charAt(i) == ' ')
{
count++;
}
}
return count;
}
public WordCounter()
{
Container c = getContentPane();
c.setLayout((new BorderLayout()));
fieldPanel.setLayout(new GridLayout(1,1));
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//add rows to panels
fieldPanel.add(screen);
//add button to panel
buttonPanel.add(countButton);
buttonPanel.add(wordCount);
buttonPanel.add(words);
//add panels to frame
c.add(fieldPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
//add functionality to button
countButton.addActionListener(this);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
int answer = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit?", "File Submission",JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION)
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{
}
}
To display the word count, you must modify your actionPerformed method like so:
public void actionPerformed(ActionEvent e)
{
words.setText(String.valueOf(getWordCount(screen.getText())));
}
And also your method for counting words produces incorrect result if the entered text doesn't end with a space. You could modify your getWordCount method for example like this to get correct word count:
public static int getWordCount(String screen)
{
String[] words = screen.split("\\s+");
return words.length;
}
And for your second problem: your cursor displays in the center because JTextField is a single line input. Use JTextArea instead. It is after all specified in your question that you should use it:
JTextArea screen = new JTextArea();
try it:
public static int getWordCount(String screen)
{
int count = 0;
string[] words = screen.split(' ');
count = words.Length;
return count;
}
Related
I am trying to generate a GUI using swing that creates a frame with 100 buttons and every button has a "label" on it from on 1 to a 100.
What I have tried:
import javax.swing.*;
import java.awt.*;
public class ButtonScreen extends JFrame{
JFrame frame = new JFrame();
int rows=10;
int cols=10;
JButton[][] button = new JButton[rows][cols];
JTextArea screen = new JTextArea();
JPanel bpanel = new JPanel();
public static void main(String[] args) {
ButtonScreen bs = new ButtonScreen();
bs.setVisible(true);
}// end of main
public ButtonScreen(){
super("Welcome to the ButtonScreen Program!");
setDefaultCloseOperation(EXIT_ON_CLOSE);
bpanel.setLayout(new GridLayout(rows,cols));
for(int i=0;i<button.length;i++){
for(int j=0;j<button.length;j++){
button[i][j]=new JButton(""+i+j);
bpanel.add(button[i][j]);
}
}
add(bpanel);
}//end of constructor
}//end of class
This works just fine, but it creates buttons with "labels" (meaning string parameters at line 26) and also these labels, are not one string or one integer but it is a dillusion of the of i right next to j counter. So my second attempt, after some corrections, was:
import java.awt.*;
import javax.swing.*;
public class LabArr extends JFrame{
JFrame frame = new JFrame();
int rows=10;
int cols= 10;
int i=0;
JButton[][] button = new JButton[rows][cols];
JLabel[] label = new JLabel[100];
public static void main(String[] args) {
LabArr la = new LabArr();
la.setVisible(true);
}//end of main
public LabArr(){
super("title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(rows,cols));
for(i=0;i<label.length;i++){
label[i]= new JLabel(toString(i));
}
for(int i=0;i<button.length;i++){
for(int j=0;j<button.length;j++){
button[i][j]= new JButton(""+label[j]);
add(button[i][j]);
}
}
}//end of constructor
public String toString(int k){
k=i;
String s;
s=""+k;
return s;
}
}//end of class
My goal using that was to create an array of JLabel objects and then match every JLabel element to one from the JButton array.
So, first of all I would like to know to which object the methods setLayout and setDefaultCloseOperation refer to.
Second, "Does the toString method need to refer to an object at the line I am using it?". And finally, what am I missing?
This will create a single frame with buttons from 1 to 100.
import javax.swing.*;
import java.awt.GridLayout;
public class HundredButtonGrid{
public static void main(String[] args){
JFrame frame = new JFrame("100 buttons");
frame.setLayout(new GridLayout(10, 10));
for(int i = 0; i<100; i++){
frame.add( new JButton( "" + (i + 1) ) );
}
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I've addressed a few things.
I just use 1 index because the GridLayout takes care of the x/y values.
I used parenthesis to add the index to 1 so that it doesn't end up concatenating them by string.
I've set the default close operation to exit, you can have it do other things too. Like JFrame.DISPOSE_ON_CLOSE so the window will go away, but not terminate the application.
I didn't extend JFrame, I created a separate instance. In your case you have extended JFrame, so when you call setLayout it is being called on the instance you're creating. An alternative way to say it is this.setLayout same with setDefaultCloseOperation.
Hope this will help you with your problem, kindly see the code below:
public class LabArr extends JFrame{
JFrame frame = new JFrame();
int rows=10;
int cols= 10;
int counter = 0;
JButton[][] button = new JButton[rows][cols];
JLabel[] label = new JLabel[rows*cols];
public static void main(String[] args) {
DemoApplication la = new DemoApplication();
la.setVisible(true);
}//end of main
public LabArr(){
super("title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(rows,cols));
for(int i=0;i<label.length;i++){
label[i]= new JLabel(toString(i));
}
for(int i=0;i<button.length;i++){
for(int j=0;j<button.length;j++){
button[i][j]= new JButton(counter + "");
add(button[i][j]);
counter++;
}
}
}//end of constructor
public String toString(int k){
String s;
s=""+k;
return s;
}
}
You've been creating the buttons with the label toString() method name.
I don't have a lot of experience with KeyListeners but I used one in my application and it works fine except I need to wait for input before my program can continue. For this I made a while loop that loops until the String temp is not null (which would mean there would be input).
The problem is there is no way to type in the JTextField (called input). Below is code from my two methods that are supposed to work together so that the text in my JTextField (input) can be returned (as temp). I'm not sure why this doesn't work or how to fix it.
The keyPressed method for my KeyListener:
public void keyPressed(KeyEvent e)
{
//only sends text if the enter key is pressed
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
//if there really is text
if (!input.getText().equals(""))
{
//String temp is changed from null to input
temp=input.getText();
//text sent to another JTextField
output.append(temp+"\n");
//input no longer has text
input.setText("");
}
}
}
The method thats trying to get text, also in my KeyListener class
public String getTemp()
{
booleans isNull=temp==null;
//loops until temp is not null
while (isNull)
{
//unnecessary line of code, only used so the loop not empty
isNull=checkTemp();
}
return temp;
}
public boolean checkTemp()
{
return temp==null;
}
Your while loop is a common console program construct, but understand that you're not creating a console program here but rather an event-driven GUI, and in this situation, the while loop fights against the Swing GUI library, and you need to get rid of it. Instead of a while loop with continual polling you now want to respond to events, and if you're listening for user input into a JTextField do not use a KeyListener as this low-level listener can cause unwanted side effects. Instead add a DocumentListener to the JTextField's Document.
Edit: You're listening for the enter key, and so the solution is even easier: add an ActionListener to the JTextField!
e.g.,
input.addActionListener(e -> {
String text = input.getText().trim();
if (text.isEmpty()) {
return;
}
output.append(text + "\n");
input.setText("");
});
More complete example:
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ChatBox extends JPanel {
private static final int COLS = 40;
private JTextField input = new JTextField(COLS);
private JTextArea output = new JTextArea(20, COLS);
private JButton submitButton = new JButton("Submit");
public ChatBox() {
output.setFocusable(false); // user can't get into output
JScrollPane scrollPane = new JScrollPane(output);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
ActionListener inputListener = e -> {
String text = input.getText().trim();
if (text.isEmpty()) {
return;
}
output.append(text + "\n");
input.setText("");
input.requestFocusInWindow();
};
input.addActionListener(inputListener);
submitButton.addActionListener(inputListener);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(input);
bottomPanel.add(submitButton);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
ChatBox mainPanel = new ChatBox();
JFrame frame = new JFrame("Chat Box");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
So I have a class project where I have to create a translator where a user can enter in text, in English, hit a button, and get the Pig Latin translation.I have to use Swing GUI, FlowLayout, and JTextArea, with a separate JTextArea for the translation. My program brings up the GUI, it allows me to type in something, but when I hit the button, nothing happens. I looked through and it looks like I remembered to add everything to the JFrame, but I can't figure out why nothing is popping up.
// This program will take text that is English and translate it to Pig Latin
//import all the necessary packages for the program
import java.util.Scanner;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class PigLatin extends JFrame implements ActionListener{
public static final int WIDTH = 500;
public static final int HEIGHT= 400;
private JButton button;
private JTextArea original;
private JTextArea translation;
private JLabel english;
private JLabel pig;
public static void main(String[]args)
{
PigLatin gui = new PigLatin();
gui.setVisible(true);
/*
Scanner scan = new Scanner("far");
Scanner scan1 = new Scanner("and");
Scanner scan2 = new Scanner("away");
while (scan.hasNext())
{
//prints out original words
System.out.println(scan.next());
System.out.println(scan1.next());
System.out.println(scan2.next());
}
*/
}
public PigLatin()
{ //titles the box, creates size and what to do when 'x' is clicked
super("Pig latin translator");
this.setSize(WIDTH,HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setVisible(true);
//creates frame for everything to be added to
JPanel frame = new JPanel();
//creates labels for text boxes
english = new JLabel("English");
add(english);
//enters in origninal text
original = new JTextArea("Enter text here");
original.setEditable(true);
original.setLineWrap(true);
//adds the text area to the GUI
frame.add(original);
//create text area for translation
translation = new JTextArea();
translation.setEditable(false);
translation.setLineWrap(true);
//adds the text area to the GUI
frame.add(translation);
//adds the frame to the GUI
add(frame);
frame.setVisible(true);
//creates panel for the button
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout());
//create translate button
button = new JButton("TRANSLATE TO PIG LATIN");
button.addActionListener(this);
buttons.add(button);
JButton clear = new JButton("Clear");
buttons.add(clear);
//adds the buttons JPanel to the GUI
add(buttons);
}
private int findWordEnd(String text) {
int indexOfSpace = text.indexOf(" ");
if (indexOfSpace == -1) // Happens if there is no space
return text.length();
else
return indexOfSpace;
}
private int findVowel(String vowel)
{
int i;
//looks for vowel
for(i=0; i<vowel.length();i++)
{
if(vowel.charAt(i)=='a'||vowel.charAt(i)=='e'||vowel.charAt(i)=='i'||vowel.charAt(i)=='o'||vowel.charAt(i)=='u')
return i;
}
//if no vowels
return vowel.length();
}
private String englishToPig(String text)
{
String translate = "";
while(!text.equals(""))
{
//finds the first word
int wordEndIndex = findWordEnd(text);
String word = text.substring(0, wordEndIndex);
//finds the start and end in Pig Latin
int vowelIndex = findVowel(word);
String start = word.substring(vowelIndex);
String end = "-"+word.substring(0, vowelIndex)+"ay";
//creates the translation
translate = translate+start+end;
//gets rid of first word, so translation can continue
text = text.substring(wordEndIndex).trim();
}
return translate;
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == "TRANSLATE TO PIG LATIN") {
// Get the English they entered
String text = original.getText();
text = text.trim();
text = text.toLowerCase();
// Display the translation
translation.setText(englishToPig(text));
}
}
}
The source of the click event is the button. What you're interested in is the action command instead.
if (e.getActionCommand().equals("TRANSLATE TO PIG LATIN")) {
Also note equals() instead of ==. However, it's usually needless to use the same action listener for everything and then figure out between the sources in the listener. You could as well use an anonymous class, when the source is guaranteed to be the one you're interested in:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get the English they entered
String text = original.getText();
text = text.trim();
text = text.toLowerCase();
// Display the translation
translation.setText(englishToPig(text));
}
});
The clear button can then similarly have its own, as their functionality is not really related.
so I am trying to make a small java program to count the number of characters in a given string.
Right now, my code works in the console output, but it is not updating the text field I have created in a JFrame and I am unsure why. Can someone please explain this to me?
BTW: I have set "onPress" to true, so the button doesn't really have an effect right now, I'm just trying to test the functionality of the program before I implement button functionality.
Thank you :)! Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class characterCounterTwov2 extends JFrame {
static boolean onPress = true;
public characterCounterTwov2(){
/*******************/
/* Local Variables */
/*******************/
//creates a new Jframe to put our frame objets in
JFrame frame = new JFrame();
//creates a text field frame object
JTextField txtField = new JTextField("Enter your text here", 25);
//stores the string of the the jtextfield into a variable text
String text = txtField.getText();
//creates a text field that is uneditable with the word "characters"
String charString = "Characters: ";
JTextField charField = new JTextField(charString, 25);
charField.setEditable(false);
//integer to count the characters
int charCounter = 0;
//string that will be used in a text field to display the # of chars
String charCount = Integer.toString(charCounter);
//Text field that displays charCount
JTextField charFieldTwo = new JTextField(charCount, 10);
//calculate button
JButton calcButton = new JButton("Calculate");
calcButton.addActionListener(new calcButtonFunc());
/*******************/
/* Frame Setup */
/*******************/
//sets the layout of the frame
frame.setLayout(new BorderLayout());
//add's elements to the frame
frame.add(txtField, BorderLayout.NORTH);
frame.add(charField, BorderLayout.CENTER);
frame.add(charFieldTwo, BorderLayout.SOUTH);
frame.add(calcButton, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
//begin while loop
//infinite while loop
System.out.println("Entering main while loop");
while(true)
{
while(onPress == true)
{
System.out.println("text length is:" + charCount);
for(int i = 0; i < text.length(); i++)
{
charCounter++;
System.out.println("Number of characters:" + charCounter);
}
//charCount = Integer.toString(charCounter);
onPress = false;
}
}
}
static class calcButtonFunc implements ActionListener
{
public void actionPerformed(java.awt.event.ActionEvent event)
{
onPress = true;
}
}
public static void main(String[] args){
new characterCounterTwov2();
System.out.println("End of program. Should not get here");
}
}
~~~~~~~~~
EDIT
I was given a lot of helpful tips by Hovercraft Full of Eels, and cleaned up my code. I am still having a problem with calculating the character count on button press, and having it reflect in the GUI. I am thinking my bug lies within the line "text = txtField.getText();" inside my button listener class.
Here is my updated code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class characterCounterTwov4{
//creates a new Jframe to put our frame objets in
JFrame frame = new JFrame();
//creates a text field frame object
JTextField txtField = new JTextField(25);
//stores the string of the the jtextfield into a variable text
String text = txtField.getText();
//creates a text field that is uneditable with the word "characters"
String charString = "Characters: ";
JTextField charField = new JTextField(charString, 25);
public characterCounterTwov4(){
charField.setEditable(false);
//integer to count the characters
int charCounter = 0;
//string that will be used in a text field to display the # of chars
String charCount = Integer.toString(text.length());
//Text field that displays charCount
JTextField charFieldTwo = new JTextField(charCount, 10);
//calculate button
JButton calcButton = new JButton("Calculate");
calcButton.addActionListener(new ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event)
{
System.out.println("button pressed");
//stores the string of the the jtextfield into a variable text
text = txtField.getText();
//string that will be used in a text field to display the # of chars
String charCount = Integer.toString(text.length());
//Text field that displays charCount
JTextField charFieldTwo = new JTextField(charCount, 10);
}
});
/*******************/
/* Frame Setup */
/*******************/
//sets the layout of the frame
frame.setLayout(new BorderLayout());
//add's elements to the frame
frame.add(txtField, BorderLayout.NORTH);
frame.add(charField, BorderLayout.CENTER);
frame.add(charFieldTwo, BorderLayout.SOUTH);
frame.add(calcButton, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
new characterCounterTwov4();
System.out.println("End of program. Should not get here");
}
}
Your code is not structured for correct Swing GUI event-driven programming but rather looks like a linear console program that is being shoe-horned into a GUI. Get rid of that while loop, get rid of that static boolean variable. Instead give your class a non-static (instance) int counter variable and a JTextField non-static variable and simply increment your counter in the actionPerformed method and display the results in the JTextField (or JLabel if you prefer).
So the actionPerformed could look something like:
public void actionPerformed(ActionEVent e) {
counter++; // increment the counter variable
charCount.setText("Count: " + counter); // display the results
}
and again, counter and charCount are non-static and are declared and initialized in the class, not inside of the constructor or any method.
Edit
Additional notes:
Why does your class extend JFrame when you don't use it as a JFrame?
In general, it's a good idea to start all Swing proggrams on the Swing Event Dispatch Thread or EDT. This can be done by passing a Runnable with your start-up code in it to the SwingUtilities static method invokeLater(...).
For example:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
// create and display your GUI from in here
MainGui mainGui = new MainGui();
JFrame mainFrame = new JFrame("Main GUI");
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.add(mainGui);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
Edit 2
Oops, I read your requirements wrong. You need to count the chars in a String, and so you will need another class instance JTextField, one to hold the user's String, get rid of the counter instance field since it no longer will be needed, and then in the actionPerformed method, simply get the String from the JTextField, get its length, and display the length in another JTextField or in a JLabel, again your choice.
Edit 3
Your code is now almost there!
Problems:
The charFieldTwo variable is a non-final local variable. To be able to use it in your anonymous inner class, either make it final, and note that doing this won't harm its ability to work since it is a reference variable, not a primite,
Or you could move its declaration out of the constructor, like you do the other variables.
Once you've done this, it is easy to call charFieldTwo.setText(charCount); on it at the bottom of your ActionListener, and you're pretty much done.
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?