Prints whole array not single value in Java Applet - java

this is a telephone keypad applet.....
I am having issues with my applet it seems to be printing the the whole array up to the chosen number I would like it only to print the chosen number like what happens on a cell phone when you dial a number. Can anyone see where I went wrong? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
public class Telephone extends Frame implements ActionListener
{
Button keys[];
Panel keypad;
TextField lcd;
Label value;
boolean foundKey;
public Telephone()
{
lcd =new TextField(20);
lcd.setEditable(false);
keypad= new Panel ();
keys= new Button[13];
//construct and assign captions to the buttons
for (int i=0; i<=9; i++)
keys[i] = new Button(String.valueOf(i));
keys[10] =new Button ("*");
keys[11] =new Button ("0");
keys[12] =new Button ("#");
setBackground(Color.magenta);
setLayout(new BorderLayout());
keypad.setLayout(new GridLayout(4,3,10,10));
//add keys
for(int i=1; i<=3; i++)//1,2,3
keypad.add(keys[i]);
for (int i=4; i<=6; i++)//4,5,6
keypad.add(keys[i]);
for (int i=7; i<=9; i++)//7,8,9
keypad.add(keys[i]);
keypad.add(keys[10]);
keypad.add(keys[11]);
keypad.add(keys[12]);
for (int i=0; i<keys.length; i++)
keys[i].addActionListener(this);
//add componets to display
add(lcd, BorderLayout.NORTH);
add(keypad,BorderLayout.CENTER);
//add()
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}//constructor ends
public void actionPerformed(ActionEvent e)
{
foundKey = false;
for (int i=0; i<keys.length &&!foundKey;i++)
{
if(e.getSource() == keys[i])
foundKey=true;
//switch(i)
//{
// case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:
lcd.setText(lcd.getText()+ keys[i].getLabel());
// break;
// }//end switch
}//end for
}//end actionPerformed
public static void main(String args[])
{
Telephone f = new Telephone();
f.setTitle("Telephone Application");
f.setBounds(50,130,250,300);
f.setVisible(true);
}
}//class ends

As your statement
if(e.getSource() == keys[i])
has no brackets, only the next statement will be conditionally executed:
foundKey=true;
. But the statement
lcd.setText(lcd.getText()+ keys[i].getLabel());
will be printed, regardless of the if-condition.
Solution: Learn to always put brackets on if, switch, while, for and so on.

Related

Comparing the text of different JButtons

I am currently coding a game and part of it consist of having different tiles to be put in a board. I plan on simulating this by having different buttons that will be used to represent the tiles with their corresponding coordinates. For example, one button will say "A1", "A2", etc. What I would like to accomplish, is to have the user click on the "A1" tile and then the button on the board that represents "A1" will change colors, is there any way to go through the buttons on the board and compare its text to the selection of the user? The following is what I used to create the board:
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
panel.add(buttons[r][c]);
}
}
This is what I wrote on the code of one of the tiles
JButton tile1 = new JButton ("A1");
tile1.setBounds(60,725,60,60);
frame.getContentPane().add(tile1);
tile1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String buttonText = tile1.getText();
// iterating through all buttons:
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++)
{
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText))
{
[i][j].setBackground(Color.BLACK);
}
}
}
}
} );
However, it is given me an error saying that there is an action expected after "{"
You may add an action listener to each of the JButton you are creating in the loop like below:
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code here
}
} );
Placing the listener in your code may look like
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
// now iterate over all the jbuttons you have
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++){
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText)){
// you found a match here
// and you have the positions i, j
//
}
}
}
}
} );
panel.add(buttons[r][c]);
}
}
And you could store the the colors to be changed to in global static array, and use that array in your action listener.
For information on adding listener to the JButton, you may refer this thread How do you add an ActionListener onto a JButton in Java
Hope this helps!
You need listeners.
Implement ActionListener to your class. This will require you to add public void actionPerformed(ActionEvent e) {} to your class.
Every JButton you use should have an action listener.
Apply one like that:
JButton but = new JButton();
but.addActionListener(this);
Finally, in the actionPerformed method we added, you need to add something like that:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but)
but.setBackground(Color.BLACK);
}
P.S. you can get a button's text value by the means of:
but.getText();

Is there a way I can stick this into a for loop?

I updated the code to use for loops, and an arrayList for the buttons. now it has given me an error.
java.lang.NullPointerException
BlueJ editor is pointing to this line.
for(int i=0; i<=buttonsList.size(); i++){
I think it has something to do with instance variables not existing or something before the arrayList. Also, it compiles perfectly, but when I run main, it then goes back to the line in the code!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
//Created class the extends JFrame, and implements action listener
public class Board extends JFrame implements ActionListener
{
//Instance variables
private JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, reset;
private ArrayList<JButton> buttonsList;
//'playerO' uses the letter 'O', not the number zero
Icon playerO = new ImageIcon("images/playerO.jpg");
Icon playerX = new ImageIcon("images/playerX.jpg");
Icon playerN = new ImageIcon("images/reset.jpg");
//Instance variable to determine player turn
boolean firstPlayer = true;
//Constructor
public Board()
{
//Title of Frame
super("Gui7 - TicTacToe || Jose Reyes");
//Created container and set the layout
Container c = getContentPane();
c.setLayout(new BorderLayout());
//Created a panel, and set the layout
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(3,3));
//Created new JButtons and added them to the array list
for(int i=0; i<=buttonsList.size(); i++){
JButton jBut = new JButton(playerN);
buttonsList.add(jBut);
}
//Created reset button and title
reset = new JButton("Play Again?");
//Added buttons to panel with for loop
for(int i=0; i<=buttonsList.size(); i++){
gridPanel.add(buttonsList.get(i));
}
//Added panel and reset button to container
c.add(gridPanel);
c.add(reset, BorderLayout.PAGE_END);
//Added Action Listeners with loop
for(int i=0; i<=buttonsList.size(); i++){
buttonsList.get(i).addActionListener(this);
}
//Added action listener to reset button
reset.addActionListener(this);
//Set the window size and set visibility
setSize(600,600);
setVisible(true);
}
//ActionEvents
public void actionPerformed(ActionEvent e)
{
//Grab source
Object src = e.getSource();
for (int i = 0; i<=buttonsList.size(); i++){
if(src == buttonsList.get(i)){
if(firstPlayer){
buttonsList.get(i).setIcon(playerO);
firstPlayer = false;
} else {
buttonsList.get(i).setIcon(playerX);
firstPlayer = true;
}
}
}
//Reset button icons with loop
if(src == reset){
for (int i = 0; i < 9; i++){
buttonsList.get(i).setIcon(playerN);
}
firstPlayer = true;
}
}
//Main method
public static void main (String args[])
{
Board t = new Board();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Yes you can do this with a for loop.
First, store all your buttons in an array or arraylist. Since the other answer is an array, I'll do arraylist.
ArrayList<Button> buttonsList = new ArrayList<>();
buttonsList.add(b1);
buttonsList.add(b2);
etc. Then,
for (Button b: buttonsList){
if (src == b) {
if (firstPlayer) {
b.setIcon(playerO);
firstPlayer = false;
} else {
b.setIcon(playerX);
firstPlayer = true;
}
}
}
EDIT:
I suggest you just use an arraylist instead of array. Its much easier to work with since you don't need to specify a size before hand.
Instead of this line:
private JButton buttons[];
Do
private ArrayList<Button> buttonList = new Arraylist()<>;
Additionally change,
for(int i=0; i<10; i++){
buttons[i] = new JButton(playerN);
}
//do this instead
for(int i=0; i<10; i++){
JButton jBut = new JButton(playerN);
buttonsList.add(jBut);
}
//Added buttons to panel with for loop
for(int i=0; i<10; i++){
gridPanel.add(buttons[i]);
}
//Do this instead
//Added buttons to panel with for loop
for(int i=0; i<10; i++){
gridPanel.add(buttonsList.get(i));
}
EDIT2:
This is almost definitely causing one of your problems lol
//Added Action Listeners with loop
for(int i=0; i<10; i++){
buttons[1].addActionListener(this);
}
You are adding the listener to the second button- buttons[1] every time. Change that to buttons[i].addActionListener(this); and it will probably work.
Rather than have a bunch of variables named b1...b9, make an array of whatever type b1 is. Then you can iterate over the array like this:
for (int i = 0; i < 9; i++){
if(src == bArray[i]){
if(firstPlayer){
bArray[i].setIcon(playerO);
firstPlayer = false;
} else {
bArray[i].setIcon(playerX);
firstPlayer = true;
}
}
}
something like below should work.
JButton[] buttons = new JButton[9]; // i'll leave you to fill it
for(int i = 0; i < buttons.length; i++){ // assuming the array is filled
if(src == buttons[i]){
if(firstPlayer){
buttons[i].setIcon(playerO);
firstPlayer = false;
} else {
buttons[i].setIcon(playerX);
firstPlayer = true;
}
}
}

Program freezing(not responding) after button click no a Java app

Ok so I'm building to show students how a loop goes through an array, I have added 2 images to help explain and the code, the first is the result I get after I click go then it freezes . The Second image is what I'd like it to do after you put in the values of 1 in start, 15 in stop, 3 in step and click the Go Button. And then to be cleared on the click of Clear button. I think they probably related. Can anyone see the problem? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
public Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}//end for
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
The problem is your loop: your loop variable name is i but you change the varStep variable instead of i so basically the loop variable never changes and thus the exit condition will never be true.
I believe you want to step i with varStep, so change your loop to:
for (int i = varStart; i<varStop; i += varStep)
// stuff inside loop
Take a look at this loop.
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
It ends when i >= varStop, but neither i nor varStop change as a consequence of its execution, so it can never stop. You only increment varStep.
I think you want to increment i by varStep on each iteration instead, i.e. i += varStep
You use varStep++ in your for loop. I think you meant to do i+varStep.
The application freezes because you're never increasing i, resulting in an endless loop.

JButton array ActionListener

In short, I would like to accumulate a bunch of JButton's to an array, and create one ActionListener class for the array.
I'm trying to create a calculator, and all the numbered buttons, such as "6", are in a JButton array, because I would like to have it input the set number into a temporary int, and it would be easier to create one method, instead of 10. I also have 40 other buttons, that I would like to apply the same principal to, but in a different array, so it would be much faster and easier to put these into a couple of ActionListener methods where the buttons data is implemented to that method.
this is the code I have:
private JButton num0, num1, num2, num3, num4, num5, num6, num7, num8, num9;
private JButton numArray[] = {num0, num1, num2, num3, num4, num5, num6, num7, num8, num9};
public GUI(){
numArray.AddActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
}
});
}
You can consider the proposal of Newb Monad. However, you can use the same listener for all your buttons, as in the following example.
public static void main(String[] args) {
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
String text = ((JButton) e.getSource()).getText();
JOptionPane.showMessageDialog(null, text);
}
}
};
JPanel panel = new JPanel(new GridLayout(4,3));
JButton[] array = new JButton[10];
for (int i = 0; i < array.length; i++) {
array[i] = new JButton(String.valueOf(i));
array[i].addActionListener(listener);
panel.add(array[i]);
}
JOptionPane.showMessageDialog(null, panel);
}
You have the right idea. However, array objects do not have an addActionListener() method. You must add an action listener to each JButton individually. You can use the same listener for every button, but then you have to figure out which button was clicked inside the actionPerformed() method. IMO, a cleaner solution is to assign a separate listener to each JButton because that way each ActionListener can know which number is pressed without checking the source of the event. For example, you can create a NumberButtonListener class which takes an int as the only argument to its constructor. You can then create the JButtons and the corresponding NumberButtonListeners at the same time in a small loop.
This seems to work well for me.
I essentially loop through all of the buttons while checking it against the action (e.getSource()).
public void actionPerformed(ActionEvent e){
//loop through allbuttons to check if clicked
for(int i = 0; i < buttonArr.length; i++){
for(int j = 0; j < buttonArr[0].length; j++){
if(e.getSource() == buttonArr[i][j]){
//do stuff
}
}
}
}
I had a similar problem with a 2D array of buttons for a game of "Connect Four". I was able to use a for loop inside ActionListener to test which of my buttons had been pushed. The key was modifying the toString() method from my button class to supply the array element as a string:
Within the JPanel class definition:
...
discs = new RoundButton[6][7]; //my 2D array
...
public class RoundButton extends JButton {
...
public String toString() {
return "discs["+i+"]["+j+"]";
}
...
}
private class ButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < discs.length; i++){
for (int j= 0; j < discs[i].length; j++){
if (event.getSource() == discs[i][j]){
discs[i][j].setIcon(yellowDisc); //my particular action for that button
}
}
Sorry this is messy. I've never posted on here before.

for loop for array only processing one element in java?

I can't figure out why whenever I cycle through my array using the for-loop it only produces one element (the first) to console? I'm pretty sure it's a rookie-mistake I'm looking over, so any tips and suggestions would help.
I'm making a program for fun that compares two strings typed in a text field and if they don't exist in the array it produces a JOPtionPane message on the contrary. It's for a battle-hack I may produce in the future for vBulletin forum, but I'm messing around with algorithms before I move to that step. Thanks, guys!
package battleoptionspart1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
import javax.swing.border.*;
public class BattleOptionsPart1 extends JFrame{
JButton newthread, previewpost;
JRadioButton battle1;
JTextField postcount, oppA, oppB;
JLabel battle2, max;
JPanel panel;
String [] array = {"Bill","Tom","Wendy", "Paula"};
public BattleOptionsPart1 () {
panel = new JPanel();
Toolkit tool = Toolkit.getDefaultToolkit();
Dimension dim = tool.getScreenSize();
this.setSize(500, 500);
this.setTitle("Battle Options");
GridLayout grid = new GridLayout(0,1,2,2);
this.setLayout(grid);
newthread = new JButton("Post New Thread");
previewpost = new JButton("Preview Post");
postcount = new JTextField("", 4);
oppA = new JTextField("",10);
oppB = new JTextField("",10);
battle1 = new JRadioButton();
battle2 = new JLabel("Would you like to start a recorded battle?");
max = new JLabel("Enter max post count user must have to vote");
ListenForButton listen = new ListenForButton();
newthread.addActionListener(listen);
previewpost.addActionListener(listen);
JPanel opponents = new JPanel();
Border oppBorder = BorderFactory.createTitledBorder("Battlers");
opponents.setBorder(oppBorder);
opponents.add(oppA);
opponents.add(oppB);
JPanel battle = new JPanel();
Border battleBorder = BorderFactory.createTitledBorder("Start Battle");
battle.setBorder(battleBorder);
battle.add(battle1);
battle.add(battle2);
JPanel buttons = new JPanel();
Border buttonBorder = BorderFactory.createTitledBorder("Create Thread");
buttons.setBorder(buttonBorder);
buttons.add(newthread);
buttons.add(previewpost);
JPanel restriction = new JPanel();
Border resBorder = BorderFactory.createTitledBorder("Restrictions");
restriction.setBorder(buttonBorder);
restriction.add(postcount);
restriction.add(max);
this.add(opponents);
this.add(battle);
this.add(restriction);
this.add(buttons);
this.add(panel);
int xPos = (dim.width / 2) - (this.getWidth() / 2);
int yPos = (dim.height / 2) - (this.getHeight() / 2);
this.setLocation(xPos,yPos); //places form in the middle
this.setVisible(true); // users can see form
this.setResizable(false); //users can't resize the form
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String compareA = oppA.getText();
String compareB = oppB.getText();
if (e.getSource() == newthread)
{
System.out.println(compareA + "\n" + compareB);
for(int j = 0; j < array.length; j++)
{
System.out.println(array[j]);
if(!compareA.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareA + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppA.requestFocus();
break;
}
if (!compareB.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareB + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppB.requestFocus();
break;
}
else
{
JOptionPane.showMessageDialog(null, "New thread created successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
else if (e.getSource() == previewpost)
{
System.exit(0);
}
}
}
public static void main(String[] args) {
BattleOptionsPart1 battle = new BattleOptionsPart1();
}
}
In each of the possible options in your loop, you use break, which leaves the loop immediately. If you remove those statements, you'll process each object in the array.
If you want to check if there's a match, you need to go through every element and do your processing after going through the whole array. Here is an example for an array of type int:
boolean contains = false;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == searchKey)
{
contains = true;
break;
}
}
You're breaking out of the loop. with the break; command after the first array element

Categories

Resources