Db Query not executing on Button Click - java

I'm having a problem with GUI. When I click on JButton b1, when the text is empty in the JTextField text it does not catch the exception.
The query is executing only once when the button is clicked,if clicked again it throws exception and query is not executing
Code:
public class A extends JFrame{
private JTextField text;
private JButton b1;
private JLabel l1;
private Connection conn;
private Statement state;
private ResultSet set;
String server = "jdbc:mysql://localhost";
String user="tim";
String pass="u";
//query enter in textfield | select * from universty.student where rollno=2
public A() throws ClassNotFoundException, SQLException{
super("Frame");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(server,user,pass);
state = conn.createStatement();
getContentPane().setLayout(null);
text = new JTextField();
text.setBounds(35, 132, 346, 35);
getContentPane().add(text);
l1= new JLabel();
l1.setFont(new Font("Tahoma", Font.PLAIN, 22));
l1.setBounds(35, 305, 384, 27);
getContentPane().add(l1);
b1 = new JButton("Submit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = text.getText();
set = state.executeQuery(query);
set.next();
String answer = set.getString(2);
l1.setText(answer);
}
catch (Exception e){
JOptionPane.showMessageDialog( null,
e.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE );
return;
}
finally{
try{
set.close();
state.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}});
b1.setBounds(132, 178, 129, 35);
getContentPane().add(b1);
setSize(450,450);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
}
Main Method:
public class Main {
public static void main(String args[]) throws ClassNotFoundException, SQLException{
A obj = new A();
}
}

You should open and close the database connection within your:
actionPerformed()
Since when you call your constructor it opens the db connection and closes it again. When you click the db connection is already closed again
public void actionPerformed(ActionEvent arg0) {
conn = DriverManager.getConnection(server,user,pass);
state = conn.createStatement();
//do query here
set.close();
state.close()
conn.close();
}

At the end of the first click, you close everything with following statement.
finally{
try{
set.close();
state.close();
conn.close();
That's why.
__UPDATE__
I am asked to provide a solution. Actually I have given half of the solution by pin-pointing the problem. But let me elaborate more, since I am asked.
Simple solution is not to close connection or statement or whatever. But this would be a bad solution, as unnecessary resources could be hold active. No need for that.
I do not know your application. So I can not give you a precise answer but rather, I can give you some guide lines and help you find the right answer by yourself.
Hold on to the resources, as long as you need them. And get rid of them as soon as you are done with them. For this case, If it is required user to click on that button and make a change in the database, then do not close connection etc but reuse them. If it is a multi-page application, you can close these resource when user moves to another page. (or activity if it a mobile app).
I hope it makes sense =]

I'm not sure of the purpose of your code but you should try and separate your view logic from your business logic. Also allowing a user to run SQL from a text box and submit button sounds dangerous, but if that's really what you want to do, here is one implementation you could use. Note the DAO here is not a true DAO because of the way you want to execute a query
public class A extends JFrame {
private final JTextField text;
private final JButton b1;
private final JLabel l1;
private AService service;
public A() {
super("Frame");
service = new AServiceImpl(new ADAOJDBCImpl());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
text = new JTextField();
text.setBounds(35, 132, 346, 35);
getContentPane().add(text);
l1= new JLabel();
l1.setFont(new Font("Tahoma", Font.PLAIN, 22));
l1.setBounds(35, 305, 384, 27);
getContentPane().add(l1);
b1 = new JButton("Submit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String query = text.getText();
try {
String answer = service.executeQuery(query);
l1.setText(answer);
} catch (SQLException e){
JOptionPane.showMessageDialog( null,
e.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE );
return;
}
}});
b1.setBounds(132, 178, 129, 35);
getContentPane().add(b1);
setSize(450,450);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
pack();
setVisible(true);
}
}
public interface AService {
public String executeQuery(String query) throws SQLException;
}
public class AServiceImpl implements AService {
private ADAO dao;
public AServiceImpl(ADAO dao) {
this.dao = doa;
}
#Override
public String executeQuery(String query) throws SQLException {
return dao.executeQuery();
}
}
/**
* Note usually a DAO is specfically for accessing data, NOT
* for executing User defined queries from a GUI text box
* so it would usually have methods such as add, find, delete, update etc.
*/
public interface ADAO {
public String executeQuery(String query) throws SQLException;
}
public class ADAOJDBCImpl implements ADAO {
#Override
public String executeQuery(String query) throws SQLException {
String server = "jdbc:mysql://localhost";
String user="tim";
String pass="u";
String answer = "":
try (Connection conn = DriverManager.getConnection(server,user,pass);
Statement state = conn.createStatement();
ResultSet set = state.executeQuery(query);) {
if(set.next()) {
answer = set.getString(2);
}
}
return answer;
}
}

Related

Java doubts about ActionEvent

this is my first question on this website.
I have this problem, in this class I have two buttons with two different functions, one to exit and another to put the first and last name in a text field.
I can't get the second ActionEvent to work, please help me, thanks.
import javax.swing.*;
import java.awt.event.*;
public class Prueba1 extends JFrame implements ActionListener{
private JLabel nombre, apellidos,respondo;
private JTextField textfield, textfield1;
private JButton boton,botonoff;
public Prueba1() {
setLayout(null);
nombre = new JLabel("Nombre:");
nombre.setBounds(10, 10, 300, 30);
add(nombre);
apellidos = new JLabel("Apellidos");
apellidos.setBounds(10, 40, 300, 30);
add(apellidos);
textfield = new JTextField();
textfield.setBounds(100,10,150,20);
add(textfield);
textfield1 = new JTextField();
textfield1.setBounds(100,40,150,20);
add(textfield1);
boton = new JButton("¿Que saldrá?");
boton.setBounds(10,80,120,30);
boton.addActionListener(this);
add(boton);
botonoff = new JButton("Salir");
botonoff.setBounds(10,120,120,30);
botonoff.addActionListener(this);
add(botonoff);
respondo = new JLabel("UwU");
respondo.setBounds(160,80,300,30);
add(respondo);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
}
}
public void actionPerformed1(ActionEvent e) {
if(e.getSource() == botonoff) {
System.exit(0);
}
}
public static void main(String args[]) {
Prueba1 clase = new Prueba1();
clase.setVisible(true);
clase.setBounds(0, 0, 500, 500);
clase.setResizable(true);
clase.setLocationRelativeTo(null);
}
}
Remove public void actionPerformed1(ActionEvent e) method and add the body of that method in the else branch in the body of public void actionPerformed(ActionEvent e).
public void actionPerformed(ActionEvent e) {
if (e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
} else if (e.getSource() == botonoff) {
System.exit(0);
}
}
When you provide an ActionListener object to a buttons button.addActionListener(listener)
You have several ways to accomplish this.
button.addActionListener(this);
Is only one way. This way says the the class implements ActionListener.
In effect it implements the
public void actionPerformed(ActionEvent e)
method.
Your
public void actionPerformed1(ActionEvent e)
can't be used by the button at all.
Fortunately there are many other ways to describe the code that should be executed when an action event is produced.
An inner class, static or not. Other class/object.
A lambda expression.
You can find how to express a lambda here.

Deleting data in table (SQLite) through java (Eclipse)

as the title suggests, ive been trying to delete data in a table in my SQLite through the use of a button. I have been able to make it work on another class, but i cant seem to make it work on this specific class which i will show you.
the button is called btnDelete, and the method that loads the database and deletes it is called delete_account.
Button btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
Here's the whole code in the class just in case it is needed:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class AccSettings {
private JFrame frmAccountSett;
private JTextField txtFullname;
private JTextField txtUsername;
private JPasswordField txtPassword;
private int userid;
private String user;
/**
* Create the application.
*/
public AccSettings(String username) {
user=username;
//userid = id;
initialize();
edit_account();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAccountSett = new JFrame();
frmAccountSett.setTitle("Account Settings");
frmAccountSett.setBounds(100, 100, 450, 300);
frmAccountSett.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAccountSett.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Edit Username:");
lblUsername.setBounds(85, 62, 103, 14);
frmAccountSett.getContentPane().add(lblUsername);
txtUsername = new JTextField();
txtUsername.setBounds(229, 59, 137, 20);
frmAccountSett.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(229, 90, 137, 20);
frmAccountSett.getContentPane().add(txtPassword);
JButton btnConfirm = new JButton("Confirm Changes");
btnConfirm.setBounds(146, 164, 137, 29);
frmAccountSett.getContentPane().add(btnConfirm);
JLabel lblPassword = new JLabel("Edit Password:");
lblPassword.setBounds(85, 93, 103, 14);
frmAccountSett.getContentPane().add(lblPassword);
frmAccountSett.setVisible(true);
JButton btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
btnDelete.setBounds(299, 227, 125, 23);
frmAccountSett.getContentPane().add(btnDelete);
JButton btnBack = new JButton("<< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frmAccountSett.dispose();
}
});
btnBack.setBounds(10, 227, 103, 23);
frmAccountSett.getContentPane().add(btnBack);
JLabel lblFullname = new JLabel("Edit Fullname:");
lblFullname.setBounds(85, 31, 103, 14);
frmAccountSett.getContentPane().add(lblFullname);
txtFullname = new JTextField();
txtFullname.setColumns(10);
txtFullname.setBounds(229, 28, 137, 20);
frmAccountSett.getContentPane().add(txtFullname);
btnConfirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
update_account();
}
});
}
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
#SuppressWarnings("deprecation")
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"'"
+ "WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
//load the results
public void edit_account()
{
try {
Connection con; //create a variable for con
Database db = new Database(); //create an instance of database class
con = db.open_connection(); //set con as connection form database class
Statement st;
st = con.createStatement();
//create a statement variable
//create the query that will search the table based on similar terms
String query = "SELECT * FROM tblUsers WHERE userID=" + userid+ "";
//get the resultset of the query (rows)
ResultSet rs = st.executeQuery(query);
if (rs.next())
{
do{
txtFullname.setText(rs.getString(2));
txtUsername.setText(rs.getString(3));
txtPassword.setText(rs.getString(4));
}
while(rs.next());
}
/*
else {
JOptionPane.showMessageDialog(null, "Edit failed");
}
*/
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I believe the problem stems mostly from userID which zephyr has stated. I followed a code from another class(frmEditRef), but that class uses a JScrollPane, which when called from another class (frmMainInterface) looks like this:
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int x = table.getSelectedRow(); //get the current row
int ans = JOptionPane.showConfirmDialog(null, "Do you want to edit this record?");
if (ans == 0) {
//proceed to edit the transaction
//get the id
String id = String.valueOf(model.getValueAt(x, 0));
new EditRef(user,Integer.valueOf(id));
frmUserRef.dispose();
}
}
});
The class im trying to work with does not use JScrollPane. Therefore the coding to it would be different. Here's how it looks like from frmMainInterface:
btnAccountSett.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String id = ;
new AccSettings(user,Integer.valueOf(id));
}
});
As you can see, i have no idea what to put in after the "String id =".
I hope this explanation can get through you guys. I myself am having difficulty trying to explain something i dont even fully understand.

Cant Stop JTextFeild from getting default focus

I have a simple login screen. I want UserName and Password to show up in the first and second text fields until they are clicked on. This functionality is working. However the first text field is always focused when the app launches and therefore shows up as "" until it loses focus. I tried to set a default button and request focus to no avail. It looks like the button is defaulting correctly, but it is not receiving focus for some reason. Anyone know how to fix this?
public class Basics implements ActionListener{
private JFrame frmBasics;
private JTextField userNameFeild;
private JTextField passwordFeild;
private JButton btnSignIn;
private JButton btnSignUp;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Basics window = new Basics();
window.frmBasics.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}//end main
/**
* Create the application.
*/
public Basics() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmBasics = new JFrame();
frmBasics.setTitle("Welcome to the POOPalace!!!");
frmBasics.setBounds(100, 100, 511, 344);
frmBasics.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmBasics.getContentPane().setLayout(null);
userNameFeild = new JTextField("UserName");
userNameFeild.setBounds(148, 79, 214, 20);
userNameFeild.addFocusListener(new FocusedClass());
frmBasics.getContentPane().add(userNameFeild);
userNameFeild.setColumns(10);
passwordFeild = new JTextField("Password");
passwordFeild.setBounds(148, 126, 214, 20);
passwordFeild.addFocusListener(new FocusedClass());
frmBasics.getContentPane().add(passwordFeild);
passwordFeild.setColumns(10);
btnSignIn = new JButton("Sign In");
btnSignIn.setBounds(148, 182, 89, 23);
btnSignIn.addActionListener(this);
frmBasics.getContentPane().add(btnSignIn);
btnSignUp = new JButton("Sign Up");
btnSignUp.setBounds(273, 182, 89, 23);
btnSignUp.addActionListener(this);
frmBasics.getContentPane().add(btnSignUp);
//from what I've been reading these 2 lines should be the solution
//but the request focus seems to not be working
frmBasics.getRootPane().setDefaultButton(btnSignIn);;
btnSignIn.requestFocus();
}
#Override
public void actionPerformed(ActionEvent e) {
//frmBasics.getContentPane().removeAll();
//frmBasics.repaint();
System.out.println(userNameFeild.getText());
System.out.println(passwordFeild.getText());
}//actionPerformed
private class FocusedClass implements FocusListener {
#Override
public void focusGained(FocusEvent arg0) {
if(arg0.getSource().equals(userNameFeild) && userNameFeild.getText().compareTo("UserName") == 0){
userNameFeild.setText("");
}
if(arg0.getSource().equals(passwordFeild) && passwordFeild.getText().compareTo("Password") == 0){
passwordFeild.setText("");
}
}
#Override
public void focusLost(FocusEvent arg0) {
if(userNameFeild.getText().compareTo("") == 0){
userNameFeild.setText("UserName");
}
if(passwordFeild.getText().compareTo("") == 0){
passwordFeild.setText("Password");
}
frmBasics.getContentPane().repaint();
}
}
}//class
Requesting focus works only after the layout of the window is complete.
We need to call the requestFocusInWindow() in one of the three specific situations:
In the windowOpened() method.
In the EventQueue's invokeLater(), which will run after all pending events are processed.
In the overriden JFrame's setVisible() method.
The first option:
//btnSignIn.requestFocusInWindow();
frmBasics.addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
btnSignIn.requestFocusInWindow();
}
});
Also note that requestFocusInWindow() is more portable than
requestFocus().

Listing currently executing SwingWorker and Stop it

I have below SwingWorker;
public class WorkerTrying extends SwingWorker<Void, Void> {
Statement stmt;
Connection con;
ResultSet rs;
String connectionUrl = "jdbc:sqlserver://192.168.131.10;" + "databaseName=SomeDB;" + "user=" + "SomeUser" + ";" + "password=" + "SomeUserPassword" + ";";
public void closeConnection() throws SQLException{
stmt.close();
System.out.println("Closed!!!");
}
protected Void doInBackground() throws Exception {
String query = "Select column1,column2 from Table1"
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()){
//Doing something...
}
return null;
}
public void done() {
}
}
As you can see some DB connection and data fetchinbg via While loop in this worker. My problem is DB Queries takes very long time sometimes. I want add STOP button for closing Statements and Connections in SwingWorker and cancel immediatelly itself.
I am trying below stop button but no help;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
WorkerTrying workerTrying = new WorkerTrying();
workerTrying.cancel(true);
}
Also i have 3-4 SwingWorkers. So i must detect which one is currently running first.
Regards.
==== UPDATE ====
New Stop button like this;
jButtonStop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
for(SwingWorker workerTrying : _workers){
if(!workerTrying.isDone()){
try {
((WorkerTrying)workerTrying).closeConnection();
} catch (SQLException ex) {
Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
}
workerTrying.cancel(true);
}
}
}
}
});
==== SECOND ISSUE UPDATE ====
Start button Action Listener just like this;
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.getText().equals("")){
final SwingWorker workerTrying = new WorkerTrying();
_workers.add(workerTrying);
workerTrying.execute();
}
else{
final SwingWorker workerTrying2 = new WorkerTrying2();
_workers.add(workerTrying2);
workerTrying2.execute();
}
}
});
As you can see some condition for which SwingWorker can be execute.
Than Stop button just like this;
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
for (SwingWorker workerTrying : _workers) {
if(!workerTrying.isDone()){
try {
((WorkerTrying)workerTrying).closeConnection();
} catch (SQLException ex) {
Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
}
workerTrying.cancel(true);
}
}
for (SwingWorker workerTrying2 : _workers) {
if(!workerTrying2.isDone()){
try {
((WorkerTrying2)workerTrying2).closeConnection();
} catch (SQLException ex) {
Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
}
workerTrying2.cancel(true);
}
}
}
});
If First SwingWorker (workerTrying) executed and try stopping, everythings looks ok. Statement closed and SwingWorker canceled succesfully.
But when second SwingWorker (workerTrying2) executed and wanted to Stop, below exception throwed;
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: testproject.MainGui$WorkerTrying2 cannot be cast to testproject.MainGui$WorkerTrying
I used List to track all the Workers. And stopped it all. You can try this.
public class SwingT {
private List<SwingWorker> _workers = new ArrayList<>();
public SwingT(){
JFrame frame = new JFrame("Test Worker");
frame.setSize(320, 160);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JButton btn = new JButton("Add Work");
btn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SwingWorker workerTrying = new WorkerTrying();
_workers.add(workerTrying);
workerTrying.execute();
}
});
JButton btn2 = new JButton("Stop All");
btn2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
for(SwingWorker workerTrying : _workers){
if(!workerTrying.isDone()){
//Close DB Connections
((WorkerTrying)workerTrying).closeConnection();
workerTrying.cancel(true);
}
}
}
});
frame.add(btn);
frame.add(btn2);
frame.setVisible(true);
}
/**
* #param args
*/
public static void main(String[] args) {
new SwingT();
}
}
UPDATE
public class WorkerTrying extends SwingWorker<Void, Void> {
public void closeConnection(){
//Close the connection
System.out.println("closed");
}
..........
}

While loop whithout instruction in Java [duplicate]

This question already has an answer here:
Loop doesn't see value changed by other thread without a print statement
(1 answer)
Closed 7 years ago.
Why this code do not stop when the while loop is empty. If I add an instruction the code work fine. Normally after the the user clicked an button the test variable will be changed so the loop will ends. Is there another way to test that the JDialog was disposed.
public class FenetreAjoutClass extends JDialog {
private JPanel pan = new JPanel();
private JPanel buttPan = new JPanel();
private JTextField schoolLevl = new JTextField();
private JButton valide = new JButton("OK");
private static String infos = null;
private static boolean test = false;
private JButton cancel = new JButton("CANCEL");
FenetreAjoutClass(JFrame parent, Boolean modal) {
valide.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
infos = schoolLevl.getText();
test = true;
dispose();
}
});
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
test = true;
dispose();
}
});
this.setLocationRelativeTo(null);
this.setResizable(true);
this.setLayout(new BorderLayout());
pan.setLayout(new GridLayout(1, 1));
pan.add(schoolLevl);
this.add(pan, BorderLayout.NORTH);
buttPan.add(valide);
buttPan.add(cancel);
this.add(buttPan, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public static void main(String[] args) {
System.out.println(get());
}
public static String get() {
new FenetreAjoutClass(null, false);
while (!test) {
//System.out.println(test);
}
return infos;
}
}
The dispose will free up your memory. All data for the dialog are gone. If you want to show the window later again you have to work with visibility. This can be checked with isVisible().
You can replace the dispose() in your code with this.setVisible(false)
public static String get() {
FenetreAjoutClass dialog = new FenetreAjoutClass(null, false);
while (dialog.isVisible()) {
System.out.println("is Visible");
}
System.out.println("is not Visible");
return infos;
}
Mind that the console will still print "is Visible" over a short time after the dialog is closed. But this is because the console can does not print as quick as the while loop restarts.

Categories