Can't see JDialog components when calling from another JDialog - java

i would like to know how can i see the components in my JDialog when calling it from another one.
I have one jDialog called Cargando1 which has a ProgressBar inside,this jDialog runs a method called iterate() when loading.
Otherwise i have another jDialog called login1, it has a button called btnIngresar, it validates some user and password stuff and then it should call Cargando1.
Also cargando1 calls a Frame called Principal after the progressbar has reach 100% but it doesn't matter.
I would like to know why when i called Cargando1 from Login1 it runs but i can't see the components on it.
Thank you for helping me!
This is the Jdialog called Login1
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login1 extends JDialog implements ActionListener {
private JLabel lblUsuario;
private JTextField txtUsuario;
private JPasswordField jpassContrasena;
private JLabel lblContrasena;
private JButton btnIngresar;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Login1 dialog = new Login1();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Login1() {
setBounds(100, 100, 225, 157);
getContentPane().setLayout(null);
lblUsuario = new JLabel("Usuario:");
lblUsuario.setFont(new Font("Courier New", Font.PLAIN, 11));
lblUsuario.setBounds(10, 12, 80, 20);
getContentPane().add(lblUsuario);
txtUsuario = new JTextField();
txtUsuario.setColumns(10);
txtUsuario.setBounds(101, 11, 95, 20);
getContentPane().add(txtUsuario);
jpassContrasena = new JPasswordField();
jpassContrasena.setBounds(101, 43, 95, 20);
getContentPane().add(jpassContrasena);
lblContrasena = new JLabel("Contrase\u00F1a:");
lblContrasena.setFont(new Font("Courier New", Font.PLAIN, 11));
lblContrasena.setBounds(10, 44, 80, 20);
getContentPane().add(lblContrasena);
btnIngresar = new JButton("Ingresar");
btnIngresar.addActionListener(this);
btnIngresar.setBounds(60, 80, 90, 23);
getContentPane().add(btnIngresar);
}
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() == btnIngresar) {
actionPerformedBtnIngresar(arg0);
}
}
protected void actionPerformedBtnIngresar(ActionEvent arg0) {
char contrasena[] = jpassContrasena.getPassword();
String contrasenadef = new String(contrasena);
if (txtUsuario.getText().equals("Administrador") && contrasenadef.equals("admin"))
{ Principal.sesion = 'A';
JOptionPane.showMessageDialog(this, "Bienvenido, administrador", "Mensaje de bienvenida", JOptionPane.INFORMATION_MESSAGE);
Cargando1 dialog = new Cargando1();
this.dispose();
dialog.setVisible(true);
dialog.iterate();
}
else if (txtUsuario.getText().equals("Vendedor") && contrasenadef.equals("vendedor"))
{ Principal.sesion = 'V';
JOptionPane.showMessageDialog(this, "Bienvenido, vendedor", "Mensaje de bienvenida", JOptionPane.INFORMATION_MESSAGE);
Cargando1 dialog = new Cargando1();
this.dispose();
dialog.setVisible(true);
dialog.iterate();
}
else
{ JOptionPane.showMessageDialog(null, "Por favor ingrese un usuario y/o contraseƱa correctos", "Acceso denegado", JOptionPane.ERROR_MESSAGE);
}
}
}
This is the JDialog called cargando1
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JProgressBar;
public class Cargando1 extends JDialog {
private final JPanel contentPanel = new JPanel();
private JProgressBar pgbCargando;
int porcentaje=0;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Cargando1 dialog = new Cargando1();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.iterate();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Cargando1() {
setBounds(100, 100, 450, 154);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
pgbCargando = new JProgressBar(0,2000);
pgbCargando.setBounds(10, 11, 414, 93);
pgbCargando.setStringPainted(true);
contentPanel.add(pgbCargando);
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
setContentPane(contentPanel);
}
void iterate() {
while (porcentaje < 2000)
{ pgbCargando.setValue(porcentaje);
try {Thread.sleep(100);}
catch (InterruptedException e) { }
porcentaje += 95;
}
Principal formulario1 = new Principal();
formulario1.setLocationRelativeTo(null);
this.dispose();
formulario1.setVisible(true);
}
}

The problem is in the iterate() method. Change your iterate() method to the following and give it a try.
void iterate() {
final Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (porcentaje < 2000) {
pgbCargando.setValue(porcentaje);
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
}
porcentaje += 95;
}
}
});
t.setDaemon(true);
t.start();
}
This will free up the main thread to do gui updates while the ProgressBar's value is modified in the background.

Two things to fix(and a note for the future):
Use Cargando1.setVisible(true) in Cargando1
DO NOT use Thread.sleep for swing, because javax.swing is not thread-safe. Your JDialog will freeze if you use Thread.sleep. Rather, use a Timer(javax.swing) with an ActionListener, or if you really want to use Thread.sleep, look into multithreading.
3. please indent better!!!! usually a new line with an extra 4 spaces after every {

Related

is the method to create simple login wrong

I am a newbie in Java GUI development and I am stuck in the following code.
I am open to suggestions. I am actually trying to create a simple login that gives OK if the password is matched to the number 3124, and otherwise shows the error message. Please help me.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
public class testing {
private JFrame frame;
private JTextField username;
private JTextField password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testing window = new testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public testing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton_1 = new JButton("cancel");
btnNewButton_1.setBounds(266, 181, 109, 56);
frame.getContentPane().add(btnNewButton_1);
username = new JTextField();
username.setBounds(227, 11, 128, 39);
frame.getContentPane().add(username);
username.setColumns(10);
password = new JTextField();
password.setBounds(227, 76, 128, 39);
frame.getContentPane().add(password);
final int num;
num=Integer.parseInt(password);
password.setColumns(10);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(num==3124)
{JOptionPane.showMessageDialog(null, "correct");}
else
{JOptionPane.showMessageDialog(null, "wrong");}
}
});
btnNewButton.setBounds(62, 181, 123, 56);
frame.getContentPane().add(btnNewButton);
}
}
You were checking the password even before the user has had the chance to enter anything into the text box. You need to get and check the value of num in the event listener code i.e. in actionPerformed. Also, don't convert the password to int (someone may enter some non-numeric string).
This code below works better.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
public class Testing {
private JFrame frame;
private JTextField username;
private JTextField password;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Testing window = new Testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Testing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton_1 = new JButton("cancel");
btnNewButton_1.setBounds(266, 181, 109, 56);
frame.getContentPane().add(btnNewButton_1);
username = new JTextField();
username.setBounds(227, 11, 128, 39);
frame.getContentPane().add(username);
username.setColumns(10);
password = new JTextField();
password.setBounds(227, 76, 128, 39);
frame.getContentPane().add(password);
password.setColumns(10);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String num;
num = (password.getText());
if (num.equalsIgnoreCase("3124")) {
JOptionPane.showMessageDialog(null, "correct");
} else {
JOptionPane.showMessageDialog(null, "wrong");
}
}
});
btnNewButton.setBounds(62, 181, 123, 56);
frame.getContentPane().add(btnNewButton);
}
}

JAVA window design is blank

I am making autoclicker as a project and when i open now the window design thingy its shows me just a blank.
im trying to ask from the user to write a number in the spinner
the spinner sending it to the delay.
than you press a key to run the autoclicker and stop him
but i still didnt put the keylistener now im just trying to get output which is the delay from the spinner, not work well till now.
package autoclicker;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.InputEvent;
import java.util.*;
import javax.swing.JFormattedTextField;
public class auto {
static Scanner console = new Scanner(System.in);
private Robot robot;
private int delay;
public void AutoClicker1() {
try
{
robot = new Robot();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void clickMouse(int button)
{
try {
robot.mousePress(button);
robot.delay(10);
robot.mouseRelease(button);
robot.delay(delay);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void setDelay(int delayy)
{
this.delay = delayy;
}
}
THIS IS THE MAIN
package autoclicker;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.lang.Thread;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class autoclicker {
private static KeyEvent e;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
JFrame frame = new JFrame("AutoClicker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.setVisible(true);
frame.setResizable(false);
JPanel Panel = new JPanel();
Panel.setBackground(Color.DARK_GRAY);
Panel.setLayout(null);
JLabel AutoClicker = new JLabel("delay\r\n in ms");
AutoClicker.setBounds(10, 80, 151, 30);
AutoClicker.setForeground(Color.WHITE);
AutoClicker.setFont(new Font("Secular One", Font.PLAIN, 20));
JLabel label = new JLabel("AutoClicker");
label.setForeground(Color.CYAN);
label.setFont(new Font("Secular One", Font.PLAIN, 30));
label.setBounds(10, 11, 200, 57);
Panel.add(label);
JSpinner spinner = new JSpinner();
int Delayy = (int) spinner.getValue();
spinner.setBounds(128, 87, 69, 20);
Panel.add(spinner);
frame.add(Panel);
auto clicker = new auto();
System.out.println("----Auto Clicker----");
System.out.println("Enter delay in ms:");
while(Delayy==0)
{
}
clicker.setDelay(Delayy);
System.out.println("Program will start in 3 seconds.");
try {
System.out.println(3);
Thread.sleep(1000);
System.out.println(2);
Thread.sleep(1000);
System.out.println(1);
Thread.sleep(1000);
}
catch (Exception e)
{
e.printStackTrace();
}
clicker.AutoClicker1();
for(int i = 0; i<100; i++)
{
clicker.clickMouse(InputEvent.BUTTON1_DOWN_MASK);
}
}
}
You need to add your panel to your JFrame.
frame.add(Panel);
Once you add components to your JFrame you then need to setVisibility() to true in order for it to show.
frame.setVisible(true);

How can activate another gui class with JButton

I have two GUI classes named Menu and convert. I want to run the convert class when I click the "open" button. It looks so simple, but I couldn't figure it out.
Menu class
package com.ui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Menu {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnConvert = new JButton("open");
btnConvert.setBounds(44, 52, 89, 23);
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//???
}
});
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnConvert);
}
}
convert class
package com.ui;
import java.awt.EventQueue;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class convert {
private JFrame frmTitle;
private JTextField textField;
private double value;
private ButtonGroup group;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
convert window = new convert();
window.frmTitle.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public convert() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTitle = new JFrame();
frmTitle.setTitle("TITLE");
frmTitle.setBounds(100, 100, 450, 300);
frmTitle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTitle.getContentPane().setLayout(null);
JLabel lblInputValue = new JLabel("Input value:");
lblInputValue.setBounds(29, 22, 79, 14);
frmTitle.getContentPane().add(lblInputValue);
textField = new JTextField();
textField.setBounds(22, 47, 86, 20);
frmTitle.getContentPane().add(textField);
textField.setColumns(10);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Convert", TitledBorder.LEADING, TitledBorder.TOP, null, Color.RED));
panel.setBounds(29, 118, 264, 133);
frmTitle.getContentPane().add(panel);
panel.setLayout(null);
final JRadioButton rdbtnKelvin = new JRadioButton("Kelvin");
rdbtnKelvin.setBounds(6, 30, 67, 23);
panel.add(rdbtnKelvin);
final JRadioButton rdbtnFahrenheit = new JRadioButton("Fahrenheit");
rdbtnFahrenheit.setBounds(71, 30, 77, 23);
panel.add(rdbtnFahrenheit);
final JRadioButton rdbtnCelcius = new JRadioButton("Celcius");
rdbtnCelcius.setBounds(174, 30, 67, 23);
panel.add(rdbtnCelcius);
group = new ButtonGroup();
group.add(rdbtnCelcius);
group.add(rdbtnFahrenheit);
group.add(rdbtnKelvin);
final JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Celcius", "Fahrenheit", "Kelvin"}));
comboBox.setBounds(177, 47, 116, 20);
frmTitle.getContentPane().add(comboBox);
JButton btnConvert = new JButton("CONVERT");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value = Double.parseDouble(textField.getText().toString());
if(comboBox.getSelectedItem().toString().equals("Celcius")){
if(rdbtnCelcius.isSelected()==true){
value = value;
}
else if (rdbtnFahrenheit.isSelected()==true){
value= 1.8*value +32;
}
else{
value =value+273;
}
}
else if (comboBox.getSelectedItem().toString().equals("Fahrenheit")){
if(rdbtnFahrenheit.isSelected()==true){
value = value;
}
else if (rdbtnCelcius.isSelected()==true){
value= (value-32)*1.8;
}
else{
value =(value-32)/1.8+273;
}
}
else{
if(rdbtnCelcius.isSelected()==true){
value = value-273;
}
else if (rdbtnFahrenheit.isSelected()==true){
value= value -273*1.8+32;
}
else{
value =value;
}
}
textField.setText(value +"");
textField.setEnabled(false);
}
});
btnConvert.setBounds(303, 114, 89, 23);
frmTitle.getContentPane().add(btnConvert);
JButton btnClear = new JButton("CLEAR");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField.setEnabled(true);
comboBox.setSelectedIndex(0);
rdbtnKelvin.setSelected(true);
}
});
btnClear.setBounds(303, 170, 89, 23);
frmTitle.getContentPane().add(btnClear);
}
}
First of all, class names and constructors should start with an upper case letter, like you did it for class Menu, but not for class convert.
A Java programm should have just one and only one main method for all classes. So, delete complete your main method from Convert class, put new Convert(); in the actionPerformed() method of btnConvert in Menu class:
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new Convert();
}
});
and add frmTitle.setVisible(true); to the end of the initialize() method of Convert class.
First, your class names should begin with a capital letter, so instead of "convert" it should be "Convert.
Create a public method in Convert:
public JFrame getFrame() {
return frmTitle;
}
Then in your button's actionPerformed() method, just:
Convert w = new Convert();
w.getFrame().setVisible(true);

NullPointException error when setting attributes

I'm getting a NullPointerException error at line 77 lblNewLabel.setVisible(false);
which is called from line 65 runTest(); in the following code. (This is a dummy project I wrote to simulate a problem I'm having in a larger project). What I'm trying to do is change the attribute of several fields, buttons, etc based on user action at various places in the project. I would like to group all the changes in a separate method that can be called from various other methods. I'm still a Java novice, having come from some Visual Basic and Pascal experience. Seems like what I'm trying to do should be straight forward, but for now, I'm at a loss. Thanks in advance for your suggestions.
package woodruff;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class MyTest extends JFrame {
private JPanel contentPane;
private JTextField txtHasFocus;
private JLabel lblNewLabel;
/**
* Create the frame.
*/
public MyTest() {
initialize();
}
private void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 237, 161);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JLabel lblNewLabel = new JLabel("This is a label.");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setHorizontalTextPosition(SwingConstants.CENTER);
lblNewLabel.setBounds(10, 25, 202, 14);
contentPane.add(lblNewLabel);
JButton btnShow = new JButton("Show");
btnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setVisible(true);
}
});
btnShow.setBounds(10, 50, 89, 23);
contentPane.add(btnShow);
JButton btnHide = new JButton("Hide");
btnHide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblNewLabel.setVisible(false);
}
});
btnHide.setBounds(123, 50, 89, 23);
contentPane.add(btnHide);
txtHasFocus = new JTextField();
txtHasFocus.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
// Following results in NullPointerException error
// at woodruff.MyTest.runTest(MyTest.java:77)
runTest();
}
});
txtHasFocus.setHorizontalAlignment(SwingConstants.CENTER);
txtHasFocus.setText("Has Focus?");
txtHasFocus.setBounds(67, 92, 86, 20);
contentPane.add(txtHasFocus);
txtHasFocus.setColumns(10);
}
private void runTest() {
lblNewLabel.setVisible(false);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyTest frame = new MyTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
In the initialize() method, you have created a local variable for JLabel, and hence are not initializing the instance field, as a reason it remains initialized to null, and hence NPE.
final JLabel lblNewLabel = new JLabel("This is a label.");
change the above line to: -
lblNewLabel = new JLabel("This is a label.");

how to close a frame when button clicks

I am new to Java Swing. I am creating a frame with some components.
I have to close the frame and open another frame when the button is clicked. I had tried setVisible(false) but it only hides the frame, not closing it. When I use System.exit(0), it closed all the frames.
I had tried in another way, i.e. add all the components to panel, and add the panel at first. When the frame has to close I just remove those components in actionListener and add the other components for the corresponding next process.
My entire code is as follows:
package JavaApp;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.IllegalBlockSizeException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Login extends JFrame {
public static JLabel labelUser;
public static JLabel labelPass;
public static JTextField textFieldUser;
public static JPasswordField passwordField;
public static JButton clear;
public static JButton buttonLogin;
public static JButton ChangePassword;
public static JButton MasterKey;
public static JButton AppKey;
public static JPanel panelGnereate;
public static JPanel panelLogin;
public static JFrame frame;
public static JLabel UserName;
public static JTextField UserTxt;
public static JButton GenerateKey;
public static JPanel panelMaster;
private static void designUI() {
frame = new JFrame("Instalation");
frame.setLayout(new GridLayout(2, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelLogin = new JPanel();
panelLogin.setLayout(null);
labelUser = new JLabel("Enter UserName");
textFieldUser = new JTextField(10);
labelPass = new JLabel("Enter Password");
passwordField = new JPasswordField(10);
buttonLogin = new JButton("Login");
clear = new JButton("Cancel");
panelLogin.add(buttonLogin);
panelLogin.add(clear);
panelLogin.add(labelUser);
panelLogin.add(textFieldUser);
panelLogin.add(labelPass);
panelLogin.add(passwordField);
textFieldUser.setBounds(200, 120, 100, 20);
labelUser.setBounds(50, 120, 120, 20);
labelPass.setBounds(50, 150, 120, 20);
passwordField.setBounds(200, 150, 100, 20);
buttonLogin.setBounds(70, 180, 100, 20);
clear.setBounds(200, 180, 100, 20);
buttonLogin.addActionListener(actionEvent);
clear.addActionListener(actionEvent);
frame.add(panelLogin);
//Login frame ends...
//Gnereate frame starts here..
panelGnereate = new JPanel();
panelGnereate.setLayout(null);
ChangePassword = new JButton("Change Password");
MasterKey = new JButton("Create Master Key");
AppKey = new JButton("Create Application key");
panelGnereate.add(ChangePassword);
panelGnereate.add(MasterKey);
panelGnereate.add(AppKey);
ChangePassword.setBounds(150, 100, 200, 25);
MasterKey.setBounds(150, 150, 200, 25);
AppKey.setBounds(150, 200, 200, 25);
ChangePassword.addActionListener(actionEvent);
MasterKey.addActionListener(actionEvent);
AppKey.addActionListener(actionEvent);
//Gnerate Frame ends here..
//MasterKey Generate Starts Here..
panelMaster = new JPanel();
panelMaster.setLayout(null);
UserName = new JLabel("Text");
UserTxt = new JTextField(20);
GenerateKey = new JButton("Generate Key");
panelMaster.add(UserName);
panelMaster.add(UserTxt);
panelMaster.add(GenerateKey);
UserName.setBounds(150, 150, 50, 25);
UserTxt.setBounds(220, 150, 100, 25);
GenerateKey.setBounds(180, 180, 150, 25);
GenerateKey.addActionListener(actionEvent);
frame.setSize(500, 500);
frame.setVisible(true);
}
public static void main(String args[]) {
designUI();
}
private static ActionListener actionEvent = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if ("Login".equals(action)) {
System.out.println("Login action" + e.getActionCommand());
if ("".equals(textFieldUser.getText()) || "".equals(passwordField.getText())) {
JOptionPane.showMessageDialog(null,
"Enter Both UserName and Password");
} else if ("admin".equals(textFieldUser.getText()) && "admin".equals(passwordField.getText())) {
System.out.println("login value" + textFieldUser.getText() + " " + passwordField.getText());
frame.remove(panelLogin);
frame.add(panelGnereate);
frame.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,
"Wrong Password");
}
} else if ("Cancel".equals(action)) {
System.out.println(e.getActionCommand());
System.exit(0);
} else if ("Change Password".equals(action)) {
} else if ("Create Master Key".equals(action)) {
frame.remove(panelGnereate);
frame.add(panelMaster);
frame.setVisible(true);
} else if ("Create Application key".equals(action)) {
System.out.println("Message " + UserTxt.getText());
frame.setVisible(false);
}else if("Generate Key".equals(action))
{
try {
new GenerateTxt(UserTxt.getText());
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
frame.remove(panelMaster);
frame.add(panelGnereate);
frame.setVisible(true);
}
}
;
};
}
It's not working for throughout the process. When I click the master key it showing relevant textbox after clicking genearteKey it showing same panel not the previous one. But when I am moving the mouse over there it is showing the components of the both panels.
looking at your code, you'll probably need something like this:
if(frame == null)
frame = new JFrame();
else {
//remove the previous JFrame
frame.setVisible(false);
frame.dispose();
//create a new one
frame = new JFrame();
}
you'll have to put this inside the actionperformed method so that the frame can be removed..
btw, it would be a gd idea to change your class variables from public to private, in accordance with good programming practice..
EDIT: To answer the "flickering" problem.
you're accessing the swing component from outside the event thread. swing widgets arent generally thread safe. as such, u need to modify your main method:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
designUI();
}
});
}
also, refer to Swing component flickering when updated a lot for further queries.
You can send a closing event to the frame/dialog. Like this:
WindowEvent winClosingEvent = new WindowEvent( targetFrame, WindowEvent.WINDOW_CLOSING );
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
I sometimes implement close() method in my frames/dialogs like this:
public void close() {
WindowEvent winClosingEvent = new WindowEvent( this, WindowEvent.WINDOW_CLOSING );
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
}
Hope that helped...
Did you try calling dispose() on the frame? I think that may be what you're looking for.

Categories