Why wont my JOptionPane error message pop up? - java

I made a GUI program where it counts certain elements of whatever is entered in the main text field. If the text field is empty, a message should pop up saying that the user should enter text in the text field. I made an if statement if tfMain == null, a JOptionPane message should pop-up, but for some reason it won't. Any tips on why it doesn't pop up?
here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class LabExcer9 extends WindowAdapter implements ActionListener
{
//Container
private Frame f;
private Panel p1,p2,p3;
//Component
private Button bReadAndComp, bClear;
private TextField tfMain,tf1,tf2,tf3,tf4,tf5,tf6;
private Label l1,l2,l3,l4,l5,l6;
public LabExcer9()
{
f = new Frame("Character Counter of Miguel Martin");
p1 = new Panel();
p2 = new Panel();
p3 = new Panel();
bReadAndComp = new Button("Read and Compute");
bClear = new Button("Clear ALL Values");
tfMain = new TextField(null);
tf1 = new TextField("0");
tf2 = new TextField("0");
tf3 = new TextField("0");
tf4 = new TextField("0");
tf5 = new TextField("0");
tf6 = new TextField("0");
l1 = new Label("Number of Words ");
l2 = new Label("Number of Characters ");
l3 = new Label("Number of Vowels ");
l4 = new Label("Number of Consonants ");
l5 = new Label("Number of Digits ");
l6 = new Label("Number of Symbols and Spaces ");
}
public void assembleGUI()
{
p1.setLayout(new GridLayout(1,1));
p1.setPreferredSize(new Dimension(200, 200));
p1.add(tfMain);
p2.setLayout(new GridLayout(6,2));
p2.add(l1);
p2.add(tf1);
p2.add(l2);
p2.add(tf2);
p2.add(l3);
p2.add(tf3);
p2.add(l4);
p2.add(tf4);
p2.add(l5);
p2.add(tf5);
p2.add(l6);
p2.add(tf6);
p3.setLayout(new GridLayout(1,2));
p3.add(bReadAndComp);
p3.add(bClear);
f.add(p1,BorderLayout.NORTH);
f.add(p2,BorderLayout.CENTER);
f.add(p3,BorderLayout.SOUTH);
f.pack();
f.addWindowListener(this);
f.setVisible(true);
//registers
bReadAndComp.addActionListener(this);
bClear.addActionListener(this);
}
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
//gets main text
String textString = tfMain.getText();
//puts words into array
int vowels = 0, consonants = 0, digits = 0, symbolsAndSpaces = 0;
int characters = textString.length();
if(tfMain.getText() == "" || tfMain.getText() == null )
{
if(source == bReadAndComp)
JOptionPane.showMessageDialog(null, "Please Enter Text!");
}
else if(tfMain.getText() != null && tfMain.getText() != "")
{
if(source == bReadAndComp)
{
for(int i = 0;i<textString.length();i++)
{
if(Character.isDigit(textString.charAt(i)))
digits++;
if(Character.isLetterOrDigit(textString.charAt(i)) == false)
symbolsAndSpaces++;
if(isVowel(textString.charAt(i)) == true)
vowels++;
else if(Character.isDigit(textString.charAt(i)) == false && isVowel(textString.charAt(i)) == false && textString.charAt(i) != ' ' && Character.isLetter(textString.charAt(i)) == true)
consonants++;
}
tf1.setText(""+textString.split(" ").length);
tf2.setText(""+characters);
tf3.setText(""+vowels);
tf4.setText(""+consonants);
tf5.setText(""+digits);
tf6.setText(""+symbolsAndSpaces);
//System.out.println(textStringArray[0]+"wat");
//JOptionPane.showMessageDialog(null, "Please Enter Text!");
}
else if (source == bClear)
{
tf1.setText("0");
tf2.setText("0");
tf3.setText("0");
tf4.setText("0");
tf5.setText("0");
tf6.setText("0");
tfMain.setText(null);
}
}
}
public boolean isVowel(char c)
{
if (c == 'a' || c == 'A' ||c== 'e' ||c == 'E' ||c == 'i' ||c == 'I' ||c == 'o' ||c == 'O' ||c == 'u' ||c == 'U')
return true;
else
return false;
}
public static void main(String args [])
{
LabExcer9 GUI = new LabExcer9();
GUI.assembleGUI();
}
}

To compare string please use equals or equalsIgnoreCase.
Replace your
if(tfMain.getText() == "" || tfMain.getText() == null )
statement with the following:
if("".equals(tfMain.getText())){
}

Related

Infinite loop while comparing characters in a string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
What statement should I use to compare the characters in a string one by one so that it does not enter an infinite loop. Something like comparing an array of characters in C/C++.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class Calcc extends JFrame implements ActionListener {
String l = "b";
int z = 0;
JFrame f;
JTextField t1 = new JTextField(30);
JTextField t2 = new JTextField(10);
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("0");
JButton b11 = new JButton("+");
JButton b12 = new JButton("-");
JButton b13 = new JButton("*");
JButton b14 = new JButton("/");
JButton b15 = new JButton("=");
Calcc() {
f = new JFrame();
f.add(t1);
f.add(t2);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(b10);
f.add(b11);
f.add(b12);
f.add(b13);
f.add(b14);
f.add(b15);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);
f.setVisible(true);
f.setSize(350, 350);
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String d;
d = t1.getText();
if (e.getSource() == b1) {
t1.setText(d + "1");
}
if (e.getSource() == b2) {
t1.setText(d + "2");
}
if (e.getSource() == b3) {
t1.setText(d + "3");
}
if (e.getSource() == b4) {
t1.setText(d + "4");
}
if (e.getSource() == b5) {
t1.setText(d + "5");
}
if (e.getSource() == b6) {
t1.setText(d + "6");
}
if (e.getSource() == b7) {
t1.setText(d + "7");
}
if (e.getSource() == b8) {
t1.setText(d + "8");
}
if (e.getSource() == b9) {
t1.setText(d + "9");
}
if (e.getSource() == b10) {
t1.setText(d + "0");
}
if (e.getSource() == b11) {
t1.setText(d + "+");
}
if (e.getSource() == b12) {
t1.setText(d + "-");
}
if (e.getSource() == b13) {
t1.setText(d + "*");
}
if (e.getSource() == b14) {
t1.setText(d + "/");
}
if (e.getSource() == b15) {
while (l != "a") {
int b = calcA(d);
if (l == "+")
z = z + b;
else if (l == "-")
z = z - b;
else if (l == "*")
z = z * b;
else if (l == "*")
z = z * b;
}
t2.setText(String.valueOf(z));
}
}
int calcA(String d1) {
l = "a";
int k = 0;
while ((d1 != "+") && (d1 != "-") && (d1 != "*") && (d1 != "/")) {
if (d1 != "\n")
break;
k = k * 10 + Integer.valueOf(d1);
}
l = d1;
return k;
}
}
public class CalcD {
public static void main(String[] args) {
new Calcc();
}
}
You appear to be comparing strings alot, using == to do it is bad practice.
This is because Strings are objects and comparing using the == operator will check to see if they are the exact same object regardless of value. Strings are a special case, when creating a String the jvm will decide whether or not to use an existing object or create a new one, so we can not be 100% sure if "==" will return true or not even the they contain the same value.
To compare Strings please use string1.equals(string2).
The .equals method should be used to compare the value of objects, and the == operator to compare primitives.
You do not need to check with any character like you do in C/C++. You need to simply iterate it with the length of the String. Simply use this in your loop:
for (int i=0;i<string.length();i++) {
char c = string.charAt(i);
// do whatever with your character.
}
That said, when you compare strings for equality in Java, you should always use the String.equals method instead of ==.
So, you should change your code from
getSource() == b1
to
getSource().equals(b1)
Hope this helps!
Thank you guys for clarifying some doubts....
for the above programme i used String.charAt(int);
to compare every specific character at the loop....

Swing frame doesnt hold or stay after clicking jbutton

I have 2 text areas with a button in between them in a frame in swing and I am using netbeans.
Clicking the button picks up an sql query from textArea1, using getText().
The input is processed (i.e. checked the spellings of the keywords after splitting the query) with SubmitData(). Inside that method, it only uses setText() to set the output to textArea2.
My Problem Is:
The frame just doesn't stay or hold after I press the button.
Here is my code:
void createUI() throws Exception
{
JFrame frame = new JFrame("JDBC All in One");
// Layout of Main Window
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
textArea1 = new JTextArea(10, 50);
textArea1.setBounds(10, 10, 30, 30);
btnInsert = new JButton("Submit");
btnInsert.setBounds(10, 10, 10, 10);
btnInsert.addActionListener(this);
textArea2 = new JTextArea(10, 50);
textArea2.setBounds(10, 10, 30, 30);
JPanel pnlInput1 = new JPanel();
JPanel pnlInput2 = new JPanel();
JPanel pnlInput3 = new JPanel();
pnlInput1.add(textArea1);
pnlInput3.add(btnInsert);
pnlInput2.add(textArea2);
frame.add(pnlInput1);
frame.add(pnlInput3);
frame.add(pnlInput2);
frame.setSize(400, 500);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
String cmd = evt.getActionCommand();
if (cmd.equals("Submit")) {
try {
SubmitData();
} catch (Exception e) {}
}
}
public static void SubmitData() throws Exception {
s1 = textArea1.getText();
String[] s2 = s1.split("\\s+");
for (int i = 0; i < s2.length; i++) {
if (s2[i] .equals("elect")|| s2[i] .equals("selct") || s2[i].equals("slect" )|| s2[i].equals("selec")|| s2[i].equals("seect")
{
textArea2.setText("use 'select' instead of " + s2[i]);
System.exit(0);
}
if (s2[i] == "updat" || s2[i] == "updae" || s2[i] == "updte" || s2[i] == "upate") {
textArea2.setText("use 'update' instead of " + s2[i]);
System.exit(0);
}
if (s2[i] == "delet" || s2[i] == "delte" || s2[i] == "elete" || s2[i] == "dlete") {
textArea2.setText("use 'delete' instead of " + s2[i]);
System.exit(0);
}
if (s2[i] == "fro" || s2[i] == "frm" || s2[i] == "fom") {
textArea2.setText("use 'from' instead of " + s2[i]);
System.exit(0);
}
}
}
Edited-i've changed "==" fro string comparision with .equals() but the problem doesnt seem to go away.
System.exit(0);terminates your JVM. Remove it if you want to keep your frame.
Edit for second question :
After your first if, replace your if by else if in order that the others if don't execute when a condition is true.
for (int i = 0; i < s2.length; i++) {
if (s2[i] .equals("elect")|| s2[i] .equals("selct") || s2[i].equals("slect" )|| s2[i].equals("selec")|| s2[i].equals("seect")
{
textArea2.setText("use 'select' instead of " + s2[i]);
}
else if (s2[i] == "updat" || s2[i] == "updae" || s2[i] == "updte" || s2[i] == "upate") {
textArea2.setText("use 'update' instead of " + s2[i]);
}
else if (s2[i] == "delet" || s2[i] == "delte" || s2[i] == "elete" || s2[i] == "dlete") {
textArea2.setText("use 'delete' instead of " + s2[i]);
}
else if (s2[i] == "fro" || s2[i] == "frm" || s2[i] == "fom") {
textArea2.setText("use 'from' instead of " + s2[i]);
}
}

Tic Tac Toe game in Java

Ok guys...I'm stumped again.
I managed to get the game working. However, now I'm down to the point of trying to code the win conditions. I'm thinking of using a boolean array for each of the buttons, but can't figure out how to cross reference the buttons[] to the gameSquares[] to set the elements of gameSquares[] to true/false flags.
Any pointers? (Code is copied below).
** A few other interesting bugs I feel worth mentioning:
1) Start and Reset don't seem to work correctly
2) When the computer tries multiple attempts in invalid squares, the squares seem to jump or dance around. It's really weird.
package tictactoegame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
class TicTacToeBoard extends JFrame implements ActionListener
{
JButton[] buttons = new JButton[10];
boolean player1 = false, player2 = false;
boolean[] gameSquares = {false, false, false,
false, false, false,
false, false, false};
boolean startPlayer = false;
int turnCount = 0;
public TicTacToeBoard()
{
JFrame gameWindow = new JFrame();
gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
gameWindow.setSize(300,400);
gameWindow.setVisible(true);
JPanel gamePanel = new JPanel();
gamePanel.setSize(300,400);
GridLayout grid = new GridLayout(4,3);
gamePanel.setLayout(grid);
for(int i = 0; i < 9; i++)
{
buttons[i] = new JButton("");
buttons[i].addActionListener(this);
gamePanel.add(buttons[i]);
}
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
JButton helpButton = new JButton("Help");
helpButton.addActionListener(this);
gamePanel.add(startButton);
gamePanel.add(helpButton);
gamePanel.add(resetButton);
gameWindow.add(gamePanel);
gameWindow.pack();
while (turnCount < 9)
{
gamePlay();
}
}
public void gamePlay()
{
while(!startPlayer)
{
int random = randomGenerator();
if (random%2 == 0)
{
player1 = true;
JOptionPane.showMessageDialog(null, "Player is first.");
startPlayer = true;
}
else if (random%2 == 1)
{
player2 = true;
JOptionPane.showMessageDialog(null, "Computer is first.");
startPlayer = true;
}
}
if (player2)
{
int index;
Random randomGenerator = new Random();
index = randomGenerator.nextInt(9);
buttons[index].doClick();
player2 = false;
player1 = true;
}
}
public int randomGenerator()
{
int randomNum;
Random randomGenerator = new Random();
randomNum = randomGenerator.nextInt(100);
return randomNum;
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source instanceof JButton)
{
JButton button = (JButton) source;
if (button.getText() == "Start")
{
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Reset")
{
for(int i = 0; i < 9; i++)
{
buttons[i].setText("");
}
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Help")
{
JOptionPane.showMessageDialog(null, "Help:\n\n" +
"How to play-\n" +
"Select an empty square. The square will be filled with"
+ "with your symbole, either X or O.\n" +
"The game is won when either player gets three X's or"
+ "O's in a row horizontally,\n vertically, or diagonally.");
}
if (button.getText() == "" && player1)
{
button.setText("X");
turnCount += 1;
player1 = false;
player2 = true;
}
else if (button.getText() == "" && player2)
{
button.setText("O");
turnCount+=1;
player2 = false;
player1 = true;
}
else if (button.getText() == "X" || button.getText() == "O")
{
if(player2 == true)
{
gamePlay();
}
else
{
JOptionPane.showMessageDialog(null, "Invalid choice. Select"
+ " another square.");
}
}
}
}
}
Check this TicTacToe Full code using the Applets...:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
<applet code="TicTacToe.class" width="300" height="300">
</applet>
*/
public class TicTacToe extends Applet implements ActionListener {
Button[] btnarray = new Button[9];
private final static String PLAYER1 = "PLAYER1";
private final static String PLAYER2 = "PLAYER2";
private static String CURRENT_PLAYER = null;
Label lbl = new Label();
public void init() {
CURRENT_PLAYER = PLAYER1;
lbl.setText(CURRENT_PLAYER + " Turn!");
setLayout(new BorderLayout());
Panel p = new Panel();
GridLayout gl = new GridLayout(3, 3);
p.setLayout(gl);
setBackground(Color.BLACK);
setForeground(Color.WHITE);
setSize(300, 300);
Font myFont = new Font("TimesRoman", Font.BOLD, 80);
for (int i = 0; i < 9; i++) {
btnarray[i] = new Button(null);
btnarray[i].setActionCommand("" + i);
btnarray[i].addActionListener(this);
btnarray[i].setFont(myFont);
btnarray[i].setBackground(Color.white);
p.add(btnarray[i]);
}
add(BorderLayout.CENTER, p);
add(BorderLayout.NORTH, lbl);
add(BorderLayout.SOUTH, new Label("Player 1 => X , Player 2 => 0"));
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int index = Integer.parseInt(e.getActionCommand());
btnarray[index].disable();
if (CURRENT_PLAYER == PLAYER1) {
btnarray[index].setLabel("X");
CURRENT_PLAYER = PLAYER2;
} else {
btnarray[index].setLabel("0");
CURRENT_PLAYER = PLAYER1;
}
lbl.setText(CURRENT_PLAYER + " Turn!");
check();
}
void check() {
String[] pattern = new String[8];
pattern[0] = btnarray[0].getLabel() + btnarray[1].getLabel()
+ btnarray[2].getLabel();
pattern[1] = btnarray[3].getLabel() + btnarray[4].getLabel()
+ btnarray[5].getLabel();
pattern[2] = btnarray[6].getLabel() + btnarray[7].getLabel()
+ btnarray[8].getLabel();
pattern[3] = btnarray[0].getLabel() + btnarray[3].getLabel()
+ btnarray[6].getLabel();
pattern[4] = btnarray[1].getLabel() + btnarray[4].getLabel()
+ btnarray[7].getLabel();
pattern[5] = btnarray[2].getLabel() + btnarray[5].getLabel()
+ btnarray[8].getLabel();
pattern[6] = btnarray[0].getLabel() + btnarray[4].getLabel()
+ btnarray[8].getLabel();
pattern[7] = btnarray[2].getLabel() + btnarray[4].getLabel()
+ btnarray[6].getLabel();
int j = 0;
while (j < 8) {
char[] array = pattern[j].toCharArray();
if (array[0] == 'X' && array[1] == 'X' && array[2] == 'X') {
lbl.setText(PLAYER1 + " Wins!");
} else if (array[0] == '0' && array[1] == '0' && array[2] == '0') {
lbl.setText(PLAYER2 + " Wins!");
}
j++;
}
}
}

Adding a main to a pre existing program

I wrote a fairly simple program using a GUI template to learn about adding some form of GUI in java. I completed the program only to discover that it cant be run outside of the IDE without a main method. The program works fine inside Eclipse IDE, but useless otherwise. How do I go about adding a main class so it can be executed as a .jar?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JApplet implements ActionListener {
// Create all labels, textfields and buttons needed (in order)
/**
* This is a tic tac toe game made with the purposes of learning java
*/
private static final long serialVersionUID = 1L;
JButton firstButton;
JButton secondButton;
JButton thirdButton;
JButton fourthButton;
JButton fithButton;
JButton sixthButton;
JButton seventhButton;
JButton eighthButton;
JButton ninthButton;
//this is the position value checker which are later set to x and o
String[] posCheck = { "", "", "", "", "", "", "", "", "" };
// score count JLABELs to display the score inside the game pane.
JLabel scoreP1;
JLabel scoreP2;
// this is used for formatting purposes or something like that, I guess.
JLabel blank;
// score count variables for both players, they both start at 0.
int scoreCount1 = 0, scoreCount2 = 0;
int gamesPlayed = -1;
boolean gameDone = false;
int k;
String prevWinner = "";
// Create any global variables/arrays needed later in the program (final)
Container pane = getContentPane();
//this sets the tile to X or O depending on who's turn it is
String[] symbol = { "O", "X" };
int turnCounter = 0;
int tieChecker = 0;
// Sets up GUI components.
public void init() {
pane.setLayout(new GridLayout(4, 3));
setSize(500, 500);
// Adds jlabel for scores
scoreP1 = new JLabel();
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
scoreP2 = new JLabel();
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank = new JLabel();
blank.setText(prevWinner);
// these are the JButtons that go in the game panel along with action
// listeners
firstButton = new JButton();
firstButton.addActionListener(this);
secondButton = new JButton();
secondButton.addActionListener(this);
thirdButton = new JButton();
thirdButton.addActionListener(this);
fourthButton = new JButton();
fourthButton.addActionListener(this);
fithButton = new JButton();
fithButton.addActionListener(this);
sixthButton = new JButton();
sixthButton.addActionListener(this);
seventhButton = new JButton();
seventhButton.addActionListener(this);
eighthButton = new JButton();
eighthButton.addActionListener(this);
ninthButton = new JButton();
ninthButton.addActionListener(this);
pane.add(firstButton, 0); // second parameter is the index on pane
pane.add(secondButton, 1);
pane.add(thirdButton, 2);
pane.add(fourthButton, 3);
pane.add(fithButton, 4);
pane.add(sixthButton, 5);
pane.add(seventhButton, 6);
pane.add(eighthButton, 7);
pane.add(ninthButton, 8);
pane.add(scoreP1);
pane.add(blank);
pane.add(scoreP2);
gamesPlayed++;
setContentPane(pane);
} // init method
// checks for mouse clicks here.
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
if (e.getSource() == firstButton)
revealButton(firstButton, 0);
else if (e.getSource() == secondButton)
revealButton(secondButton, 1);
else if (e.getSource() == thirdButton)
revealButton(thirdButton, 2);
else if (e.getSource() == fourthButton)
revealButton(fourthButton, 3);
else if (e.getSource() == fithButton)
revealButton(fithButton, 4);
else if (e.getSource() == sixthButton)
revealButton(sixthButton, 5);
else if (e.getSource() == seventhButton)
revealButton(seventhButton, 6);
else if (e.getSource() == eighthButton)
revealButton(eighthButton, 7);
else if (e.getSource() == ninthButton)
revealButton(ninthButton, 8);
}
} // actionPerformed method
// respond to button pushed
public void revealButton(JButton button, int index) {
// removes the indicated button from pane
pane.remove(button);
// creates a new text field to take the place of the button, makes it
// uneditable and sets background colour
JTextField textField = new JTextField();
textField.setEditable(false);
textField.setBackground(Color.WHITE);
// sets the alignment for the text in the field
textField.setHorizontalAlignment(SwingConstants.CENTER);
// adds the new textfield to the pane at the location of the old button
pane.add(textField, index);
posCheck[index] = symbol[(turnCounter % 2)];
prevWinner = "Player (" + symbol[(turnCounter % 2)]
+ ") is the winner!";
// re-creates pane with new information
setContentPane(pane);
// this sets the text field to either X or O depending who placed last.
textField.setText(symbol[(turnCounter) % 2]);
button.setEnabled(false);
// this is a counter to check if it is a cats game.
tieChecker++;
// check for winner X here
if (((posCheck[0] == "X") && (posCheck[1] == "X") && (posCheck[2] == "X"))
|| ((posCheck[3] == "X") && (posCheck[4] == "X") && (posCheck[5] == "X"))
|| ((posCheck[6] == "X") && (posCheck[7] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[3] == "X") && (posCheck[6] == "X"))
|| ((posCheck[1] == "X") && (posCheck[4] == "X") && (posCheck[7] == "X"))
|| ((posCheck[2] == "X") && (posCheck[5] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[4] == "X") && (posCheck[8] == "X"))
|| ((posCheck[2] == "X") && (posCheck[4] == "X") && (posCheck[6] == "X"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount1++;
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
blank.setText("Player (X) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if O has won the game.
else if (((posCheck[0] == "O") && (posCheck[1] == "O") && (posCheck[2] == "O"))
|| ((posCheck[3] == "O") && (posCheck[4] == "O") && (posCheck[5] == "O"))
|| ((posCheck[6] == "O") && (posCheck[7] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[3] == "O") && (posCheck[6] == "O"))
|| ((posCheck[1] == "O") && (posCheck[4] == "O") && (posCheck[7] == "O"))
|| ((posCheck[2] == "O") && (posCheck[5] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[4] == "O") && (posCheck[8] == "O"))
|| ((posCheck[2] == "O") && (posCheck[4] == "O") && (posCheck[6] == "O"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount2++;
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank.setText("Player (O) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if there has been a tie in the game
else if (tieChecker >= 9) {
prevWinner = ("It's a cat's game!");
tieChecker = 0;
gameDone = true;
turnCounter++;
}
// this makes sure the game doesnt end prematurely
else {
gameDone = false;
}
// this if statement is engaged when the game is done and resets the
// board
if (gameDone == true) {
pane.removeAll();
textField.removeAll();
tieChecker = 0;
init();
posCheck[0] = "";
posCheck[1] = "";
posCheck[2] = "";
posCheck[3] = "";
posCheck[4] = "";
posCheck[5] = "";
posCheck[6] = "";
posCheck[7] = "";
posCheck[8] = "";
posCheck[9] = "";
}// end of reset sequence
turnCounter++;
blank.setText("Games Played: " + gamesPlayed);
}
}
If you insist on keeping it as an Applet, make another class and do this:
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
Game g = new Game();
g.init();
frame.getContentPane().add(g);
frame.pack();
frame.setVisible(true);
}
}
You can convert JApplet to JFrame - Change your public init() method to public static void main (String args[]).Then create an instance of JFrame
JFrame frame = new JFrame(); Then add components to it.
or
Add existing applet to JFrame - Adding JApplet into JFrame
So using second method your code would be -
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JApplet implements ActionListener {
// Create all labels, textfields and buttons needed (in order)
/**
* This is a tic tac toe game made with the purposes of learning java
*/
private static final long serialVersionUID = 1L;
JButton firstButton;
JButton secondButton;
JButton thirdButton;
JButton fourthButton;
JButton fithButton;
JButton sixthButton;
JButton seventhButton;
JButton eighthButton;
JButton ninthButton;
//this is the position value checker which are later set to x and o
String[] posCheck = { "", "", "", "", "", "", "", "", "" };
// score count JLABELs to display the score inside the game pane.
JLabel scoreP1;
JLabel scoreP2;
// this is used for formatting purposes or something like that, I guess.
JLabel blank;
// score count variables for both players, they both start at 0.
int scoreCount1 = 0, scoreCount2 = 0;
int gamesPlayed = -1;
boolean gameDone = false;
int k;
String prevWinner = "";
// Create any global variables/arrays needed later in the program (final)
Container pane = getContentPane();
//this sets the tile to X or O depending on who's turn it is
String[] symbol = { "O", "X" };
int turnCounter = 0;
int tieChecker = 0;
// Sets up GUI components.
public void init() {
pane.setLayout(new GridLayout(4, 3));
setSize(500, 500);
// Adds jlabel for scores
scoreP1 = new JLabel();
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
scoreP2 = new JLabel();
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank = new JLabel();
blank.setText(prevWinner);
// these are the JButtons that go in the game panel along with action
// listeners
firstButton = new JButton();
firstButton.addActionListener(this);
secondButton = new JButton();
secondButton.addActionListener(this);
thirdButton = new JButton();
thirdButton.addActionListener(this);
fourthButton = new JButton();
fourthButton.addActionListener(this);
fithButton = new JButton();
fithButton.addActionListener(this);
sixthButton = new JButton();
sixthButton.addActionListener(this);
seventhButton = new JButton();
seventhButton.addActionListener(this);
eighthButton = new JButton();
eighthButton.addActionListener(this);
ninthButton = new JButton();
ninthButton.addActionListener(this);
pane.add(firstButton, 0); // second parameter is the index on pane
pane.add(secondButton, 1);
pane.add(thirdButton, 2);
pane.add(fourthButton, 3);
pane.add(fithButton, 4);
pane.add(sixthButton, 5);
pane.add(seventhButton, 6);
pane.add(eighthButton, 7);
pane.add(ninthButton, 8);
pane.add(scoreP1);
pane.add(blank);
pane.add(scoreP2);
gamesPlayed++;
setContentPane(pane);
} // init method
// checks for mouse clicks here.
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
if (e.getSource() == firstButton)
revealButton(firstButton, 0);
else if (e.getSource() == secondButton)
revealButton(secondButton, 1);
else if (e.getSource() == thirdButton)
revealButton(thirdButton, 2);
else if (e.getSource() == fourthButton)
revealButton(fourthButton, 3);
else if (e.getSource() == fithButton)
revealButton(fithButton, 4);
else if (e.getSource() == sixthButton)
revealButton(sixthButton, 5);
else if (e.getSource() == seventhButton)
revealButton(seventhButton, 6);
else if (e.getSource() == eighthButton)
revealButton(eighthButton, 7);
else if (e.getSource() == ninthButton)
revealButton(ninthButton, 8);
}
} // actionPerformed method
// respond to button pushed
public void revealButton(JButton button, int index) {
// removes the indicated button from pane
pane.remove(button);
// creates a new text field to take the place of the button, makes it
// uneditable and sets background colour
JTextField textField = new JTextField();
textField.setEditable(false);
textField.setBackground(Color.WHITE);
// sets the alignment for the text in the field
textField.setHorizontalAlignment(SwingConstants.CENTER);
// adds the new textfield to the pane at the location of the old button
pane.add(textField, index);
posCheck[index] = symbol[(turnCounter % 2)];
prevWinner = "Player (" + symbol[(turnCounter % 2)]
+ ") is the winner!";
// re-creates pane with new information
setContentPane(pane);
// this sets the text field to either X or O depending who placed last.
textField.setText(symbol[(turnCounter) % 2]);
button.setEnabled(false);
// this is a counter to check if it is a cats game.
tieChecker++;
// check for winner X here
if (((posCheck[0] == "X") && (posCheck[1] == "X") && (posCheck[2] == "X"))
|| ((posCheck[3] == "X") && (posCheck[4] == "X") && (posCheck[5] == "X"))
|| ((posCheck[6] == "X") && (posCheck[7] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[3] == "X") && (posCheck[6] == "X"))
|| ((posCheck[1] == "X") && (posCheck[4] == "X") && (posCheck[7] == "X"))
|| ((posCheck[2] == "X") && (posCheck[5] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[4] == "X") && (posCheck[8] == "X"))
|| ((posCheck[2] == "X") && (posCheck[4] == "X") && (posCheck[6] == "X"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount1++;
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
blank.setText("Player (X) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if O has won the game.
else if (((posCheck[0] == "O") && (posCheck[1] == "O") && (posCheck[2] == "O"))
|| ((posCheck[3] == "O") && (posCheck[4] == "O") && (posCheck[5] == "O"))
|| ((posCheck[6] == "O") && (posCheck[7] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[3] == "O") && (posCheck[6] == "O"))
|| ((posCheck[1] == "O") && (posCheck[4] == "O") && (posCheck[7] == "O"))
|| ((posCheck[2] == "O") && (posCheck[5] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[4] == "O") && (posCheck[8] == "O"))
|| ((posCheck[2] == "O") && (posCheck[4] == "O") && (posCheck[6] == "O"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount2++;
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank.setText("Player (O) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if there has been a tie in the game
else if (tieChecker >= 9) {
prevWinner = ("It's a cat's game!");
tieChecker = 0;
gameDone = true;
turnCounter++;
}
// this makes sure the game doesnt end prematurely
else {
gameDone = false;
}
// this if statement is engaged when the game is done and resets the
// board
if (gameDone == true) {
pane.removeAll();
textField.removeAll();
tieChecker = 0;
init();
posCheck[0] = "";
posCheck[1] = "";
posCheck[2] = "";
posCheck[3] = "";
posCheck[4] = "";
posCheck[5] = "";
posCheck[6] = "";
posCheck[7] = "";
posCheck[8] = "";
posCheck[9] = "";
}// end of reset sequence
turnCounter++;
blank.setText("Games Played: " + gamesPlayed);
}
public static void main(String[] args) {
JFrame baseFrame = new JFrame();
Game gameObject = new Game();
gameObject.init();
baseFrame.setVisible(true);
baseFrame.getContentPane().add(gameObject);
}
}

Run-time error for GUI calculator in Java

I'm creating a GUI calculator, using FlowLayout, GridLayout and BorderLayout. I have the following code.
import java.awt.*;
import javax.swing.*;
//Imports visual components for program
import java.awt.event.*;
//Imports functions for providing performing action on object
public class Calc extends JFrame implements ActionListener {
JPanel[] row = new JPanel[5];
//5 panels are created for 5 rows of buttons
JButton[] button = new JButton[19];
String[] buttonString = {"1","2","3","+","4","5","6","-",
"7","8","9","*",".","/","C","rt","%",
"=", "0"};
double[] temporary = {0,0};
//Two memory locations for current number and upcoming number for signs such as *,/,%,+,-
boolean[] sign = new boolean[5];
//5 values for +,-,*,/,% are stored in array because they expect another number upon invocation
JTextArea display = new JTextArea(1,10);
//Creates display with location specified
Calc(){
//Constructor begins here
setResizable(false);
//Sets calculator size to be fixed at 380x250
//5x5 is created and selected for the calculator
for(int a = 0; a < 5; a++)
sign[a] = false;
//Initialises the state of the signs for +,-,*,/,%
JPanel displaypanel = new JPanel();
JPanel first = new JPanel();
JPanel last = new JPanel();
//Create three panels for buttons to be placed in
displaypanel.setLayout(new FlowLayout());
displaypanel.add(display);
//Display is added
first.setLayout(new GridLayout(3,5));
for(int a = 0; a<15; a++)
first.add(button[a]);
//"first" panel is added
last.setLayout(new GridLayout(1,4));
last.add(button[15]);
last.add(button[16]);
last.add(button[17]);
last.add(button[18]);
JFrame window = new JFrame("Task twelve");
window.setLayout(new BorderLayout());
window.add(displaypanel, BorderLayout.PAGE_START);
window.add(first, BorderLayout.CENTER);
window.add(last, BorderLayout.PAGE_END);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 400);
for(int a = 0; a < 19; a++){
button[a] = new JButton();
button[a].setText(buttonString[a]);
button[a].addActionListener(this);
//Assigns all the numbers and signs for the buttons
}
for(int a = 0; a < 5; a++)
row[a] = new JPanel();
//Initialises JPanel for rows so they can be used
//Assigns size for all buttons and display
display.setEditable(false);
}
public void clear(){
try{
display.setText("");
//Sets the display to be blank
for(int a = 0; a < 5; a++)
sign[a] = false;
//Sets state of all signs to be false
temporary[0] = 0;
temporary[1] = 0;
//Sets temporary values to be 0 as well
} catch(NullPointerException e){
}
}
public void root(){
try{
double temp = Math.sqrt(Double.parseDouble(display.getText()));
//Creates variable that converts the value in display to a double and Sqroots the value
display.setText(Double.toString(temp));
//Converts value in temp to string and copies it to display
} catch(NullPointerException e){
}
}
public void getResult() {
double result = 0;
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(temp0.contains("-")) {
String[] temp2 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp2[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp3 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp3[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}
try {
if(sign[0] == true)
//Addition sign
result = temporary[0] + temporary[1];
else if(sign[1] == true)
//Subtraction sign
result = temporary[0] - temporary[1];
else if(sign[2] == true)
//Multiplication sign
result = temporary[0] * temporary[1];
else if(sign[3] == true)
//Division sign
result = temporary[0] / temporary[1];
else if(sign[4] == true)
//Modulus sign
result = temporary[0] % temporary[1];
display.setText(Double.toString(result));
for(int a = 0; a < 5; a++)
sign[a] = false;
//Sets state of all signs to be false after one of them has been invoked
} catch(NumberFormatException e) {
}
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == button[0])
display.append("1");
//When "1" is pressed, "1" is inserted to the display
if(ae.getSource() == button[1])
display.append("2");
if(ae.getSource() == button[2])
display.append("3");
if(ae.getSource() == button[3]){
//Addition sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[0] = true;
display.setText("");
}
if(ae.getSource() == button[4])
display.append("4");
if(ae.getSource() == button[5])
display.append("5");
if(ae.getSource() == button[6])
display.append("6");
if(ae.getSource() == button[7]){
//Subtraction sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[1] = true;
display.setText("");
}
if(ae.getSource() == button[8])
display.append("7");
if(ae.getSource() == button[9])
display.append("8");
if(ae.getSource() == button[10])
display.append("9");
if(ae.getSource() == button[11]){
//Multiplication sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append(".");
if(ae.getSource() == button[13]){
//Division sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[3] = true;
display.setText("");
}
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15])
root();
if(ae.getSource() == button[16]){
//Modulus sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[4] = true;
display.setText("");
}
if(ae.getSource() == button[17])
getResult();
if(ae.getSource() == button[18])
display.append("0");
}
public static void main(String[] args){
Calc c = new Calc();
}
}
Compiling this doesn't result in any errors. However, running the class does.
Exception in thread"main" java.lang.NullPointerException
at java.awt.Container.addlmpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Calc.<init>(Calc.java:43)
at Calc.main(Calc.java:198)
I don't understand these errors so I do not know how to fix this. Can anyone help?
You are creating 15 buttons in the loop button[a] = new JButton(buttonString[a]); but then you are asking for button[15, 16, ...] (the 16nth, 17nth... button you have not created) and are null.

Categories

Resources