I need a method that goes back to the previous screen - java

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);
}
}

Related

this.dispose() is not working to close a JFrame

When I add:
this.dispose();
The window is not closing, what can I do?.
I use Eclipse with windowsBuilder.
I want to close the actual window to open another window.
My code:
public class Ventana_login extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7948060398287723741L;
private JPanel contentPane;
private JTextField txtUsuario;
private JPasswordField txtContrasena;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ventana_login frame = new Ventana_login();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Ventana_login() {
setTitle("Sistema Gestor de Eventos v1.0");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblBienvenidoAlSistema = new JLabel("Bienvenido");
lblBienvenidoAlSistema.setHorizontalAlignment(SwingConstants.CENTER);
lblBienvenidoAlSistema.setFont(new Font("Tahoma", Font.BOLD, 16));
lblBienvenidoAlSistema.setBounds(10, 11, 424, 14);
contentPane.add(lblBienvenidoAlSistema);
JLabel lblUsuario = new JLabel("Usuario");
lblUsuario.setHorizontalAlignment(SwingConstants.RIGHT);
lblUsuario.setBounds(96, 79, 70, 14);
contentPane.add(lblUsuario);
JLabel lblContrasena = new JLabel("Contrase\u00F1a");
lblContrasena.setHorizontalAlignment(SwingConstants.RIGHT);
lblContrasena.setBounds(96, 109, 70, 14);
contentPane.add(lblContrasena);
txtUsuario = new JTextField();
txtUsuario.setBounds(176, 76, 150, 20);
contentPane.add(txtUsuario);
txtUsuario.setColumns(10);
JButton btnIniciarSesion = new JButton("Iniciar Sesi\u00F3n");
btnIniciarSesion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Dato_login d_lgn = new Dato_login();
Logica_login l_lgn = new Logica_login();
d_lgn.setUsuario(txtUsuario.getText());
char[] contrasenaChar = txtContrasena.getPassword();
String contrasenaClean = new String(contrasenaChar);
d_lgn.setContrasena(contrasenaClean);
Dato_login d_lgn2 = l_lgn.login(d_lgn.getUsuario(), d_lgn.getContrasena());
if (Logica_login.resultado) {
Ventana_menu v_menu = new Ventana_menu();
v_menu.setVisible(true);
v_menu.setLocationRelativeTo(null);
Ventana_menu.lblPerfilActual.setText(d_lgn2.getPerfil());
Ventana_menu.lblApellidoActual.setText(d_lgn2.getApellido());
Ventana_menu.lblNombreActual.setText(d_lgn2.getNombre());
Ventana_menu.lblUsuarioActual.setText(d_lgn2.getUsuario());
if (Ventana_menu.lblPerfilActual.getText().equals("Portero")) {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(false);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(false);
Ventana_menu.btnReportes.setEnabled(true);
} else {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(true);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(true);
Ventana_menu.btnReportes.setEnabled(true);
}
this.dispose();
} else {
JOptionPane.showMessageDialog(contentPane, "Acceso Denegado", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Exception:\n" + e, "Error: Ventana_login", JOptionPane.ERROR_MESSAGE);
}
}
});
btnIniciarSesion.setBounds(176, 163, 150, 30);
contentPane.add(btnIniciarSesion);
I will assume by window you mean JFrame:
then do:
myJframe.dispatchEvent(new WindowEvent(myJframe, WindowEvent.WINDOW_CLOSING));

jOption message not closing

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.

How to filter out some data from array list to list field in java

I'm trying to filter data in my array list according to my comboBox selected item wise. I still can't solve this problem.
public class FoodItem {
private String name;
private String type;
public FoodItem(String n,String t){
name=n;
type=t;
}
public String getType(){
return type;
}
public String getName(){
return name;
}
}
sample.java
<code>
public class A2Demo extends JFrame {
private JPanel contentPane;
private JTextField txtName;
List listFoodItem = new List();
JComboBox comboType = new JComboBox();
FoodItem[] foodItems;
private final JTextField txtBudget = new JTextField();
private final JButton btnBudget = new JButton("Search Budget");
private final JTextField textField = new JTextField();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
A2Demo frame = new A2Demo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public A2Demo() {
textField.setBounds(93, 247, 134, 28);
textField.setColumns(10);
txtBudget.setBounds(183, 11, 86, 20);
txtBudget.setColumns(10);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 334);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
foodItems=new FoodItem[2];
foodItems[0]=new FoodItem("Chicken Cutlet","Main");
foodItems[1]=new FoodItem("Chendol","Dessert");
comboType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
comboType.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
JOptionPane.showMessageDialog(null,comboType.getSelectedItem());
}
});
comboType.setBounds(32, 11, 93, 20);
contentPane.add(comboType);
for(int i=0; i<foodItems.length; i++)
comboType.addItem(foodItems[i].getType());
listFoodItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
txtName.setText(listFoodItem.getSelectedItem());
}
});
listFoodItem.setBounds(37, 63, 330, 125);
contentPane.add(listFoodItem);
JLabel lblName = new JLabel("Name");
lblName.setBounds(37, 217, 46, 14);
contentPane.add(lblName);
txtName = new JTextField();
txtName.setBounds(93, 214, 134, 20);
contentPane.add(txtName);
txtName.setColumns(10);
contentPane.add(txtBudget);
btnBudget.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, comboType.getSelectedItem()+ " "+txtBudget.getText());
}
});
btnBudget.setBounds(280, 10, 127, 23);
contentPane.add(btnBudget);
contentPane.add(textField);
}
}
i want to display food name in the list. but combobox changeing to different type my list need to change according l

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.

Clicking on JButton(Bubble Sort) clears the JTextField.Why?

public class Sort_BenchMark extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnBubbleSort;
private JLabel label_1;
private JButton btnGenerate;
private JButton btnSelectionSort;
private JLabel lblSs;
private JLabel lblStatus;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Sort_BenchMark frame = new Sort_BenchMark();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sort_BenchMark()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField("Enter ");
textField.setForeground(Color.GRAY);
textField.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
});
textField.setBounds(29, 30, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
label_1 = new JLabel("");
label_1.setBounds(334, 20, 120, 30);
contentPane.add(label_1);
btnBubbleSort = new JButton("Bubble Sort");
btnBubbleSort.setBounds(204, 20, 120, 30);
contentPane.add(btnBubbleSort);
btnSelectionSort = new JButton("Selection Sort");
btnSelectionSort.setBounds(204, 70, 120, 30);
contentPane.add(btnSelectionSort);
lblSs = new JLabel("");
lblSs.setBounds(334, 70, 120, 30);
contentPane.add(lblSs);
lblStatus = new JLabel("");
lblStatus.setBounds(75, 87, 93, 23);
contentPane.add(lblStatus);
final JRadioButton rdbtnAvgCase = new JRadioButton("Avg Case");
rdbtnAvgCase.setBounds(29, 150, 109, 23);
contentPane.add(rdbtnAvgCase);
ButtonGroup b = new ButtonGroup();
b.add(rdbtnAvgCase);
btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnBubbleSort.setEnabled(true);
btnSelectionSort.setEnabled(true);
final String s = textField.getText();
if(s.contentEquals(""))
{
lblStatus.setText("Enter length");
}
else
{
lblStatus.setText("Ready");
if(rdbtnAvgCase.isSelected())
{
btnBubbleSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
btnBubbleSort.setEnabled(false);
label_1.setText("done");
btnBubbleSort.setEnabled(true);
}
});
t1.start();
}
});
btnSelectionSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t3 = new Thread(new Runnable()
{
#Override
public void run()
{
btnSelectionSort.setEnabled(false);
lblSs.setText("done");
btnSelectionSort.setEnabled(true);
}
});
t3.start();
}
});
}
}
}
});
btnGenerate.setBounds(64, 62, 88, 25);
contentPane.add(btnGenerate);
}
}
The above code is about Swing.
The actual code how i designed is:-(In the frame)
Select the Average Case (RadioButton)
Enter any number in textfield (Enter)
click on generate
click on any sort button(Bubble Sort and Selection Sort)
Now, whats the problem is, If I click on BubbleSort the text field gets cleared. But it should not happen as per I designed. Can anyone suggest me the solution so that text field wont get clear after entered anything in it?
These lines here:
#Override
public void focusGained(FocusEvent e) {
textField.setText(""); //HERE
textField.setForeground(Color.BLACK);
}
in the focus listener code says that when you click in the textfield then set its text to a empty string.
Firstly, horrible nested ActionPerformed you've got there.
That aside, Vincent Ramdhanie is right as to where the problem is originating. The reason why it only happens when you click a certain button, is because when you disable a button, then it cannot have focus, which forces the focus to be on something else, which in the disable-btnBubbleSort's case, appears to be your textfield.
Instead of btnSelectionSort.setEnabled(false) and btnSelectionSort.setEnabled(true), try using setVisible(false) and setVisible(true).
If that doesn't work, drop the onfocus-part, and do something with a mouse-click event instead.

Categories