I developed a program to learn how log-in works. I've got a window(jFrame) where you can login with a button on it "create new account". If you click this butten, the login window closes and the create acc. window(another file) opens up. I want it to reopen the login window after you've created your acc.
My Problem:
I don't know how to reopen the login window. Be it by restarting the mainmethod or somethingelse, which you guys can tell me hopefully .
First window
public class password extends javax.swing.JFrame {
public password() {
initComponents();
}
private void initComponents() {
jButton1 = new javax.swing.JButton();
[some more Elements...]
jButton1.setText("Create an account");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
[more layoutstuff...]
}
//event where it opens the new window and closes the login window
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
register reg = new register();
reg.register();
dispose();
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(password.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(password.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(password.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(password.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new password().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
[more elements...]
}
second window
public class register extends javax.swing.JFrame {
public register() {
initComponents();
}
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
[again more elements and layoutstuff...]
}
public static void register() {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new register().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
[more elements]
}
Please excuse me for my question but I am very new to programming.
You could just hide and then show the login window later or you could roll up a new login window.
Related
private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {
Welcome a= new Welcome();
a.setVisible(true);
a.setDefaultCloseOperation(Welcome.DISPOSE_ON_CLOSE);
try {
// TODO add your handling code here:
DBManage db = new DBManage();
if(db.checkUser(textUsername.getText(), textPassword.getText())){
MESSAGE.setText("Login Successful");
}else{
MESSAGE.setText("Wrong Password or Username");
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LoginForm().setVisible(true);
}
});
}
I have this loginform jframe after I have logged in
The welcome frame will pop up, but the loginform is still there.
How do I programmatically close that?
Thank you, I am still a beginner in programming.
You would have to close the login form like so:
public void close(){
WindowEvent winClosingEvent = new WindowEvent(this,WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}
So call this method after setting the new frame to visible like this:
private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
DBManage db = new DBManage();
if(db.checkUser(textUsername.getText(), textPassword.getText())){
Welcome a= new Welcome();
a.setVisible(true);
a.setDefaultCloseOperation(Welcome.DISPOSE_ON_CLOSE);
MESSAGE.setText("Login Successful");//I think this line will not be necessary here.
close(); //<-----------------------------HERE
}else{
MESSAGE.setText("Wrong Password or Username");
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
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");
}
..........
}
I have an application I'm making for a game to automatically update a game client.
Once you press Launch, it will open up my DownloadFrame (extends JDialog), and will look like this:
If you click the icon for the application in the taskbar, (maybe Windows 8 is the problem?) it will minimize the application like usual. However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent. It looks like this:
Here's my code for my extension of JDialog. Apologies in advance for it being messy.
public class DownloadFrame extends JDialog implements Runnable {
private static final long serialVersionUID = -8764984599528942303L;
private Background frame;
private ImageIcon[] gifs;
private JLabel spinner;
public DownloadFrame() {
super(Loader.application, false);
setLayout(null);
setUndecorated(true);
setAutoRequestFocus(true);
new Thread(this).start();
generateBackground();
generateButton();
generateGif();
}
private void generateBackground() {
frame = new Background("sub_background.png");
setSize(frame.getWidth(), frame.getHeight());
setBackground(new Color(1.0f, 1.0f, 1.0f, 0.0f));
setLocationRelativeTo(null);
setLocation(this.getX(), this.getY() + 5);
setLayout(null);
setContentPane(frame);
}
private void generateGif() {
gifs = Utils.generateGifImages();
spinner = new JLabel(gifs[0]);
spinner.setBounds(70, 30, gifs[0].getIconWidth(), gifs[0].getIconHeight());
add(spinner);
}
private HoverableButton cancel;
public HoverableButton getCancelButton() {
return cancel;
}
private void generateButton() {
cancel = new HoverableButton(Settings.CANCEL_BUTTON, 75, 145);
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
/*
* TODO -
* stop the download in progress
*/
for (HoverableButton button : Loader.application.getPrimaryButtons()) {
button.setActive(true);
button.setVisible(true);
}
dispose();
}
});
add(cancel);
}
private int cycleCount;
private void cycleGif() {
if (spinner == null) {
return;
}
cycleCount++;
if (cycleCount > 7) {
cycleCount = 0;
}
spinner.setIcon(gifs[cycleCount]);
}
#Override
public void run() {
while (true) {
cycleGif();
try {
Thread.sleep(100L);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
In case it's needed, here's my usage of it. Most of the stuff can be ignored I'm sure, it's simply there to hide the four buttons while the download is in progress.
((HoverableButton) components[2]).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
HoverableButton source = (HoverableButton) components[2];
if (source.isActive()) {
try {
Thread.sleep(500L);
} catch (Exception ex) {
ex.printStackTrace();
}
if (panel == null) {
panel = new DownloadFrame();
panel.setVisible(true);
} else {
panel.setVisible(true);
panel.getCancelButton().removeHighlight();
}
for (HoverableButton button : getPrimaryButtons()) {
button.setActive(false);
button.setVisible(false);
button.removeHighlight();
}
/*
* TODO -
* handle checking for updates / downloading updates
*/
}
}
});
However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent
Yes. When you create the JDialog, you need to specify the "owner" JFrame of the dialog in the constructor.
So you must create and make the JFrame and make the frame visible before you create the dialog.
I want to disable a button on the frame from a JDialog, I tried everything but it won't work. The program's execution starts from a frame and when the button is clicked the Dialog pops up. Simple, when you click the button on the dialog the frame's button should get disabled and the dialog will close.
BTW: everything works, its just the frame's button that does not get disabled!
PS: I am coding this on NetBeans so i have removed unnecessary coding for the sake of simplicity.
Here is the coding for the frame:
public class Frame extends javax.swing.JFrame {
Dialog D = new Dialog(this, true);
public Frame(){
setTitle("Frame");
initComponents();
setResizable(false);
}
void buttonDisable(){
Btn1.setEnabled(false);
}
private void Btn1ActionPerformed(java.awt.event.ActionEvent evt) {
D.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JButton Btn1;
// End of variables declaration
}
Here is the coding for the JDialog Box:
public class Dialog extends javax.swing.JDialog {
public Dialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
setTitle("Dialog");
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new Frame().buttonDisable();
dispose();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Dialog dialog = new Dialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
I haven't run this through an IDE. But I'm fairly confident that calling the buttonDisable() on a new Frame() instead of calling it on the actual parent frame is your problem.
You need to save your "parent" in your Dialog so you can access it later on and do something like this in your Dialog.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
parentFrame.buttonDisable();
dispose();
}
So your complete code would look like this:
public class Frame extends javax.swing.JFrame {
Dialog d = new Dialog(this, true);
public Frame(){
setTitle("Frame");
initComponents();
setResizable(false);
}
void buttonDisable(){
Btn1.setEnabled(false);
}
private void Btn1ActionPerformed(java.awt.event.ActionEvent evt) {
d.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JButton Btn1;
// End of variables declaration
}
and the dialog would look like this
public class Dialog extends javax.swing.JDialog {
private Frame parentFrame;
public Dialog(Frame parent, boolean modal) {
super(parent, modal);
initComponents();
setTitle("Dialog");
this.parentFrame=parent;//hold reference to the parent
this.setVisible(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.parentFrame.buttonDisable();//invoke method on the parent reference
dispose();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
hope you can help.
I'm hoping this isn't just a bug and that we can solve it.
I currently have a Java program with a JComboBox. When the user changes the selected item in the combo box a JOptionPane appears to allow the user to confirm the change.
When the new selection is made in the combo box, the JOptionPane appears as desired but you have to click it twice to use it. That is, click it once to gain focus and then click the button you want to use. Another method is to click within the bounds of the program's GUI (behind the optionPane) and then click the button.
No Exceptions occur, and the program functions as normal once the buttons are clicked.
This functionality only occurs using the Nimbus LookAndFeel and not with the native macos laf (building on mac, haven't tested on windows) but I need to use nimbus for other reasons.
I've been looking through the Nimbus issue tracking but have yet to find the fault.
I have JButton which calls the SAME code (ie JOptionPane.showConfirmDialog(...) and this works perfectly, it's just when it's called from the action of the combo box.
Really hope you can help!
Cheers in advance!
import javax.swing.UIManager.*;
import javax.swing.*;
public class TestJavaProblem extends JFrame {
JComboBox jComboBox1;
public TestJavaProblem() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
jComboBox1 = new JComboBox();
//give it some values
jComboBox1.setModel(new DefaultComboBoxModel(new String[] { "1", "2"}));
//add listener
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) { fireTask(evt);}
});
this.add(jComboBox1);
pack();
}
private void fireTask(java.awt.event.ItemEvent evt) {
if (evt.getStateChange() == 1) { //so dialog fires only once
int i = JOptionPane.showConfirmDialog(jComboBox1, "Message Text", "Title", JOptionPane.OK_CANCEL_OPTION);
System.out.println("Result:" + i);
}
}
public static void main(String args[]) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {/*no nimbus*/}
new TestJavaProblem().setVisible(true);
}
}
don't use magic number,
if (evt.getStateChange() == 1) { //so dialog fires only once
or
int i = JOptionPane.showConfirmDialog(jComboBox1,
here is workaround code, but seems like required for MetalLookAndFeel, Substance on Windows OS
import javax.swing.UIManager.*;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class TestJavaProblem extends JFrame {
private static final long serialVersionUID = 1L;
private JComboBox jComboBox1;
private boolean boloComboBox = false;
public TestJavaProblem() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
jComboBox1 = new JComboBox();
jComboBox1.setModel(new DefaultComboBoxModel(new String[]{"1", "2"}));
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
#Override
public void itemStateChanged(final java.awt.event.ItemEvent evt) {
if (jComboBox1.isPopupVisible()) {
jComboBox1.setPopupVisible(false);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
fireTask(evt);
}
});
}
}
});
jComboBox1.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
System.out.println(e.getSource());
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
System.out.println(e.getSource());
}
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
System.out.println(e.getSource());
}
});
add(jComboBox1);
pack();
}
private void fireTask(java.awt.event.ItemEvent evt) {
if (evt.getStateChange() == 2) {
int i = JOptionPane.showConfirmDialog(jComboBox1,
"Message Text", "Title", JOptionPane.OK_CANCEL_OPTION);
System.out.println("Result:" + i);
}
}
public static void main(String args[]) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestJavaProblem().setVisible(true);
}
});
}
}