jOption message not closing - java

Hello so apologises if this is a stupid question but i'm struggling to work out why my JoptionPane message is not closing. I'm wanting to use a nested control structure to countup the amount of calculations performed by the user.
I figure it's something to do with how i'm either counting up or how i'm testing to see if the condition has been met to dispose of the calculator frame (i'm going to a new thing that will happen but for now i'm just wanting the whole thing to close)
package ac.uk.valley.forth;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
public class Calculator extends JFrame {
protected static final String operatorButton = null;
private JPanel contentPane;
private JTextField textField;
private double total = 0.0;
private double actualTotal = 0.0;
private char operator;
public int counter = 0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator frame = new Calculator();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Calculator() {
setTitle("Calculator");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 291, 330);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
textField = new JTextField();
textField.setBounds(0, 37, 275, 85);
panel.add(textField);
textField.setColumns(10);
JButton button_10 = new JButton("7");
button_10.setBounds(5, 157, 44, 23);
button_10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("7"));
}
});
panel.add(button_10);
JButton button_11 = new JButton("8");
button_11.setBounds(55, 157, 44, 23);
button_11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("8"));
}
});
panel.add(button_11);
JButton button_12 = new JButton("9");
button_12.setBounds(109, 157, 44, 23);
button_12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("9"));
}
});
panel.add(button_12);
JButton btnOff = new JButton("OFF");
btnOff.setBounds(158, 157, 61, 23);
btnOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// setVisible(false);
// dispose();
}
});
panel.add(btnOff);
JButton button_4 = new JButton("4");
button_4.setBounds(5, 185, 44, 23);
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("4"));
}
});
panel.add(button_4);
JButton button_5 = new JButton("5");
button_5.setBounds(55, 185, 44, 23);
button_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("5"));
}
});
panel.add(button_5);
JButton button_6 = new JButton("6");
button_6.setBounds(109, 185, 44, 23);
button_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("6"));
}
});
panel.add(button_6);
JButton button = new JButton("1");
button.setBounds(5, 213, 44, 23);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("1"));
}
});
panel.add(button);
JButton button_1 = new JButton("2");
button_1.setBounds(55, 213, 44, 23);
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("2"));
}
});
panel.add(button_1);
JButton button_2 = new JButton("3");
button_2.setBounds(109, 213, 44, 23);
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("3"));
}
});
panel.add(button_2);
JButton button_13 = new JButton("0");
button_13.setBounds(5, 240, 44, 23);
button_13.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("0"));
}
});
panel.add(button_13);
JButton button_14 = new JButton(".");
button_14.setBounds(56, 241, 44, 23);
button_14.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("."));
}
});
panel.add(button_14);
JButton btnCe_1 = new JButton("CE");
btnCe_1.setBounds(109, 240, 53, 23);
btnCe_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
});
panel.add(btnCe_1);
JButton equalsButton = new JButton("=");
equalsButton.setBounds(166, 212, 53, 51);
equalsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Calculate();
}
});
panel.add(equalsButton);
final JButton subtractionButton = new JButton("-");
subtractionButton.setBounds(221, 213, 44, 23);
subtractionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// textField.setText(textField.getText().concat("-"));
String operatorText = subtractionButton.getText();
getOperator(operatorText);
}
});
panel.add(subtractionButton);
final JButton moduloButton = new JButton("%");
moduloButton.setBounds(221, 157, 44, 23);
moduloButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// textField.setText(textField.getText().concat("%"));
String operatorText = moduloButton.getText();
getOperator(operatorText);
}
});
panel.add(moduloButton);
final JButton multiplicationButton = new JButton("*");
multiplicationButton.setBounds(167, 185, 44, 23);
multiplicationButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// textField.setText(textField.getText().concat("*"));
String operatorText = multiplicationButton.getText();
getOperator(operatorText);
}
});
panel.add(multiplicationButton);
final JButton divideButton = new JButton("/");
divideButton.setBounds(221, 185, 44, 23);
divideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// textField.setText(textField.getText().concat("/"));
String operatorText = divideButton.getText();
getOperator(operatorText);
}
});
panel.add(divideButton);
final JButton additionButton = new JButton("+");
additionButton.setBounds(221, 240, 44, 23);
additionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String operatorText = additionButton.getText();
getOperator(operatorText);
}
});
panel.add(additionButton);
}
private void getOperator(String operatorButton) {
operator = operatorButton.charAt(0);
total = total + Double.parseDouble(textField.getText());
textField.setText("");
}
public void Calculate() {
switch (operator) {
case '+':
actualTotal = total + Double.parseDouble(textField.getText());
break;
case '-':
actualTotal = total - Double.parseDouble(textField.getText());
break;
case '/':
actualTotal = total / Double.parseDouble(textField.getText());
break;
case '*':
actualTotal = total * Double.parseDouble(textField.getText());
break;
case '%':
actualTotal = total % Double.parseDouble(textField.getText());
break;
}
textField.setText(Double.toString(actualTotal));
total = 0;
counter++;
other(counter);
}
public void other(int counter) {
boolean onGoing = true;
String infoMessage = Integer.toString(counter);
do
{
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + "Calculations Performed",
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.getRootFrame().dispose();
if (counter > 2)
{
onGoing = false;
setVisible(false);
}
} while (onGoing == true);
}
}

You've got a while (true) block completely stomping on the Swing event thread and preventing the JOptionPane from closing:
while (onGoing == true);
Solution: get rid of it; you don't need it, since this is an event-driven program. Instead put that code in your events (your ActionListeners).
Some asides:
While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
Use arrays and ArrayLists as well as for loops to shorten most of this code making for easier coding and debugging.

I have modified the function public void other(int counter) a bit, now the JOptionPane and JFrame both are closing. The int variable counter was always 1. So you needed to increment the value of counter inside the while loop. The String variable infoMessage was required to be inside the loop to reflect the current value of counter. Please have a look at the following:-
public void other(int counter) {
boolean onGoing = true;
do{
String infoMessage = Integer.toString(counter);
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + "Calculations Performed",
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.getRootFrame().dispose();
if (counter >= 2){
onGoing = false;
this.dispose();// JFrame exits
}
counter ++;
} while (onGoing == true);
}
Hope, it serves your purpose.

As you have mentioned that you want to display how many calculations have been performed when user closes the JFrame, here is my solution:
I have removed other(int counter) method which used to display message dialog from inside the loop. I have added a windowClosing listener which displays one and only message when user clicks on cancel button.
Please have a look at the following:-
package ac.uk.valley.forth;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Calculator extends JFrame {
private static final long serialVersionUID = 1L;
protected static final String operatorButton = null;
private JPanel contentPane;
private JTextField textField;
private double total = 0.0;
private double actualTotal = 0.0;
private char operator;
private int calcCount = 0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator frame = new Calculator();
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
JOptionPane.showMessageDialog(null, "Total Calculation performed: " + frame.getCalcCount(),
"Calculations Performed", JOptionPane.INFORMATION_MESSAGE);
}
});
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Calculator() {
setTitle("Calculator");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 291, 330);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
textField = new JTextField();
textField.setBounds(0, 37, 275, 85);
panel.add(textField);
textField.setColumns(10);
JButton button_10 = new JButton("7");
button_10.setBounds(5, 157, 44, 23);
button_10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("7"));
}
});
panel.add(button_10);
JButton button_11 = new JButton("8");
button_11.setBounds(55, 157, 44, 23);
button_11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("8"));
}
});
panel.add(button_11);
JButton button_12 = new JButton("9");
button_12.setBounds(109, 157, 44, 23);
button_12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("9"));
}
});
panel.add(button_12);
JButton btnOff = new JButton("OFF");
btnOff.setBounds(158, 157, 61, 23);
btnOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// setVisible(false);
// dispose();
}
});
panel.add(btnOff);
JButton button_4 = new JButton("4");
button_4.setBounds(5, 185, 44, 23);
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("4"));
}
});
panel.add(button_4);
JButton button_5 = new JButton("5");
button_5.setBounds(55, 185, 44, 23);
button_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("5"));
}
});
panel.add(button_5);
JButton button_6 = new JButton("6");
button_6.setBounds(109, 185, 44, 23);
button_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("6"));
}
});
panel.add(button_6);
JButton button = new JButton("1");
button.setBounds(5, 213, 44, 23);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("1"));
}
});
panel.add(button);
JButton button_1 = new JButton("2");
button_1.setBounds(55, 213, 44, 23);
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("2"));
}
});
panel.add(button_1);
JButton button_2 = new JButton("3");
button_2.setBounds(109, 213, 44, 23);
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("3"));
}
});
panel.add(button_2);
JButton button_13 = new JButton("0");
button_13.setBounds(5, 240, 44, 23);
button_13.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("0"));
}
});
panel.add(button_13);
JButton button_14 = new JButton(".");
button_14.setBounds(56, 241, 44, 23);
button_14.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat("."));
}
});
panel.add(button_14);
JButton btnCe_1 = new JButton("CE");
btnCe_1.setBounds(109, 240, 53, 23);
btnCe_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
});
panel.add(btnCe_1);
JButton equalsButton = new JButton("=");
equalsButton.setBounds(166, 212, 53, 51);
equalsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Calculate();
}
});
panel.add(equalsButton);
final JButton subtractionButton = new JButton("-");
subtractionButton.setBounds(221, 213, 44, 23);
subtractionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// textField.setText(textField.getText().concat("-"));
String operatorText = subtractionButton.getText();
getOperator(operatorText);
}
});
panel.add(subtractionButton);
final JButton moduloButton = new JButton("%");
moduloButton.setBounds(221, 157, 44, 23);
moduloButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// textField.setText(textField.getText().concat("%"));
String operatorText = moduloButton.getText();
getOperator(operatorText);
}
});
panel.add(moduloButton);
final JButton multiplicationButton = new JButton("*");
multiplicationButton.setBounds(167, 185, 44, 23);
multiplicationButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// textField.setText(textField.getText().concat("*"));
String operatorText = multiplicationButton.getText();
getOperator(operatorText);
}
});
panel.add(multiplicationButton);
final JButton divideButton = new JButton("/");
divideButton.setBounds(221, 185, 44, 23);
divideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// textField.setText(textField.getText().concat("/"));
String operatorText = divideButton.getText();
getOperator(operatorText);
}
});
panel.add(divideButton);
final JButton additionButton = new JButton("+");
additionButton.setBounds(221, 240, 44, 23);
additionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String operatorText = additionButton.getText();
getOperator(operatorText);
}
});
panel.add(additionButton);
}
private void getOperator(String operatorButton) {
operator = operatorButton.charAt(0);
total = total + Double.parseDouble(textField.getText());
textField.setText("");
}
public void Calculate() {
switch (operator) {
case '+':
actualTotal = total + Double.parseDouble(textField.getText());
break;
case '-':
actualTotal = total - Double.parseDouble(textField.getText());
break;
case '/':
actualTotal = total / Double.parseDouble(textField.getText());
break;
case '*':
actualTotal = total * Double.parseDouble(textField.getText());
break;
case '%':
actualTotal = total % Double.parseDouble(textField.getText());
break;
}
textField.setText(Double.toString(actualTotal));
total = 0;
calcCount++;
}
public int getCalcCount() {
return calcCount;
}
}
Please tell me whether it solves your problem or not.

Related

having trouble with making custom JOptionPane dialogs

So, before you go and say that I should do more research, I have been trying to figure this out for about a week now and this is kind of my last resort. Moving on, I'm trying to make a dialog box with multiple buttons; a calculator. Although, I don't know almost any of the methods of javax.swing. I only know the JOptionPane method and a little bit of JTextField. Please, if possible, give me a hint or some clues as to what i need to do so that I can figure it out myself. Thanks for your time.
JOptionPane don't have the functionalities you are looking for. If you want a lot of more buttons populating your Dialog you need some other component. Here is a skeleton of a calculator. You have to add the logic:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Calculator extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField textField;
public static void main(String[] args) {
try {
Calculator dialog = new Calculator();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
}
}
public Calculator() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
JOptionPane.showMessageDialog(null, "Bye");
}
});
setBounds(100, 100, 348, 234);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setBounds(12, 13, 323, 19);
contentPanel.add(textField);
textField.setColumns(10);
}
JButton button_8 = new JButton("8");
button_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("8 pressed");
}
});
button_8.setBounds(79, 46, 55, 25);
contentPanel.add(button_8);
JButton button_9 = new JButton("9");
button_9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("9 pressed");
}
});
button_9.setBounds(146, 46, 55, 25);
contentPanel.add(button_9);
JButton button_4 = new JButton("4");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("4 pressed");
}
});
button_4.setBounds(12, 83, 55, 25);
contentPanel.add(button_4);
JButton button_5 = new JButton("5");
button_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("5 pressed");
}
});
button_5.setBounds(79, 83, 55, 25);
contentPanel.add(button_5);
JButton button_6 = new JButton("6");
button_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("6 pressed");
}
});
button_6.setBounds(146, 83, 55, 25);
contentPanel.add(button_6);
JButton button_1 = new JButton("1");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("1 pressed");
}
});
button_1.setBounds(12, 120, 55, 25);
contentPanel.add(button_1);
JButton button_2 = new JButton("2");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("2 pressed");
}
});
button_2.setBounds(79, 120, 55, 25);
contentPanel.add(button_2);
JButton button_3 = new JButton("3");
button_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("3 pressed");
}
});
button_3.setBounds(146, 120, 55, 25);
contentPanel.add(button_3);
JButton button_0 = new JButton("0");
button_0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("0 pressed");
}
});
button_0.setBounds(12, 157, 122, 25);
contentPanel.add(button_0);
JButton button_point = new JButton(".");
button_point.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText(". pressed");
}
});
button_point.setBounds(146, 157, 55, 25);
contentPanel.add(button_point);
JButton button_divide = new JButton("/");
button_divide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("/ pressed");
}
});
button_divide.setBounds(213, 46, 55, 25);
contentPanel.add(button_divide);
JButton button_multiply = new JButton("*");
button_multiply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("* pressed");
}
});
button_multiply.setBounds(213, 83, 55, 25);
contentPanel.add(button_multiply);
JButton button_subtract = new JButton("-");
button_subtract.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("- pressed");
}
});
button_subtract.setBounds(213, 120, 55, 25);
contentPanel.add(button_subtract);
JButton button_sum = new JButton("+");
button_sum.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("+ pressed");
}
});
button_sum.setBounds(213, 157, 55, 25);
contentPanel.add(button_sum);
JButton button_back = new JButton("<");
button_back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("Back pressed");
}
});
button_back.setBounds(280, 46, 55, 25);
contentPanel.add(button_back);
JButton button_clear = new JButton("C");
button_clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("Clear pressed");
}
});
button_clear.setBounds(280, 83, 55, 25);
contentPanel.add(button_clear);
JButton button_equals = new JButton("=");
button_equals.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("= pressed");
}
});
button_equals.setBounds(280, 120, 55, 62);
contentPanel.add(button_equals);
JButton button_7 = new JButton("7");
button_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("7 pressed");
}
});
button_7.setBounds(12, 46, 55, 25);
contentPanel.add(button_7);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
}
}
}
Hope it helps. A clue: this was made using WindowBuiler for Eclipse. You should try it as well.

I need a method that goes back to the previous screen

I need a method so that when the user presses the nextCustomerBtn it will load the previous screen.
Any help would be much appreciated.
This is the extract from class MenuPage
JButton nextCustomerBtn = new JButton("Next Customer");
nextCustomerBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
nextCustomerBtn.setBounds(364, 306, 127, 29);
contentPane.add(nextCustomerBtn);
}
This is the code for the previous screen.
public class Restaurant extends JFrame {
private JPanel contentPane;
private JTextField restaurantTxt;
private JTextField numDiners;
private JTextField numDinersTxt;
private JTextField tableNumTxt;
private JTextField numTable;
private JButton numTableSubBtn;
private JButton proceedMenuBtn;
MenuPage parent;
/**
* Launch the application.
*/
////
public static String tableNumber;
public static String dinerNumber;
////
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Restaurant frame = new Restaurant();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Restaurant() {
super("Restaurant");
parent = new MenuPage();
initGUI();
// numTable = new JTextField("NewUser", 10);
}
public void initGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 840, 368);
contentPane = new JPanel();
contentPane.setBackground(new Color(100, 149, 237));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
restaurantTxt = new JTextField();
restaurantTxt.setHorizontalAlignment(SwingConstants.CENTER);
restaurantTxt.setEditable(false);
restaurantTxt.setText("Matthew's Restaurant");
restaurantTxt.setBounds(340, 23, 191, 20);
contentPane.add(restaurantTxt);
restaurantTxt.setColumns(10);
numDiners = new JTextField("", 10);
numDiners.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) { //method to only allow the textfield to accept numbers, backspace or delete.
char c=e.getKeyChar();
if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
e.consume(); // consume will not allow the user to enter anyhting but a number.
if (e.getKeyCode() == 10) {
JOptionPane.showMessageDialog(Restaurant.this, "Please select a meal");
}
}
}
});
numDiners.setBounds(448, 89, 83, 26);
contentPane.add(numDiners);
numDiners.setColumns(10);
JButton numDinersSubBtn = new JButton("Submit");
numDinersSubBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dinerNumber = numDiners.getText();
numDiners.setText(""); // this sets the textfield to be blank when the submit button is entered.
}
});
numDinersSubBtn.setBounds(612, 89, 83, 29);
contentPane.add(numDinersSubBtn);
numDinersTxt = new JTextField();
numDinersTxt.setEditable(false);
numDinersTxt.setText("Number of diners ?");
numDinersTxt.setBounds(251, 89, 130, 26);
contentPane.add(numDinersTxt);
numDinersTxt.setColumns(10);
tableNumTxt = new JTextField();
tableNumTxt.setEditable(false);
tableNumTxt.setText("Table number ?");
tableNumTxt.setBounds(252, 164, 130, 26);
contentPane.add(tableNumTxt);
tableNumTxt.setColumns(10);
numTable = new JTextField("", 10);
numTable.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c=e.getKeyChar();
if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
e.consume();
//method to only allow the textfield to accept numbers, backspace or delete
if (e.getKeyCode() == 10) { // consume will not allow the user to enter anyhting but a number.
//tableNumber = numTable.getText();
//System.out.println("enter pressed");
}
}
}
});
numTable.setBounds(448, 164, 83, 26);
contentPane.add(numTable);
numTable.setColumns(10);
numTableSubBtn = new JButton("Submit");
numTableSubBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tableNumber = numTable.getText();
numTable.setText("");
}
});
numTableSubBtn.setBounds(612, 164, 83, 29);
contentPane.add(numTableSubBtn);
proceedMenuBtn = new JButton("Proceed to menu");
proceedMenuBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuPage nw = new MenuPage(); // the new visual class window has been created and called MenuPage. The proceedMenuBtn
nw.NewScreen(); // takes the user to the NewScreen.
}
});
proceedMenuBtn.setBounds(608, 265, 135, 29);
contentPane.add(proceedMenuBtn);
JTextPane txtpnWelcomeToMatthews = new JTextPane();
txtpnWelcomeToMatthews.setEditable(false);
txtpnWelcomeToMatthews.setText("Welcome to Matthew's Restaurant\n\nTo get started with your dining experience please enter the number of diners and the table number of your choice.\n\nPress Submit when done.\n\nPress proceed to menu.\n\nEnjoy.");
txtpnWelcomeToMatthews.setBounds(20, 38, 183, 256);
contentPane.add(txtpnWelcomeToMatthews);
}
}

Swing gui disappeared

I am working on a simple GUI with options to add,remove,write to disk etc.. While i was coding my program i came to a problem where the GUI start to disappear and opening only blank frame in the design tab/editor(also in run time), i tried to undo multiple times and it was coming back but this time i am to a point where i cannot do undo anymore. I posted all the code i have. What could be the solution to this problem ?
package nikola.lozanovski.bitola;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class VozenRed extends JFrame {
public VozenRed() {
}
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JButton Delete;
private JButton Transporter;
private JTextField IdBox;
private JTextField InitialBox;
private JTextField FinalBox;
private JTextField Hbox;
private JTextField PriceBox;
private JTextField AgencyBox;
private JTextField SaveBox;
private JTextField Mbox;
private JTextField DeleteBox;
private JTextField DestinationsBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VozenRed frame = new VozenRed();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #return
*/
public void pishi(){ //tried deleting from here
Hashtable<Broj, Elementi> h1=new Hashtable<Broj, Elementi>();
try
{
Broj B=new Broj(IdBox.getText());
Elementi elem=new Elementi(InitialBox.getText(), FinalBox.getText(), Hbox.getText(), Mbox.getText(), PriceBox.getText(), AgencyBox.getText());
h1.put(B , elem);
}
catch(Exception e)//i tried NullPointerException still the same
{
System.out.println("asd");//not realy what i meant
}
} //deleting to here, still no frame
public void VozenRed1() {
setTitle("Transport me");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 502, 396);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton InitialDestination = new JButton("Initial Destination");
InitialDestination.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Input the initial destination, I.E. My Home", "Initial Destination", 2);
}
});
InitialDestination.setBounds(255, 63, 194, 23);
contentPane.add(InitialDestination);
JButton FinalDestination = new JButton("Final Destination");
FinalDestination.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Input final destination, I.E. Your Home", "Final Destination", 2);
}
});
FinalDestination.setBounds(255, 97, 194, 23);
contentPane.add(FinalDestination);
JButton TimeDeparture = new JButton("Departure Time");
TimeDeparture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Input time, Hours in first box, Minutes in second box, I.E. 00:00", "Departure Time", 2);
}
});
TimeDeparture.setBounds(255, 128, 194, 23);
contentPane.add(TimeDeparture);
JButton TicketPrice = new JButton("Ticket Price");
TicketPrice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,"Input price, digits only, I.E. 100","TicketPrice",2);
}
});
TicketPrice.setBounds(255, 159, 194, 23);
contentPane.add(TicketPrice);
Transporter = new JButton("Transport Agency");
Transporter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,"Input transporter name, I.E. MyTrans","Transporter",2);
}
});
Transporter.setBounds(255, 190, 194, 23);
contentPane.add(Transporter);
JButton SaveRoute = new JButton("Save Route");
SaveRoute.setBounds(255, 320, 194, 23);
contentPane.add(SaveRoute);
Delete = new JButton("Delete");
Delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Delete.setBounds(255, 286, 194, 23);
contentPane.add(Delete);
JButton Destinations = new JButton("Destinations");
Destinations.setBounds(255, 252, 194, 23);
contentPane.add(Destinations);
JLabel InputLabel = new JLabel("Input Elements");
InputLabel.setBounds(44, 11, 211, 14);
contentPane.add(InputLabel);
JLabel CommandsLabel = new JLabel("Additional Commands");
CommandsLabel.setBounds(44, 222, 201, 14);
contentPane.add(CommandsLabel);
JButton IdentificationNumber = new JButton("Identification Number");
IdentificationNumber.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Enter Identification number , only numbers, I.E. 0123","IdentificationNumber", 2);
}
});
IdentificationNumber.setBounds(255, 29, 194, 23);
contentPane.add(IdentificationNumber);
JButton ClearAll = new JButton("Clear All");
ClearAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IdBox.setText(null);
InitialBox.setText(null);
FinalBox.setText(null);
Hbox.setText(null);
Mbox.setText(null);
PriceBox.setText(null);
AgencyBox.setText(null);
}
});
ClearAll.setFont(new Font("Tahoma", Font.BOLD, 11));
ClearAll.setBounds(255, 218, 194, 23);
contentPane.add(ClearAll);
JLabel lblHelpButtons = new JLabel("Help Buttons");
lblHelpButtons.setBounds(314, 11, 76, 14);
contentPane.add(lblHelpButtons);
JButton HelpDestinations = new JButton("");
HelpDestinations.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Outputs Destinations in a new box","Destinations", 2);
}
});
HelpDestinations.setBounds(459, 252, 17, 23);
contentPane.add(HelpDestinations);
JButton HelpDelete = new JButton("");
HelpDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Deletes selected Identification","Delete", 2);
}
});
HelpDelete.setBounds(459, 286, 17, 23);
contentPane.add(HelpDelete);
JButton HelpSave = new JButton("");
HelpSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Choose Directory to save","Save Document", 2);
}
});
HelpSave.setBounds(459, 320, 17, 23);
contentPane.add(HelpSave);
JButton HelpClearAll = new JButton("");
HelpClearAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Clears all the boxes above","Clear All", 2);
}
});
HelpClearAll.setBounds(459, 218, 17, 23);
contentPane.add(HelpClearAll);
JButton IdentificationHelpButton = new JButton("");
IdentificationHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IdBox.setText(null);
}
});
IdentificationHelpButton.setBounds(10, 29, 17, 23);
contentPane.add(IdentificationHelpButton);
JButton InitialDestinationHelpButton = new JButton("");
InitialDestinationHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
InitialBox.setText(null);
}
});
InitialDestinationHelpButton.setBounds(10, 60, 17, 23);
contentPane.add(InitialDestinationHelpButton);
JButton FinalDestinationHelpButton = new JButton("");
FinalDestinationHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
FinalBox.setText(null);
}
});
FinalDestinationHelpButton.setBounds(10, 97, 17, 23);
contentPane.add(FinalDestinationHelpButton);
JButton DeparturetimeHelpButton = new JButton("");
DeparturetimeHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Hbox.setText(null);
Mbox.setText(null);
}
});
DeparturetimeHelpButton.setBounds(10, 129, 17, 23);
contentPane.add(DeparturetimeHelpButton);
JButton TicketPriceHelpButton = new JButton("");
TicketPriceHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
PriceBox.setText(null);
}
});
TicketPriceHelpButton.setBounds(10, 159, 17, 23);
contentPane.add(TicketPriceHelpButton);
JButton TransporterHelpButton = new JButton("");
TransporterHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AgencyBox.setText(null);
}
});
TransporterHelpButton.setBounds(10, 190, 17, 23);
contentPane.add(TransporterHelpButton);
JLabel label = new JLabel(" :");
label.setBounds(113, 132, 39, 14);
contentPane.add(label);
JButton SaveDocumentButton = new JButton("");
SaveDocumentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SaveBox.setText(null);
}
});
SaveDocumentButton.setBounds(10, 320, 17, 23);
contentPane.add(SaveDocumentButton);
IdBox = new JTextField();
IdBox.setBounds(44, 30, 201, 20);
contentPane.add(IdBox);
IdBox.setColumns(10);
InitialBox = new JTextField();
InitialBox.setColumns(10);
InitialBox.setBounds(44, 64, 201, 20);
contentPane.add(InitialBox);
FinalBox = new JTextField();
FinalBox.setColumns(10);
FinalBox.setBounds(44, 98, 201, 20);
contentPane.add(FinalBox);
Hbox = new JTextField();
Hbox.setColumns(10);
Hbox.setBounds(44, 129, 86, 20);
contentPane.add(Hbox);
PriceBox = new JTextField();
PriceBox.setColumns(10);
PriceBox.setBounds(44, 160, 201, 20);
contentPane.add(PriceBox);
AgencyBox = new JTextField();
AgencyBox.setColumns(10);
AgencyBox.setBounds(44, 191, 201, 20);
contentPane.add(AgencyBox);
SaveBox = new JTextField();
SaveBox.setColumns(10);
SaveBox.setBounds(44, 321, 201, 20);
contentPane.add(SaveBox);
Mbox = new JTextField();
Mbox.setColumns(10);
Mbox.setBounds(145, 129, 100, 20);
contentPane.add(Mbox);
DeleteBox = new JTextField();
DeleteBox.setColumns(10);
DeleteBox.setBounds(44, 287, 201, 20);
contentPane.add(DeleteBox);
DestinationsBox = new JTextField();
DestinationsBox.setColumns(10);
DestinationsBox.setBounds(44, 253, 201, 20);
contentPane.add(DestinationsBox);
JButton DeleteHelpButton = new JButton("");
DeleteHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DeleteBox.setText(null);
}
});
DeleteHelpButton.setBounds(10, 286, 17, 23);
contentPane.add(DeleteHelpButton);
JButton DestinationHelpButton = new JButton("");
DestinationHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DestinationsBox.setText(null);
}
});
DestinationHelpButton.setBounds(10, 252, 17, 23);
contentPane.add(DestinationHelpButton);
}
}
Looks like your code never calls all that UI stuff in VozenRed1().
You create the VozenRed object, which calls the empty constructor, then you set it to be visible. Never calling VozenRed1().
I think you've missed initComponents() in the constructor of your jframe.

How to change the result "0" on calculator?

I'm new to Java and I'm trying to make a calculator but I have a problem with the result. It is always "0". I used eclipse with Swing. My codes are like this:
package calculator1;
import java.awt.BorderLayout;
public class MainForm extends JFrame {
private JPanel contentPane;
private JTextField textResult;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainForm frame = new MainForm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
double number1=0;
double number2=0;
String islem="";
/**
* Create the frame.
*/
public MainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 509, 534);
contentPane = new JPanel();
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
textResult = new JTextField();
textResult.setEditable(false);
textResult.setBounds(5, 5, 486, 42);
textResult.setColumns(10);
JButton btn1 = new JButton("1");
btn1.setBounds(45, 105, 80, 80);
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"1");
}
});
JButton btn4 = new JButton("4");
btn4.setBounds(45, 185, 80, 80);
btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"4");
}
});
JButton btn7 = new JButton("7");
btn7.setBounds(45, 265, 80, 80);
btn7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"7");
}
});
JButton btn5 = new JButton("5");
btn5.setBounds(125, 185, 80, 80);
btn5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"5");
}
});
JButton btn8 = new JButton("8");
btn8.setBounds(125, 265, 80, 80);
btn8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"8");
}
});
JButton btn2 = new JButton("2");
btn2.setBounds(125, 105, 80, 80);
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"2");
}
});
JButton btn3 = new JButton("3");
btn3.setBounds(205, 105, 80, 80);
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"3");
}
});
JButton btn6 = new JButton("6");
btn6.setBounds(205, 185, 80, 80);
btn6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"6");
}
});
JButton btn9 = new JButton("9");
btn9.setForeground(Color.BLACK);
btn9.setBounds(205, 265, 80, 80);
btn9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"9");
}
});
JButton btn0 = new JButton("0");
btn0.setBounds(125, 345, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(islem.equals(""));
textResult.setText("");
textResult.setText(textResult.getText()+"0");
}
});
JButton btncarp = new JButton("*");
btncarp.setFont(new Font("Tahoma", Font.PLAIN, 35));
btncarp.setBounds(382, 60, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="*";
number1=Double.parseDouble(textResult.getText());
}
});
JButton btnarti = new JButton("+");
btnarti.setFont(new Font("Tahoma", Font.PLAIN, 35));
btnarti.setBounds(285, 265, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="+";
number1=Double.parseDouble(textResult.getText());
}
});
JButton btneksi = new JButton("-");
btneksi.setFont(new Font("Tahoma", Font.PLAIN, 35));
btneksi.setBounds(285, 105, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="-";
number1=Double.parseDouble(textResult.getText());
}
});
JButton btnbolu = new JButton("/");
btnbolu.setFont(new Font("Tahoma", Font.PLAIN, 35));
btnbolu.setBounds(285, 185, 80, 80);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="/";
number1=Double.parseDouble(textResult.getText());
}
});
JButton btnesittir = new JButton("=");
btnesittir.setForeground(new Color(255, 153, 255));
btnesittir.setFont(new Font("Tahoma", Font.PLAIN, 35));
btnesittir.setBounds(285, 345, 80, 80);
btnesittir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
number1=Double.parseDouble(textResult.getText());
number2=Double.parseDouble(textResult.getText());
**double result=0;**
switch (islem) {
case "*":
result=number1*number2;
break;
case "/":
result=number1/number2;
break;
case "+":
result=number1+number2;
break;
case "-":
result=number1-number2;
break;
default:
break;
} //end switch
**textResult.setText(String.valueOf(result));**
islem="";
}
});
contentPane.setLayout(null);
contentPane.add(textResult);
contentPane.add(btn1);
contentPane.add(btn4);
contentPane.add(btn7);
contentPane.add(btn5);
contentPane.add(btn8);
contentPane.add(btn2);
contentPane.add(btn3);
contentPane.add(btn6);
contentPane.add(btn9);
contentPane.add(btn0);
contentPane.add(btncarp);
contentPane.add(btnesittir);
contentPane.add(btnarti);
contentPane.add(btneksi);
contentPane.add(btnbolu);
}
}
What can I write instead of "double result=0;" ?
Or maybe I need to change something else?
You seem to have some serious logic issues, take a look at...
number1 = Double.parseDouble(textResult.getText());
number2 = Double.parseDouble(textResult.getText());
How are these two numbers ever going to be different, you've taken the value from same source (textResult)
You are setting islem to "" every time the user presses a numeric key, so if the user presses 1+2, islem is now ""...
The question now is, how to fix it...
You need to change your logic, rather than waiting till the user presses the = button, you could perform each calculation as the enter the values...
This would mean that you would need some kind of method which could maintain a running result and carry out the required calculations
For example...
protected void performOperation(double value) {
switch (islem) {
case "*":
result *= value;
break;
case "/":
result /= value;
break;
case "+":
result += value;
break;
case "-":
result -= value;
break;
default:
result = value;
} //end switch
islem = "";
textResult.setText(String.valueOf(result));
}
What this does, is takes a value to be calculated, determines what calculation needs to be performed (if any), updates the textResult field and rests the calculate modifier...
You could need to change all your numeric buttons to call this method with the appropriate value, for example...
JButton btn1 = new JButton("1");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performOperation(1);
}
});
Now, in your original code, all of your modifier buttons did nothing...this is because you kept registering there actions to btn0 instead, so you need to fix that...
JButton btneksi = new JButton("-");
//...
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem="-";
number1=Double.parseDouble(textResult.getText());
}
});
They should now set the calculation modifier that they need to use...
JButton btncarp = new JButton("*");
//...
btncarp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem = "*";
}
});
Which should fix the core issues you seem to be having...
You may also want to take a look at How to Use Actions for more details
I just tried to point out your issues that your code has, and
I am sure there are other better ways to solve calculator problem with
less code and more concise
First Major issue, your variable naming is Terrible
For example you named * button , btncarp which does not make sense for whoever will read your code.
Second issue, you add your action listener to button 0 in * , / , and - operation
like
JButton btncarp = new JButton("*"); <---- your button name is btncarp
....
....
btn0.addActionListener(new ActionListener() { <----you add action listener to btn0?!!!
public void actionPerformed(ActionEvent e) {
......
......
}
});
Third issue you never assigned your number1 value , so it turns zero all them time
try this
btnarti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
islem = "+";
number1 = Double.parseDouble(textResult.getText());
textResult.setText(" ");
}
});
Explanation: you will read number1 value and clear the result box and make it ready for second value that you will read inside your operation method
Fourth: you can read your second number which is number2 in = opration ActionListener section and no need to read number1 at that place
like
btnesittir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
number2=Double.parseDouble(textResult.getText());
....
....
}
}
Please choose some sensible name for your variables
Note: your code is almost ok except the issue that I pointed out and you read your number1 and number2 variables in wrong places

I'm Trying To Make A Calculator in Java with a GUI

So I am trying to make a calculator in Java and I have it so that when you clikc the 123456789 or . buttons it will add it to the text field. The problem is that once I add the 6 character it will show "null". Here is my code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import java.awt.Font;
public class Calculator {
private JFrame frame;
private JTextField textField;
//Variables
private double plus;
private double minus;
private double divide;
private double multiply;
//Check for button clicks
private int plusClick;
private int munisClick;
private int multiplyClick;
private int divideClick;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator window = new Calculator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Calculator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 242, 315);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton equalsButton = new JButton("=");
equalsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
equalsButton.setBounds(185, 202, 41, 74);
frame.getContentPane().add(equalsButton);
JButton additionButton = new JButton("+");
additionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
additionButton.setBounds(185, 163, 41, 38);
frame.getContentPane().add(additionButton);
JButton subtractionButton = new JButton("-");
subtractionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
subtractionButton.setBounds(185, 124, 41, 38);
frame.getContentPane().add(subtractionButton);
JButton divideButton = new JButton("/");
divideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
divideButton.setBounds(185, 86, 41, 38);
frame.getContentPane().add(divideButton);
JButton multiplyButton = new JButton("x");
multiplyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
multiplyButton.setBounds(185, 49, 41, 37);
frame.getContentPane().add(multiplyButton);
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setBounds(0, 0, 226, 49);
frame.getContentPane().add(textField);
textField.setColumns(10);
final JButton zeroButton = new JButton("0");
zeroButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText()+zeroButton.getText());
}
});
zeroButton.setBounds(10, 231, 137, 34);
frame.getContentPane().add(zeroButton);
final JButton one = new JButton("1");
one.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + one.getText());
}
});
one.setBounds(10, 193, 41, 34);
frame.getContentPane().add(one);
final JButton two = new JButton("2");
two.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + two.getText());
}
});
two.setBounds(56, 193, 41, 34);
frame.getContentPane().add(two);
final JButton three = new JButton("3");
three.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + three.getText());
}
});
three.setBounds(106, 193, 41, 34);
frame.getContentPane().add(three);
final JButton four = new JButton("4");
four.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + four.getText());
}
});
four.setBounds(10, 153, 41, 34);
frame.getContentPane().add(four);
final JButton five = new JButton("5");
five.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + five.getText());
}
});
five.setBounds(56, 153, 41, 34);
frame.getContentPane().add(five);
final JButton six = new JButton("6");
six.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getSelectedText() + six.getText());
}
});
six.setBounds(106, 153, 41, 34);
frame.getContentPane().add(six);
final JButton seven = new JButton("7");
seven.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + seven.getText());
}
});
seven.setBounds(10, 116, 41, 34);
frame.getContentPane().add(seven);
final JButton eight = new JButton("8");
eight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + eight.getText());
}
});
eight.setBounds(56, 116, 41, 34);
frame.getContentPane().add(eight);
final JButton nine = new JButton("9");
nine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + nine.getText());
}
});
nine.setBounds(106, 116, 41, 34);
frame.getContentPane().add(nine);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
});
clearButton.setBounds(10, 67, 87, 38);
frame.getContentPane().add(clearButton);
final JButton decimalButton = new JButton(".");
decimalButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
textField.setText(textField.getText() + decimalButton.getText());
}
});
decimalButton.setFont(new Font("Tahoma", Font.PLAIN, 20));
decimalButton.setBounds(106, 67, 41, 38);
frame.getContentPane().add(decimalButton);
}
}
How to I get it to display all the numbers without giving me "null".
Thanks!
final JButton six = new JButton("6");
six.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getSelectedText() + six.getText());
}
});
should be
final JButton six = new JButton("6");
six.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + six.getText());
}
});
As no text is selected when the button is pushed, it returns null, which is then converted to a string and then has "6" appended to it.
Simple. If you just compare your 6 button to the rest of your buttons, you'll notice you're doing something different in the ActionListener. Change the following:
textField.setText(textField.getSelectedText() + six.getText());
to
textField.setText(textField.getText() + six.getText());
Also, I highly recommend that you go through A Visual Guide to Layout Managers before you run into problems using a null layout.

Categories