First time user here, so please bear with me...I want to create a code that asks the user for the number of rows and columns they want to create multiplication table, but I honestly don't know where to go from here...Can someone help? I'd like for some specifics...such as...create a for loop here for this purpose...
sorry if my code is not formatted correctly...this is what i have so far..it correctly asks the user for a number of rows and columns and displays those rows and columns..I want to make it so once the user clicks a button at a certain intersection, the answer will be displayed.
For example: the first button when clicked will display "1*1=1"
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SquareGrid {
private int rowCount;
private int colCount;
public SquareGrid(int rowCount, int colCount){
this.rowCount=rowCount;
this.colCount= colCount;
}
JFrame theFrame;
JButton[][] buttons;
JPanel panel;
private void createAndShowGui(){
theFrame = new JFrame ("grid");
buttons = new JButton[rowCount][colCount];
panel = new JPanel();
panel.setLayout(new GridLayout(rowCount, colCount));
for(int rowCounter = 0; rowCounter < rowCount; rowCounter++)
for(int colCounter = 0; colCounter < colCount; colCounter++){
final JButton j = new JButton("not clicked");
j.setActionCommand((rowCount + 1) * (colCount + 1) + "");
j.addActionListener(new ActionListener(){
boolean clicked = false;
#Override
public void actionPerformed(ActionEvent event) {
if(clicked == false) clicked = true;
else clicked = false;
if (clicked) {
j.setText(j.getActionCommand());
}
}
});
String event;
buttons[rowCounter][colCounter] = j;
panel.add(j);
}
theFrame.add(panel);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.pack();
theFrame.setVisible(true);
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows");
int rowCount=input.nextInt();
Scanner input1=new Scanner(System.in);
System.out.println("Enter number of columns");
int colCount=input1.nextInt();
SquareGrid h = new SquareGrid(colCount,rowCount);
h.createAndShowGui();
}
}
I want to make it so once the user clicks a button at a certain intersection, the answer will be displayed.
For example: the first button when clicked will display "1*1=1"
You can set the actionCommand in your loop, with the multiplication already done from your loop count.
final JButton j = new JButton("not clicked");
j.setActionCommand((rowCounter + 1) * (colCounter + 1) + "");
Then just use that actionCommand
if (clicked) {
j.setText(j.getActionCommand());
UPDATE
Not sure what you changed, but try this
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SquareGrid {
private int rowCount;
private int colCount;
public SquareGrid(int rowCount, int colCount) {
this.rowCount = rowCount;
this.colCount = colCount;
}
JFrame theFrame;
JButton[][] buttons;
JPanel panel;
private void createAndShowGui() {
theFrame = new JFrame("grid");
buttons = new JButton[rowCount][colCount];
panel = new JPanel();
panel.setLayout(new GridLayout(rowCount, colCount));
for (int rowCounter = 0; rowCounter < rowCount; rowCounter++) {
for (int colCounter = 0; colCounter < colCount; colCounter++) {
final JButton j = new JButton("not clicked");
j.setActionCommand((rowCounter + 1) * (colCounter + 1) + "");
j.addActionListener(new ActionListener() {
boolean clicked = false;
#Override
public void actionPerformed(ActionEvent event) {
if(clicked == false) clicked = true;
else clicked = false;
if (clicked) {
j.setText(j.getActionCommand());
} else {
j.setText("not clicked");
}
}
});
buttons[rowCounter][colCounter] = j;
panel.add(j);
JButton buttonClicked = (j); //THIS WAS ADDED
}
}
theFrame.add(panel);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.pack();
theFrame.setVisible(true);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows");
int rowCount = input.nextInt();
Scanner input1 = new Scanner(System.in);
System.out.println("Enter number of columns");
int colCount = input1.nextInt();
SquareGrid h = new SquareGrid(colCount, rowCount);
h.createAndShowGui();
}
}
When a button is clicked, you can tell which button has been clicked by getting it from the event:
JButton buttonClicked = (JButton) event.getSource();
All you need to do now is to find the row and the column of this button inside your 2D array of buttons, and to compute the multiplication.
PS: you don't even have to use event.getSource() to get the button, since you already have the j variable referencing this button.
EDIT:the row and columns are available from the outside variables, which simply need to be made final:
for(int rowCounter = 0; rowCounter < rowCount; rowCounter++)
for(int colCounter = 0; colCounter < colCount; colCounter++){
final JButton j = new JButton("not clicked");
final int row = rowCounter;
final int col = colCounter;
// now you can use row and col inside your listener.
John Hurley's CS202 class ROFL -John Hurley's CS202 class ROFL
Related
The question field should contain 36 questions, the answer to these question are on the 36 buttons in the grid.
When the user selects the clicks the correct button answer the button is taken off the grid, the aim is to clear the grid so the grid is empty.
if the user clicks an incorrect button the game restarts.
i am having a problem with adding the question label.
the question field should display 36 question starting with what is 0 + 1 when the user clicks the correct button it then shows
question 2 shows in the field which is what is 1+1 and so till question 36
i have tried to get this by Changing this line of code
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
to this:
gui.statusLabel.setText("what is " + gui.buttonCounter + "+ 1");
but the games doesnt work properly although the correct answer is selected the code keeps saying doing the "else" in this code ie. Incorrect button clicked, start again: what is 0+ 1
if(clickedNumber == gui.buttonCounter){
gui.buttonCounter++;
buttonClicked.setText("");//optional - clears correct selection
if(gui.buttonCounter > gui.ROWS*gui.COLUMNS) gui.reset();
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
} else {
gui.reset();
gui.statusLabel.setText("Incorrect button clicked, start again: what is 0+ 1");
}
}
}
how do i fix this? so when i click the correct answer button it moves to the next question and does not display Incorrect button clicked, start again: what is 0+ 1.
full code
class NewClass {
final int ROWS = 6;
final int COLUMNS = 6;
JButton[] buttons = new JButton[ROWS * COLUMNS];
JLabel statusLabel = new JLabel("", JLabel.CENTER);
java.util.List<Integer> buttonNumbers = new ArrayList<Integer>();
int buttonCounter = 1;
public NewClass() {
JPanel buttonPanel = new JPanel(new GridLayout(ROWS, COLUMNS));
ButtonListener listener = new ButtonListener(NewClass.this);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x] = new JButton();
buttons[x].addActionListener(listener);
buttonPanel.add(buttons[x]);
buttonNumbers.add(new Integer(x + 1));
}
reset();
JFrame frame = new JFrame();
frame.getContentPane().add(statusLabel, BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void reset() {
Collections.shuffle(buttonNumbers);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x].setText(String.valueOf(buttonNumbers.get(x)));
}
buttonCounter = 1;
statusLabel.setText("Please click button " + buttonCounter);
}
public static void main(String[] args) {
new NewClass();
}
class ButtonListener implements ActionListener {
NewClass gui;
ButtonListener(NewClass g) {
gui = g;
}
public void actionPerformed(ActionEvent e) {
JButton buttonClicked = (JButton) e.getSource();
int clickedNumber = Integer.parseInt(buttonClicked.getText());
if (clickedNumber == gui.buttonCounter) {
gui.buttonCounter++;
buttonClicked.setText("");// optional - clears correct selection
if (gui.buttonCounter > gui.ROWS * gui.COLUMNS)
gui.reset();
// gui.statusLabel.setText("Please click button" +
// gui.buttonCounter);
gui.statusLabel.setText("what is " + buttonCounter);
} else {
gui.reset();
gui.statusLabel
.setText("Incorrect button clicked, start again: 0 + 1");
}
}
}
}
So, taking the code from your previous question and adding
System.out.println("ClickedNumber = " + clickedNumber);
System.out.println("gui.buttonCounter = " + gui.buttonCounter);
Into the actionPerformed method it asks...
"What is 0+1 1" (which should be "What is 0+1"). I click "1", which outputs...
ClickedNumber = 1
gui.buttonCounter = 1
So looking at the if statement;
if (clickedNumber == gui.buttonCounter) {
This is true...
Then it asks...
"What is 2+1". I click "3", which outputs...
ClickedNumber = 3
gui.buttonCounter = 2
So looking at the if statement;
if (clickedNumber == gui.buttonCounter) {
Which is false.
There is a logic error in your code. Basically, it's coming down to you not actually knowing what the question is...
Runnable example
Basically what this does is asks...
"What is " + buttonCounter + "+1"?
In the if condition, we assume the buttonCounter is 0 indexed, meaning we need to increase the comparison by 1
if (clickedNumber == (gui.buttonCounter + 1)) {
Or you could reduce the clickedNumeber by 1
if ((clickedNumber - 1) == gui.buttonCounter) {
Remember, you question is always asks "What's the next number", not what's the current number...
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class NewClass {
final int ROWS = 6;
final int COLUMNS = 6;
JButton[] buttons = new JButton[ROWS * COLUMNS];
JLabel statusLabel = new JLabel("", JLabel.CENTER);
java.util.List<Integer> buttonNumbers = new ArrayList<Integer>();
int buttonCounter = 1;
public NewClass() {
JPanel buttonPanel = new JPanel(new GridLayout(ROWS, COLUMNS));
ButtonListener listener = new ButtonListener(NewClass.this);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x] = new JButton();
buttons[x].addActionListener(listener);
buttonPanel.add(buttons[x]);
buttonNumbers.add(new Integer(x + 1));
}
reset();
JFrame frame = new JFrame();
frame.getContentPane().add(statusLabel, BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void reset() {
Collections.shuffle(buttonNumbers);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x].setText(String.valueOf(buttonNumbers.get(x)));
}
buttonCounter = 0;
statusLabel.setText("Please click button " + buttonCounter + "+1");
}
public static void main(String[] args) {
new NewClass();
}
class ButtonListener implements ActionListener {
NewClass gui;
ButtonListener(NewClass g) {
gui = g;
}
public void actionPerformed(ActionEvent e) {
JButton buttonClicked = (JButton) e.getSource();
int clickedNumber = Integer.parseInt(buttonClicked.getText());
System.out.println("ClickedNumber = " + clickedNumber);
System.out.println("gui.buttonCounter = " + gui.buttonCounter);
if (clickedNumber == (gui.buttonCounter + 1)) {
gui.buttonCounter++;
buttonClicked.setText("");// optional - clears correct selection
if (gui.buttonCounter > gui.ROWS * gui.COLUMNS) {
gui.reset();
}
// gui.statusLabel.setText("Please click button" +
// gui.buttonCounter);
gui.statusLabel.setText("what is " + buttonCounter + "+1");
} else {
gui.reset();
gui.statusLabel
.setText("Incorrect button clicked, start again: 0 + 1");
}
}
}
}
Updated with winner condition
if (clickedNumber == (gui.buttonCounter + 1)) {
if (gui.buttonCounter == (gui.ROWS * gui.COLUMNS) - 1) {
JOptionPane.showMessageDialog(null, "You Win", "Winner", JOptionPane.INFORMATION_MESSAGE);
} else {
gui.buttonCounter++;
buttonClicked.setText("");// optional - clears correct selection
if (gui.buttonCounter > gui.ROWS * gui.COLUMNS) {
gui.reset();
}
// gui.statusLabel.setText("Please click button" +
// gui.buttonCounter);
gui.statusLabel.setText("what is " + buttonCounter + "+1");
}
} else {
gui.reset();
gui.statusLabel
.setText("Incorrect button clicked, start again: 0 + 1");
}
i am creating a game based on a grid and a parser from english to java. i am having trouble making the command draw on a grid. right now im trying to simply write a letter onto the grid so i can see it and then later i will add graphics. basically, the game accepts commands in english, then parses them to java and should draw it to a grid. i have done most of the code, but its not working. im not too good with swing and GUI in java. below is the code for the parser which has been reduced, and the grid its self. i have some methods that should draw but they dont, im not sure why.
ServerPlayerParsing class:
public class ServerPlayerParsing {
ServerGridGenerator serverGrid = new ServerGridGenerator (10, 10);
public String validate(String command){
serverGrid.frameGen();
if (wordCount(command)== 3) {
String[] commandArray = command.split(" ");
commandParsing(commandArray);
} else {
System.out.println("Error! Format incorrect!");
System.out.println("Correct format = [COMMAND 1] [COMMAND 2] [COMMAND 3]");
}
return "";
}
public int wordCount(String command){
String[] commandCount = command.split("\\s");
return commandCount.length;
}
public String commandParsing(String[] commandArray) {
switch (commandArray[0]) {
case "move":
secondCommand (commandArray);
break;
default: System.out.println("Error in first command!");
}
return " ";
}
public String secondCommand (String commandArray[]) {
switch (commandArray[1]) {
case "forward":
forwardMovement(commandArray);
break;
case "backward":
backwardMovement (commandArray);
break;
case "left":
leftMovement (commandArray);
break;
case "right":
rightMovement (commandArray);
break;
default: System.out.println("Error in second command!");
}
return " ";
}
public String forwardMovement (String commandArray[]) {
switch (commandArray[2]) {
case "1":
serverGrid.serverPlayerMoveForward(1);
break;
case "2":
serverGrid.serverPlayerMoveForward(2);
break;
default: System.out.println("Error in third command!");
}
return " ";
}
public String backwardMovement (String commandArray[]) {
switch (commandArray[2]) {
case "1":
serverGrid.serverPlayerMoveBackward(1);
break;
case "2":
serverGrid.serverPlayerMoveBackward(2);
break;
default: System.out.println("Error in third command!");
}
return " ";
}
public String leftMovement (String commandArray[]) {
switch (commandArray[2]) {
case "1":
serverGrid.serverPlayerMoveLeft(1);
break;
case "2":
serverGrid.serverPlayerMoveLeft(2);
break;
default: System.out.println("Error in third command!");
}
return " ";
}
public String rightMovement (String commandArray[]) {
switch (commandArray[2]) {
case "1":
serverGrid.serverPlayerMoveRight(1);
break;
case "2":
serverGrid.serverPlayerMoveRight(2);
break;
default: System.out.println("Error in third command!");
}
return " ";
}
}
ServerGridGenerator:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ServerGridGenerator extends JFrame {
public int serverPlayerXPos = 0;
public int serverPlayerYPos = 0;
int row;
int column;
public void frameGen(){
row = 10;
column = 10;
int sizeGrid = 700;
ServerGridGenerator frame = new ServerGridGenerator(row, column);
frame.setPreferredSize(new Dimension(sizeGrid, sizeGrid));
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public ServerGridGenerator(int row, int column) {
JButton[][] squareButtons = new JButton [row][column];
Container pane = getContentPane();
pane.setLayout(new GridLayout(row, column));
for(int y=0; y<column; y++){
for (int x=0; x<row; x++) {
squareButtons[y][x] = new JButton("");
squareButtons[y][x].setOpaque(true);
squareButtons[y][x].setBackground(Color.white);
squareButtons[y][x].setEnabled(false);
pane.add(squareButtons[y][x]);
}
}
}
public void serverPlayerMoveRight (int moveBy){
JButton[][] squareButtons = new JButton [row][column];
for (int i=0; i<moveBy; i++) {
serverPlayerXPos = serverPlayerXPos + 1;
squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
}
}
public void serverPlayerMoveLeft (int moveBy){
JButton[][] squareButtons = new JButton [row][column];
for (int i=0; i<moveBy; i++) {
serverPlayerXPos = serverPlayerXPos - 1;
squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
}
}
public void serverPlayerMoveForward (int moveBy){
JButton[][] squareButtons = new JButton [row][column];
for (int i=0; i<moveBy; i++) {
serverPlayerYPos = serverPlayerYPos + 1;
squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
}
}
public void serverPlayerMoveBackward (int moveBy){
JButton[][] squareButtons = new JButton [row][column];
for (int i=0; i<moveBy; i++) {
serverPlayerYPos = serverPlayerYPos - 1;
squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
}
}
}
logically im pretty sure this works, but im not too familiar with java and if im allowed to modify text on the JButton after the program is running, either way could you please help me, it would be greatly appreciated!
Thanks
your frame and your code for the grid are seperate, it shouldnt be like that. create one method for the grid, and other for the left, right, forward and backward movements. therefore your constructor will be called and nothing else.
Your update event just has to call the setText method on whatever button you want the text on.
public void updateWhatever(String str, int buttonX, int buttonY){
squareButton[buttonX][buttonY].setText(str);
}
As for your code. You also probably need to fix your JButton 2D Array.
JButton[][] squareButtons = new JButton [width][height];
That array should probably be a global variable instead of a local. The Data is dumped every time your method finishes and none of the data is saved anywhere in memory. Also, when constructing an array of objects you need to you need to instantiate each object in the array to access any of the methods.
int height = 9;
int width = 9;
for(int i = 0; i <height; i++)
for(int j = 0; j < width; j++)
squareButtons[i][j] = new JButton();
// Grid size 10x10
Try that out let me know how it goes.
Update
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ServerGridGenerator extends JFrame {
public int serverPlayerXPos = 0;
public int serverPlayerYPos = 0;
int row = 10;
int column = 10;
int sizeGrid = 700;
JButton[][] squareButtons = new JButton [row][column];
public void frameGen(){
ServerGridGenerator frame = new ServerGridGenerator(row, column);
frame.setPreferredSize(new Dimension(sizeGrid, sizeGrid));
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public ServerGridGenerator(int r, int c) {
squareButtons = new JButton [r][c];
Container pane = getContentPane();
pane.setLayout(new GridLayout(r, c));
for(int y=0; y<c; y++){
for (int x=0; x<r; x++) {
squareButtons[y][x] = new JButton("");
squareButtons[y][x].setOpaque(true);
squareButtons[y][x].setBackground(Color.white);
squareButtons[y][x].setEnabled(false);
pane.add(squareButtons[y][x]);
}
}
}
public void serverPlayerMoveRight (int moveBy){
for (int i=0; i<moveBy; i++) {
serverPlayerXPos = serverPlayerXPos + 1;
squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
}
}
public void serverPlayerMoveLeft (int moveBy){
for (int i=0; i<moveBy; i++) {
serverPlayerXPos = serverPlayerXPos - 1;
squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
}
}
public void serverPlayerMoveForward (int moveBy){
for (int i=0; i<moveBy; i++) {
serverPlayerYPos = serverPlayerYPos + 1;
squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
}
}
public void serverPlayerMoveBackward (int moveBy){
for (int i=0; i<moveBy; i++) {
serverPlayerYPos = serverPlayerYPos - 1;
squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
}
}
}
Here's what that class should look like. I have a similar project where I made the battle ship board game.
I am trying to develop a GUI-based program to read the entries of a matrix from a text file. The first number is the number of rows; the second number is the number of columns. The remaining numbers are integers between 1 and 9 in row by row order. Scan the matrix, highlight (display the entries in different color) all cells that form a group of five cells with the same value horizontally, vertically or diagonally.
My program below is NOT reading the file correctly I don't think because every time I click Process in my menu I get in return a matrix of 0's. PLEASE HELP.
CLASS:
// GUI-related imports
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;
// File-related imports
import java.io.FileReader; // both needed
import java.io.BufferedReader; // for line input
import java.io.IOException;
public class FiveInARow
{
byte[][] tag = new byte[100][100];
int[][] matrix = new int[100][100];
int row;
int col;
String filePath, fileName;
// Constructor
public FiveInARow()
{
row = 0;
col = 0;
}
public void ReadFile()
{
// Initialize TAG(s) to 0
for(int i =0; i< tag.length; i++)
for(int j =0; i< tag.length; j++)
tag[i][j] = 0;
//Place open dialogue here
String filePath = null;
String fileName = null;
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
filePath = chooser.getSelectedFile().getPath();
fileName = chooser.getSelectedFile().getName();
}
// Define & Instantiate File
Scanner inputStream = new Scanner(filePath);
row = inputStream.nextInt();
col = inputStream.nextInt();
for(int i =0; i< row; i++) // rows
{
for(int j = 0; j < col; j++) //columns
{
matrix[i][j] = inputStream.nextInt();
}
}
} // End of ReadFile method
public void Process()
{
// Go through the matrix
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
// Checking the matrix horizantally
if(j <= col-5) // Checks the boundaries of horizantal elements
if (matrix[i][j] == matrix[i][j+1]
&&(matrix[i][j+1] == matrix[i][j+2])
&&(matrix[i][j+2] == matrix[i][j+3])
&&(matrix[i][j+3] == matrix[i][j+4]))
tag[i][j] = 1;
// Checking the matrix vertically
if(i <= row-5) // Checks the boundaries of vertical elements
if (matrix[i][j] == matrix[i+1][j]
&&(matrix[i+1][j] == matrix[i+2][j])
&&(matrix[i+2][j] == matrix[i+3][j])
&&(matrix[i+3][j] == matrix[i+4][j]))
tag[i][j] = 2;
// Checking the matrix's right diagnol CHANGEEEEE
if (matrix[i][j] == matrix[i+1][j]
&&(matrix[i+1][j] == matrix[i+2][j])
&&(matrix[i+2][j] == matrix[i+3][j])
&&(matrix[i+3][j] == matrix[i+4][j]))
tag[i][j] = 3;
// Checking the matrix's left diagnol CHANGEEE
if (matrix[i][j] == matrix[i+1][j]
&&(matrix[i+1][j] == matrix[i+2][j])
&&(matrix[i+2][j] == matrix[i+3][j])
&&(matrix[i+3][j] == matrix[i+4][j]))
tag[i][j] = 4;
}
}
} // End of Process method
}
DRIVER:
// GUI-related imports
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;
// File-related imports
import java.io.FileReader; // both needed
import java.io.IOException;
public class Project3Main extends Frame implements ActionListener
{
// File Parameters
FiveInARow f = new FiveInARow();
String dataFilePath = null;
String dataFileName = null;
int[][] Data = new int[100][100];
int[][] Tag = new int [100][100];
int row = 0;
int column = 0;
// Retrieved command code
String command = "";
public static void main(String[] args)
{
Frame frame = new Project3Main();
frame.setResizable(true);
frame.setSize(1000,700);
frame.setVisible(true);
}
public Project3Main()
{
setTitle("2D Arrays");
// Create Menu Bar
MenuBar mb = new MenuBar();
setMenuBar(mb);
// Create Menu Group Labeled "File"
Menu fileMenu = new Menu("File");
// Add it to Menu Bar
mb.add(fileMenu);
// Create Menu Items
// Add action Listener
// Add to "File" Menu Group
MenuItem miReadData = new MenuItem("Read Data");
miReadData.addActionListener(this);
fileMenu.add(miReadData);
MenuItem miProcess = new MenuItem("Process");
miProcess.addActionListener(this);
fileMenu.add(miProcess);
MenuItem miExit = new MenuItem("Exit");
miExit.addActionListener(this);
fileMenu.add(miExit);
// End program when window is closed
WindowListener l = new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
public void windowActivated(WindowEvent ev)
{
repaint();
}
public void windowStateChanged(WindowEvent ev)
{
repaint();
}
};
ComponentListener k = new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
repaint();
}
};
// register listeners
this.addWindowListener(l);
this.addComponentListener(k);
}
//******************************************************************************
// called by windows manager whenever the application window performs an action
// (select a menu item, close, resize, ....
//******************************************************************************
public void actionPerformed (ActionEvent ev)
{
// figure out which command was issued
command = ev.getActionCommand();
// take action accordingly
if("Read Data".equals(command))
{
///////////////////////////////////////////////////////////////// call readfile method in your class to do this
f.ReadFile();
dataFilePath = null;
dataFileName = null;
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
dataFilePath = chooser.getSelectedFile().getPath();
dataFileName = chooser.getSelectedFile().getName();
}
try
{
/*
* Scan the file and place it's contents into an array of Integers.
*/
Scanner inputStream = new Scanner(new FileReader(dataFilePath));
int intLine;
row = inputStream.nextInt();
column = inputStream.nextInt();
for (int i=0; i < row; i++)
{
for (int j = 0 ; j < column; j++)
{
intLine = inputStream.nextInt();
}
}
}
catch(IOException ioe)
{
System.exit(0);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
repaint();
}
else
if("Process".equals(command))
{
// call process method in your class
f.Process();
// determine if cells form a 5-cell same-valued block, mark them true in Tags array
repaint();
}
else
if("Exit".equals(command))
{
System.exit(0);
}
}
//********************************************************
// called by repaint() to redraw the screen
//********************************************************
public void paint(Graphics g)
{
int ww = (int)this.getWidth();
int wh = (int)this.getHeight() -40;
if("Read Data".equals(command))
{
// Acknowledge that file was opened
if (dataFileName != null)
{
g.drawString("File -- "+dataFileName+" -- was successfully opened", ww/2-150, wh/2);
}
else
{
g.drawString("NO File is Open", 400, 400);
}
return;
}
else
if("Process".equals(command))
{
// Display the results
int x = (ww-column*20)/2;
int y = (wh-row*20)/2;
for (int i=0; i<row; i++)
{
for (int j=0; j<column; j++)
{
g.setColor(Color.BLACK);
if (Tag[i][j] == 1)
g.setColor(Color.RED);
//******* set color for the other directions
g.drawString( ((Integer)Data[i][j]).toString(), x, y);
x=x+20;
}
x = (ww-column*20)/2;
y=y+20;
}
return;
}
}
}
The problem is this line:
Scanner inputStream = new Scanner(filePath);
filePath is a String. Scanner accepts a String in its constructor, but then it treats the String as the source. It'll never load the file.
You need to pass it an InputStream or a File or something else as you do in the Driver.
Your file chooser will give you a file you can use directly with your scanner:
File chosenFile = null;
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
chosenFile = chooser.getSelectedFile();
}
Scanner inputStream;
// Define & Instantiate File
if (chosenFile != null) {
inputStream = new Scanner(chosenFile);
}
else {
// handle appropriately
}
Change your use of the scanner to be like this:
Scanner inputStream = = new Scanner(new File("filename"));;
String line = scanner.nextLine();
String[] numbers = line.split(" ");
for(String str : numbers){
int nunber = Interger.parseInt(str);
}
This will read one line of the file at a time, split it on spaces (getting the numbers by themselves) then changing them from a string to a int. I think its getting strings and thus nextInt() has no values and picks up the default.
hi I am pretty new to java. I need to make a game name Ratsuk witch is pretty much like chess but it only has the knight. So when the knight no longer has space to move the player loses.
I did a array of buttons for this
import java.awt.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Tablero {
private JButton[][] mesa;
public Tablero() {
mesa = new JButton[8][8];
}
public void cuadriculado(JFrame ventana) {
JPanel panel = new JPanel(new GridLayout(8, 8, 4, 4));
for (int i = 0; i < mesa.length; i++) {
for (int j = 0; j < mesa[0].length; j++) {
mesa[i][j] = new JButton();
mesa[i][j].setPreferredSize(new Dimension(40, 40));
panel.add(mesa[i][j]);
}
}
for (int r = 0; r < mesa.length; r++) {
for (int t = 0; t < mesa[0].length; t++) {
if (r % 2 == 0 || r == 0) {
if (t % 2 == 0 || t == 0) {
mesa[r][t].setBackground(Color.BLACK);
} else {
mesa[r][t].setBackground(Color.WHITE);
}
} else {
if (t % 2 == 0 || t == 0) {
mesa[r][t].setBackground(Color.WHITE);
} else {
mesa[r][t].setBackground(Color.BLACK);
}
}
}
}
ventana.setContentPane(panel);
ventana.setSize(500, 500);
ventana.setVisible(true);
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0] = new JButton(image);
}
}
The file compiles but the image I am trying to set in the button mesa[0][0] does not appear. How can i fix this?
You should not create new JButton for mesa[0][0] again. But should set the icon for that existing JButton object.
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0].setIcon(image);
Try this:
try {
Icon image = ImageIO.read(getClass().getResource("redKnight.gif"));
mesa[0][0] = new JButton();
mesa[0][0].setIcon(new ImageIcon(image ));
} catch (IOException ex) {
}
You are creating new JButton object instead of adding the image to the existing JButton object, so the problem exists.
Setting mesa[0][0]=new JButton(image) will not make already added JButton object to the JFrame to be replaced. You should refresh the fundamentals of Java once.
Use JButton#setIcon(Icon img) method to add image to the already existing JButton object.
`mesa[0][0].setIcon(image);`
And also since, you are adding the image after setting the frame visible, you may have to refresh your frame by calling JFrame#repaint() or so...
Or change your code like this instead:
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0].setIcon(image);
ventana.setContentPane(panel);
ventana.setSize(500, 500);
ventana.setVisible(true);
I need to make the following exceptions: NoSuchRowException if the row is not between 1 and 3, IllegalSticksException if the number of sticks taken is not between 1 and 3, and NotEnoughSticksException if the number of sticks taken is between 1 and 3, but more than the number of sticks remaining in that row. My issue is I really don't understand the syntax. If someone could help me get started with one exception, I think I can figure the others out.
So far I have the main class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nimapp;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* #author jrsullins
*/
public class NimApp extends JFrame implements ActionListener {
private static final int ROWS = 3;
private JTextField[] gameFields; // Where sticks for each row shown
private JTextField rowField; // Where player enters row to select
private JTextField sticksField; // Where player enters sticks to take
private JButton playButton; // Pressed to take sticks
private JButton AIButton; // Pressed to make AI's move
private NimGame nim;
public NimApp() {
// Build the fields for the game play
rowField = new JTextField(5);
sticksField = new JTextField(5);
playButton = new JButton("PLAYER");
AIButton = new JButton("COMPUTER");
playButton.addActionListener(this);
AIButton.addActionListener(this);
AIButton.setEnabled(false);
// Create the layout
JPanel mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel);
JPanel sticksPanel = new JPanel(new GridLayout(3, 1));
mainPanel.add(sticksPanel, BorderLayout.EAST);
JPanel playPanel = new JPanel(new GridLayout(3, 2));
mainPanel.add(playPanel, BorderLayout.CENTER);
// Add the fields to the play panel
playPanel.add(new JLabel("Row: ", JLabel.RIGHT));
playPanel.add(rowField);
playPanel.add(new JLabel("Sticks: ", JLabel.RIGHT));
playPanel.add(sticksField);
playPanel.add(playButton);
playPanel.add(AIButton);
// Build the array of textfields to display the sticks
gameFields = new JTextField[ROWS];
for (int i = 0; i < ROWS; i++) {
gameFields[i] = new JTextField(10);
gameFields[i].setEditable(false);
sticksPanel.add(gameFields[i]);
}
setSize(350, 150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
nim = new NimGame(new int[]{3, 5, 7});
draw();
}
// Utility function to redraw game
private void draw() {
for (int row = 0; row < ROWS; row++) {
String sticks = "";
for (int j = 0; j < nim.getRow(row); j++) {
sticks += "| ";
}
gameFields[row].setText(sticks);
}
rowField.setText("");
sticksField.setText("");
}
public void actionPerformed(ActionEvent e) {
// Player move
if (e.getSource() == playButton) {
// Get the row and number of sticks to take
int row = Integer.parseInt(rowField.getText())-1;
int sticks = Integer.parseInt(sticksField.getText());
// Play that move
nim.play(row, sticks);
// Redisplay the board and enable the AI button
draw();
playButton.setEnabled(false);
AIButton.setEnabled(true);
// Determine whether the game is over
if (nim.isOver()) {
JOptionPane.showMessageDialog(null, "You win!");
playButton.setEnabled(false);
}
}
// Computer move
if (e.getSource() == AIButton) {
// Determine computer move
nim.AIMove();
// Redraw board
draw();
AIButton.setEnabled(false);
playButton.setEnabled(true);
// Is the game over?
if (nim.isOver()) {
JOptionPane.showMessageDialog(null, "You win!");
playButton.setEnabled(false);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
NimApp a = new NimApp();
}
}
The support class:
package nimapp;
import java.util.Random;
import javax.swing.JOptionPane;
import java.io.*;
import java.lang.*;
public class NimGame {
int x = 1;
int[] Sticks; //creating an array of sticks
int totalSticks = 0;
public NimGame(int[] initialSticks){
Sticks = initialSticks;}
public int getRow(int r){
return Sticks[r];}
public void play(int r, int s) throws IllegalSticksException {
try {
Sticks[r]=Sticks[r]-s;
if(s < 0 || s > 3)
throw new IllegalSticksException();
} catch (IllegalSticksException ex){
JOptionPane.showMessageDialog(null, "Not a valid row!");
} catch (IndexOutOfBoundsException e){
JOptionPane.showMessageDialog(null, "Too Many Sticks!");
}
}
public boolean isOver(){
int theTotal = 0;
for (int i = 0; i< Sticks.length; i++){
theTotal = Sticks[i];
System.out.println(Sticks[i]);
System.out.println(theTotal);
}
totalSticks = theTotal;
if (totalSticks <= 0){
return true;
}
else return false;
}
public void AIMove(){
Random randomInt = new Random ();
boolean tryRemove = true;
while(tryRemove && totalSticks >= 1){
int RandomRow = randomInt.nextInt(3);
if(Sticks[RandomRow] <= 0)//the computer can't remove from this row
continue;
//the max number to remove from row
int size = 3;
if( Sticks[RandomRow] < 3)//this row have least that 3 cards
size = Sticks[RandomRow];//make the max number to remove from the row be the number of cards on the row
int RandomDiscard = randomInt.nextInt(size) + 1;
Sticks[RandomRow] = Sticks[RandomRow] - RandomDiscard;
//I don't know if this is needed, but since we remove a RandomDiscard amount lest decrease the totalSticks
totalSticks = totalSticks - RandomDiscard;
//exit loop
tryRemove = false;
}
if(totalSticks <= 1){
int RandomRow = 0;
Sticks[RandomRow] = Sticks[RandomRow]-1;
isOver();
}
}
}
My issue is I really don't understand the syntax.
There is nothing wrong with the syntax as you have written it.
The problem is that you are catching the exception at the wrong place. You are (apparently) intending play to propagate the IllegalSticksException to its caller. But that won't happen because you are catching it within the play method.
There are two possible fixes depending on what you actually intent to happen.
You could remove the throws IllegalSticksException from the play signature.
You could remove the catch (IllegalSticksException ex){ ... } in play and catch/handle the exception at an outer level.