I am trying to learn Java and have created a GUI form that will eventually look like a Yahtzee score sheet. For now, it has all the fields, but when I try to run it, I get the following error:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Board.<init>(FiveDice.java:97)
at FiveDice.main(FiveDice.java:9)
Ideas?
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FiveDice {
public static void main(String[] args)
{
new Board();
} // main
} // FiveDice
class Board extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel l_Ones, l_Twos, l_Threes, l_Fours, l_Fives, l_Sixes,
l_SubtotalT, l_BonusT, l_TotalT;
private JLabel l_ThreeKind, l_FourKind, l_FullHouse, l_SmStr8, l_LgStr8, l_FiveDice,
l_Chance, l_SubtotalB, l_BonusB, l_GrandTotal;
private JTextField Ones, Twos, Threes, Fours, Fives, Sixes,
SubtotalT, BonusT, TotalT;
private JTextField ThreeKind, FourKind, FullHouse, SmStr8, LgStr8, FiveDice,
Chance, SubtotalB, BonusB, GrandTotal;
private JButton btnClear;
public Board() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Six Dice!!");
// Labels - Top Section
l_Ones = new JLabel("1s: ");
l_Twos = new JLabel("2s: ");
l_Threes = new JLabel("3s: ");
l_Fours = new JLabel("4s: ");
l_Fives = new JLabel("5s: ");
l_Sixes = new JLabel("6s: ");
l_SubtotalT = new JLabel("Total: ");
l_BonusT = new JLabel("Bonus: ");
l_TotalT = new JLabel("Grand Total: ");
// Input Fields - Top Section
Ones = new JTextField(2);
Twos = new JTextField(2);
Threes = new JTextField(2);
Fours = new JTextField(2);
Fives = new JTextField(2);
Sixes = new JTextField(2);
SubtotalT = new JTextField(3);
BonusT = new JTextField(3);
TotalT = new JTextField(3);
// Labels - Bottom Section
l_ThreeKind = new JLabel("3 of a Kind: ");
l_FourKind = new JLabel("4 of a Kind: ");
l_FullHouse = new JLabel("Full House: ");
l_SmStr8 = new JLabel("Sm. Straight: ");
l_LgStr8 = new JLabel("Lg. Straight: ");
l_FiveDice = new JLabel("Five Dice: ");
l_Chance = new JLabel("Chance: ");
l_SubtotalB = new JLabel("Total: ");
l_BonusB = new JLabel("Bonus: ");
l_GrandTotal = new JLabel("Grand Total: ");
// Input Fields - Bottom Section
ThreeKind = new JTextField(2);
FourKind = new JTextField(2);
FullHouse = new JTextField(2);
SmStr8 = new JTextField(2);
LgStr8 = new JTextField(2);
FiveDice = new JTextField(2);
Chance = new JTextField(2);
SubtotalB = new JTextField(3);
BonusT = new JTextField(3);
GrandTotal = new JTextField(3);
// Add to Frame - Top Section
add(l_Ones); add(Ones);
add(l_Twos); add(Twos);
add(l_Threes); add(Threes);
add(l_Fours); add(Fours);
add(l_Fives); add(Fives);
add(l_Sixes); add(Sixes);
add(l_SubtotalT); add(SubtotalT);
add(l_BonusT); add(BonusT);
add(l_TotalT); add(TotalT);
// Add to Frame - Bottom Section
add(l_ThreeKind); add(ThreeKind);
add(l_FourKind); add(FourKind);
add(l_FullHouse); add(FullHouse);
add(l_SmStr8); add(SmStr8);
add(l_LgStr8); add(LgStr8);
add(l_FiveDice); add(FiveDice);
add(l_Chance); add(Chance);
add(l_SubtotalB);
add(SubtotalB);
add(l_BonusB);
add(BonusB);
add(l_GrandTotal);
add(GrandTotal);
// Buttons
btnClear = new JButton( "Clear" );
btnClear.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
clear();
}
}); add( btnClear );
setLayout( new FlowLayout() ); // Choose a layout
pack(); // Get rid of extra space
setLocationRelativeTo(null); // Centers the window
setVisible(true);
} // Board Method
private void clear() {
Ones.setText( "" );
Twos.setText( "" );
Threes.setText( "" );
Fours.setText( "" );
Fives.setText( "" );
Sixes.setText( "" );
SubtotalT.setText( "" );
BonusT.setText( "" );
TotalT.setText( "" );
ThreeKind.setText( "" );
FourKind.setText( "" );
FullHouse.setText( "" );
SmStr8.setText( "" );
LgStr8.setText( "" );
FiveDice.setText( "" );
Chance.setText( "" );
SubtotalB.setText( "" );
BonusB.setText( "" );
GrandTotal.setText( "" );
} // clear
} // Board Class
Line 97 is your problem. BonusB is null, so you cannot add it:
add(BonusB);
Related
I'm trying to create a hangman game using the Swing class and Graphics class for a APCS class I have.
I created a JButton that would take the guess typed in by the user and either add it to the "misses" or fill in all of the corresponding letters in the word. I have a separate txt file where I pick a random word from.
When I run the program, all of the components show up, but the button does not do anything. I have been working on this for a few days and don't know what I am doing wrong. I have only learnt how to use the Swing class recently, so it may be a stupid mistake for all I know. I have put all of the code down below.
public class Hangman extends JFrame {
DrawPanel panel = new DrawPanel();
Graphics g = panel.getGraphics();
JTextField guess;
JTextField outputWord;
JTextField missesString;
boolean play;
JButton button = new JButton();
String output = "";
String word;
int misses = 0;
public Hangman() {
int again = 0;
String[] dictionary = new String[1000];
In words = new In("words.txt");
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
app.setSize(500, 500);
for (int i = 0; i < 1000; i++) {
dictionary[i] = words.readLine();
}
do {
int num = (int) (Math.random() * 1000);
word = dictionary[num].toLowerCase();
String answer = word;
word = "";
for (int i = answer.length(); i > 0; i--) {
word = word + "*";
}
int length = answer.length();
app.setLayout(new BorderLayout());
JLabel letter = new JLabel();
letter.setFont(new Font("Arial", Font.BOLD, 20));
letter.setText("Enter Your guess");
guess = new JTextField(10);
JLabel output = new JLabel();
output.setFont(new Font("Arial", Font.BOLD, 20));
output.setText("The Word is");
outputWord = new JTextField(30);
outputWord.setText(word);
outputWord.setEditable(false);
JLabel misses = new JLabel();
misses.setFont(new Font("Arial", Font.BOLD, 20));
misses.setText("Misses:");
missesString = new JTextField(52);
missesString.setEditable(false);
button = new JButton("Guess");
button.addActionListener(new ButtonListener());
JPanel panels = new JPanel();
panels.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.add(letter);
panel1.add(guess);
panel1.add(button);
JPanel panel2 = new JPanel();
panel2.add(output);
panel2.add(outputWord);
JPanel panel3 = new JPanel();
panel3.add(misses);
panel3.add(missesString);
app.add(panel1, BorderLayout.NORTH);
app.add(panel2, BorderLayout.EAST);
app.add(panel3, BorderLayout.SOUTH);
app.add(panels);
app.setVisible(true);
again = JOptionPane.showConfirmDialog(null, "Do you want to play again?");
} while (again == JOptionPane.YES_OPTION);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == guess) {
output = "";
}
for (int i = 0; i <= word.length() - 1; i++) {
if (guess.getText().equalsIgnoreCase(word.substring(i, i + 1))) {
output = output.substring(0, i) + guess + output.substring(i + 1, word.length() - 1);
outputWord.setText(output);
} else {
misses++;
missesString.setText(missesString.getText() + guess + " ");
}
}
}
}
}
The components show up perfectly on the screen, it is only the button that is giving me a hard time by not working as expected.
So I have my if statements to search a .txt file for the currency codes that correspond to the country the user types in. I store those country codes in Strings called 'from' and 'to'. I need to access the results of the if statements which are stored in the 'from' and 'to' variables to plug into something later. When I try to use these in the line way down at the end it says Cannot find symbol 'from' and Cannot find symbol 'to'. How can I fix this?
//all my imports here
public class ExchangeApp {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("Exchange App");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 2, 5, 3));
//GUI Elements
JLabel toLabel = new JLabel("To");
JTextField CurrencyTo = new JTextField(20);
JLabel fromLabel = new JLabel("From");
JTextField CurrencyFrom = new JTextField(20);
JLabel amountLabel = new JLabel("Amount");
JTextField AmountText = new JTextField(20);
JLabel displayLabel = new JLabel();
JLabel updateLabel = new JLabel();
JButton Calculate = new JButton("Calculate");
JButton Clear = new JButton("Clear");
//Add elements to panel
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.add(fromLabel);
panel.add(CurrencyFrom);
panel.add(toLabel);
panel.add(CurrencyTo);
panel.add(amountLabel);
panel.add(AmountText);
panel.add(Calculate);
panel.add(Clear);
panel.add(displayLabel);
panel.add(updateLabel);
//make visible
frame.add(panel);
frame.setVisible(true);
class calculateListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==Calculate){
String line, from, to;
String fromString = CurrencyFrom.getText();
String toString = CurrencyTo.getText();
double amount = Double.parseDouble(AmountText.getText());
try{
//import text file
File inputFile = new File("currency.txt");
//create file scanner
Scanner input = new Scanner(inputFile);
try{
//skip first line
input.nextLine();
//while has next line
while(input.hasNextLine()){
//set line equal to entire line
line = input.nextLine();
String[] countryArray = line.split("\t");
//search for from
if(fromString.equals(countryArray[0])){
//set 'from' equal to that country code
from = countryArray[2];
//testing
System.out.println(from);
}
//search for to
if(toString.equals(countryArray[0])){
//set 'to' equal to that country code
to = countryArray[2];
System.out.println(to);
}
else{
displayLabel.setText("To country not found");
}
}//while loop
}//2nd try
finally{input.close();}
}//1st try
catch(IOException exception){
System.out.println(exception);
}//catch bracket
}//if bracket ****these 2 variables****
String address = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to;
}//action bracket
}//class implements action listener bracket
ActionListener listener = new calculateListener();
Calculate.addActionListener(listener);
}//main bracket
}//class bracket
Every time I click the radio button for in2cm and try to convert, there is nothing showing when I click the convert button. If possible also show me how to use a list box, so I will just put it on a list box and make the GUI much more easier to use.
ButtonGroup convertgroup=new ButtonGroup();
jr=new JRadioButton[10];
jr[0]=new JRadioButton("Inch to Cm");
l1 = new JTextField(25);
l2 = new JTextField(25);
length1 = new JLabel("ft", SwingConstants.LEFT);
length2 = new JLabel("cm", SwingConstants.LEFT);
convertgroup.add(jr[0]);
jr[1]=new JRadioButton("Meter to Feet");
length = new JLabel("m = ", SwingConstants.LEFT);
l1 = new JTextField(25);
l2 = new JTextField(25);
length1 = new JLabel("ft", SwingConstants.LEFT);
length2 = new JLabel("cm", SwingConstants.LEFT);
convertgroup.add(jr[1]);
jr[2]=new JRadioButton("Mile to Km");
Mi2Km = new JTextField(25);
Km2Mi = new JTextField(25);
length3 = new JLabel("Mile", SwingConstants.LEFT);
length4 = new JLabel("Km", SwingConstants.LEFT);
convertgroup.add(jr[2]);
jr[3]=new JRadioButton("Nautical Mile to Km");
Nmi2Km= new JTextField(25);
Km2Nmi= new JTextField(25);
jr[4]=new JRadioButton("League to Km");
Le2Km = new JTextField(25);
Km2Le = new JTextField(25);
submit = new JButton("Convert");
clear = new JButton("Clear");
quit = new JButton("Quit");
submit.addActionListener(this);
clear.addActionListener(this);
quit.addActionListener(this);
converterPanel.add(jr[0]);
converterPanel.add(jr[2]);
converterPanel.add(jr[1]);
converterPanel.add(l1);
converterPanel.add(length);
converterPanel.add(l2);
converterPanel.add(length1);
converterPanel.add(jr[3]);
converterPanel.add(jr[4]);
converterPanel.add(submit);
converterPanel.add(clear);
converterPanel.add(quit);
length.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
Here is the action performed:
public void actionPerformed(ActionEvent event) {
if (event.getSource() == quit) {
System.exit(0);
}
if (event.getSource() == clear) {
l1.setText("");
l2.setText("");
}
if (event.getSource()== submit) {
if(!jr[0].isSelected() && !jr[1].isSelected() && !jr[2].isSelected())
JOptionPane.showMessageDialog(converterFrame,
"No RadioButton has been Selected ", "Warning",
JOptionPane.WARNING_MESSAGE);
if(jr[0].isSelected())
in2cm();
if(jr[1].isSelected()){
lengthConvert();
return;
}
}
}
I have found the problem and fixed it, but how can i change the jlabel every time the jr[0] is selected? because the jlabel in jr[1] is m and feet, and in jr[0] i need to make it in and cm.
I want to write into a file, but It doesn't seem to write into it, the files name is Grade output.txt...
for example when i run the program, the input for quiz 1 : 90.. which is Q1 it supposed to add on the file after stopped running.
'try {
BufferedWriter out = new BufferedWriter(new FileWriter("Grade output.txt"));
//for (int i = 0; i < 11; i++) {
out.write(Q1 + " ");
System.out.println(Q1);
out.close();
} catch (IOException e) {}
'
'
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class AICS_grade_applet extends Applet implements ActionListener {
// Label titleLabel = new Label(" Grading System", Label.CENTER);
Label prelimsQ1Label = new Label("Quiz 1", Label.LEFT);
TextField prelimsQ1Field = new TextField(10);
Label prelimsQ2Label = new Label("Quiz 2", Label.LEFT);
TextField prelimsQ2Field = new TextField(10);
Label prelimsCSLabel = new Label("Quiz 3", Label.LEFT);
TextField prelimsCSField = new TextField(10);
Label prelimsEXLabel = new Label("Quiz 4", Label.LEFT);
TextField prelimsEXField = new TextField(10);
Label midtermQ1Label = new Label("Quiz 5", Label.LEFT);
TextField midtermQ1Field = new TextField(10);
Label midtermQ2Label = new Label("Quiz 6", Label.LEFT);
TextField midtermQ2Field = new TextField(10);
Label midtermCSLabel = new Label("Quiz 7", Label.LEFT);
TextField midtermCSField = new TextField(10);
Label midtermEXLabel = new Label("Quiz 8", Label.LEFT);
TextField midtermEXField = new TextField(10);
Label finalsQ1Label = new Label("Quiz 9", Label.LEFT);
TextField finalsQ1Field = new TextField(10);
Label finalsQ2Label = new Label("Quiz 10", Label.LEFT);
TextField finalsQ2Field = new TextField(10);
Label finalsCSLabel = new Label("Quiz 11", Label.LEFT);
TextField finalsCSField = new TextField(10);
Label finalsEXLabel = new Label("Quiz 12", Label.LEFT);
TextField finalsEXField = new TextField(10);
Button computeButton = new Button(" Compute ");
Button clearButton = new Button(" Clear ");
Label gradeLabel = new Label("Grade: ", Label.RIGHT);
TextField gradeField = new TextField(10);
Label statusLabel = new Label("Status: ", Label.RIGHT);
TextField statusField = new TextField("enter the data", 10);
public void init() { // begin init-------------------------------
setBackground(Color.white);
setForeground(Color.red);
// add(titleLabel);
add(prelimsQ1Label);
add(prelimsQ1Field);
prelimsQ1Field.setForeground(Color.red);
add(prelimsQ2Label);
add(prelimsQ2Field);
prelimsQ2Field.setForeground(Color.red);
add(prelimsCSLabel);
add(prelimsCSField);
prelimsCSField.setForeground(Color.red);
add(prelimsEXLabel);
add(prelimsEXField);
prelimsEXField.setForeground(Color.red);
add(midtermQ1Label);
add(midtermQ1Field);
midtermQ1Field.setForeground(Color.red);
add(midtermQ2Label);
add(midtermQ2Field);
midtermQ2Field.setForeground(Color.red);
add(midtermCSLabel);
add(midtermCSField);
midtermCSField.setForeground(Color.red);
add(midtermEXLabel);
add(midtermEXField);
midtermEXField.setForeground(Color.red);
add(finalsQ1Label);
add(finalsQ1Field);
finalsQ1Field.setForeground(Color.red);
add(finalsQ2Label);
add(finalsQ2Field);
finalsQ2Field.setForeground(Color.red);
add(finalsCSLabel);
add(finalsCSField);
finalsCSField.setForeground(Color.red);
add(finalsEXLabel);
add(finalsEXField);
finalsEXField.setForeground(Color.red);
add(computeButton);
computeButton.addActionListener(this);
add(clearButton);
clearButton.addActionListener(this);
add(gradeLabel);
add(gradeField);
gradeField.setForeground(Color.gray);
add(statusLabel);
add(statusField);
statusField.setForeground(Color.blue);
} // end init
public void actionPerformed(ActionEvent yhan) {
// declare object strings
String strprelimsQ1 = new String(prelimsQ1Field.getText());
String strprelimsQ2 = new String(prelimsQ2Field.getText());
String strprelimsCS = new String(prelimsCSField.getText());
String strprelimsEX = new String(prelimsEXField.getText());
String strmidtermQ1 = new String(midtermQ1Field.getText());
String strmidtermQ2 = new String(midtermQ2Field.getText());
String strmidtermCS = new String(midtermCSField.getText());
String strmidtermEX = new String(midtermEXField.getText());
String strfinalsQ1 = new String(finalsQ1Field.getText());
String strfinalsQ2 = new String(finalsQ2Field.getText());
String strfinalsCS = new String(finalsCSField.getText());
String strfinalsEX = new String(finalsEXField.getText());
if (yhan.getSource() == computeButton)
{
if (strprelimsQ1.equals("")) {
prelimsQ1Field.setText("0");
}
if (strprelimsQ2.equals("")) {
prelimsQ2Field.setText("0");
}
if (strprelimsCS.equals("")) {
prelimsCSField.setText("0");
}
if (strprelimsEX.equals("")) {
prelimsEXField.setText("0");
}
if (strmidtermQ1.equals("")) {
midtermQ1Field.setText("0");
}
if (strmidtermQ2.equals("")) {
midtermQ2Field.setText("0");
}
if (strmidtermCS.equals("")) {
midtermCSField.setText("0");
}
if (strmidtermEX.equals("")) {
midtermEXField.setText("0");
}
if (strfinalsQ1.equals("")) {
finalsQ1Field.setText("0");
}
if (strfinalsQ2.equals("")) {
finalsQ2Field.setText("0");
}
if (strfinalsCS.equals("")) {
finalsCSField.setText("0");
}
if (strfinalsEX.equals("")) {
finalsEXField.setText("0");
}
// Converting input to values
int Q1 = Integer.parseInt(prelimsQ1Field.getText());
int Q2 = Integer.parseInt(prelimsQ2Field.getText());
int Q3 = Integer.parseInt(prelimsQ2Field.getText());
int Q4 = Integer.parseInt(prelimsEXField.getText());
int Q5 = Integer.parseInt(midtermQ1Field.getText());
int Q6 = Integer.parseInt(midtermQ2Field.getText());
int Q7 = Integer.parseInt(midtermQ2Field.getText());
int Q8 = Integer.parseInt(midtermEXField.getText());
int Q9 = Integer.parseInt(finalsQ1Field.getText());
int Q10 = Integer.parseInt(finalsQ2Field.getText());
int Q11 = Integer.parseInt(finalsQ2Field.getText());
int Q12 = Integer.parseInt(finalsEXField.getText());
// Calculations
double grade = (Q1 + Q2 + Q3 + Q4
+ Q5 + Q6 + Q7 + Q8 + Q9 + Q10+ Q11+ Q12) / 12;
try {
BufferedWriter out = new BufferedWriter(new FileWriter("Grade output.txt"));
//for (int i = 0; i < 11; i++) {
out.write(Q1 + " ");
System.out.println(Q1);
out.close();
} catch (IOException e) {}
// Output grade
gradeField.setText("" + Math.round(grade));
if (grade < 75) {
statusField.setText("failed");
} else {
statusField.setText("Pass");
}
if (grade > 100) {
statusField.setText("You may have invalid input");
}
} // end if computeButton
if (yhan.getSource() == clearButton) {
gradeField.setText("");
prelimsQ1Field.setText("");
prelimsQ2Field.setText("");
prelimsCSField.setText("");
prelimsEXField.setText("");
midtermQ1Field.setText("");
midtermQ2Field.setText("");
midtermCSField.setText("");
midtermEXField.setText("");
finalsQ1Field.setText("");
finalsQ2Field.setText("");
finalsCSField.setText("");
finalsEXField.setText("");
statusField.setText("reenter the data");
} // end if clearButton
} // end actionperformed
} // end class
'
Unless signed, an applet cannot write to the file system. You can either sign the applet or deploy re-develop the applet as an application using Java Web Start.
Read:
Signing Applets Using RSA Certificates
Java Applet & Web Start - Code Signing
What Applets Can and Cannot Do
I was wondering how I would be able to account for spaces in my Calculator program. Right now it is set up to only work if there is a space after every value. I want it to be able to work if there is multiple spaces as well. I tried doing something (in my action performed, under the '=' sign test), but it didn't really work. So wanted to know how I could make it account for multiple spaces (like if there are more than one space before the next value, then it should recognize that that is the case, and delete the extra spaces). Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
int counter = 0;
if (text.equals("="))
{
doMath math = new doMath();
for(int i = 0; i <b.length(); i++)
{
String c = b.substring(i,(i+1));
String d = b.substring((i+1),(i+2));
String temp = "";
if( c.equals(" ") && c.equals(d))
{
temp = b.substring(0,i)+(b.substring(i+1));
b = temp;
}
}
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
counter ++;
if(counter <2)
{
b+= " ";
display.setText(b);
}
else
{
b+="";
display.setText(b);
}
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
counter = 0;
}
}
This method requires knowledge of regular expressions. For each string, simply replace any instance of multiple consecutive spaces with a single space. In other words, using regular expressions, you would replace "\\s+", which means "more than one space," with " ", which is just the space character.
Example:
String c = ...
c = c.replaceAll("\\s+", " ");
String str = "your string";
Pattern _pattern = Pattern.compile("\\s+");
Matcher matcher = _pattern.matcher(str);
str = matcher.replaceAll(" ");
Instead of using a substring, use a Scanner which takes a String as a parameter.
Or you can disable the "Space" button after it's pressed, enabling it back, when a different button is pressed.
If b is not empty you could try looking at the previous character using charAt and if it is a space do nothing.