JAVA window design is blank - java

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

Related

Can't see JDialog components when calling from another JDialog

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 {

Why won't the JButtons, JLabels and JTextFields be displayed?

This code enables an employee to log in to the coffee shop system. I admit I have a lot of unneeded code. My problem is that when I run the program just the image is displayed above and no JButtons, JLabels or JTextFields.
Thanks in advance.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class login extends JFrame {
public void CreateFrame() {
JFrame frame = new JFrame("Welcome");
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout(1000,1000));
panel.setLayout(new FlowLayout());
getContentPane().add(panel);
ImagePanel imagePanel = new ImagePanel();
imagePanel.show();
panel.add(imagePanel, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new login().CreateFrame();
}
});
}
}
class GUI extends JFrame{
private JButton buttonLogin;
private JButton buttonNewUser;
private JLabel iUsername;
private JLabel iPassword;
private JTextField userField;
private JPasswordField passField;
public void createGUI(){
setLayout(new GridBagLayout());
JPanel loginPanel = new JPanel();
loginPanel.setOpaque(false);
loginPanel.setLayout(new GridLayout(3,3,3,3));
iUsername = new JLabel("Username ");
iUsername.setForeground(Color.BLACK);
userField = new JTextField(10);
iPassword = new JLabel("Password ");
iPassword.setForeground(Color.BLACK);
passField = new JPasswordField(10);
buttonLogin = new JButton("Login");
buttonNewUser = new JButton("New User");
loginPanel.add(iUsername);
loginPanel.add(iPassword);
loginPanel.add(userField);
loginPanel.add(passField);
loginPanel.add(buttonLogin);
loginPanel.add(buttonNewUser);
add(loginPanel);
pack();
Writer writer = null;
File check = new File("userPass.txt");
if(check.exists()){
//Checks if the file exists. will not add anything if the file does exist.
}else{
try{
File texting = new File("userPass.txt");
writer = new BufferedWriter(new FileWriter(texting));
writer.write("message");
}catch(IOException e){
e.printStackTrace();
}
}
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File("userPass.txt");
Scanner scan = new Scanner(file);;
String line = null;
FileWriter filewrite = new FileWriter(file, true);
String usertxt = " ";
String passtxt = " ";
String puname = userField.getText();
String ppaswd = passField.getText();
while (scan.hasNext()) {
usertxt = scan.nextLine();
passtxt = scan.nextLine();
}
if(puname.equals(usertxt) && ppaswd.equals(passtxt)) {
MainMenu menu = new MainMenu();
dispose();
}
else if(puname.equals("") && ppaswd.equals("")){
JOptionPane.showMessageDialog(null,"Please insert Username and Password");
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username / Password");
userField.setText("");
passField.setText("");
userField.requestFocus();
}
} catch (IOException d) {
d.printStackTrace();
}
}
});
buttonNewUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewUser user = new NewUser();
dispose();
}
});
}
}
class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK,5));
try
{
image = ImageIO.read(new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ8F5S_KK7uelpM5qdQXuaL1r09SS484R3-gLYArOp7Bom-LTYTT8Kjaiw"));
}
catch(Exception e)
{
e.printStackTrace();
}
GUI show = new GUI();
show.createGUI();
}
#Override
public Dimension getPreferredSize(){
return (new Dimension(430, 300));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}
Seems to me like you have a class login (which is a JFrame, but never used as one). This login class creates a new generic "Welcome" JFrame with the ImagePanel in it. The ImagePanel calls GUI.createGUI() (which creates another JFrame, but doesn't show it) and then does absolutely nothing with it, thus it is immediately lost.
There are way to many JFrames in your code. One should be enough, perhaps two. But you got three: login, gui, and a simple new JFrame().

how to make a jscrollpane scroll from the start to the end?

I'm trying to make a jscorllpane automatic scroll from the start to the end. I use set value method for verticalbar but it's doesn't work. How can i make it scroll ?
Here is my code: When i run this code it just jump to the end of the jscorllpane instead of scorlling step by step
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class JScrollPaneToTopAction implements ActionListener {
JScrollPane scrollPane;
public JScrollPaneToTopAction(JScrollPane scrollPane) {
if (scrollPane == null) {
throw new IllegalArgumentException("JScrollPaneToTopAction: null JScrollPane");
}
this.scrollPane = scrollPane;
}
public void actionPerformed(ActionEvent actionEvent) {
run();
}
public void run() {
JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
int i = verticalBar.getMinimum();
while (i < verticalBar.getMaximum()) {
verticalBar.setValue(verticalBar.getMinimum()+i);
i += 50;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scrollPane.getParent().invalidate();
scrollPane.repaint();
scrollPane.invalidate();
System.out.println("changing " + i);
}
}
}
public class Draft20 {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea tr = new JTextArea();
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton bn = new JButton("Move");
bn.addActionListener(new JScrollPaneToTopAction(jScrollPane));
frame.add(bn, BorderLayout.SOUTH);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
I think the problem is your calls to repaint are queued for computation by EDT, but EDT is busy executing your actionPerformed. EDT will execute your repaint requests only after your run() completes. That's why you can see only the final result.
I'm not sure I can make it clear... check this code, it works for me:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
class JScrollPaneToTopAction implements ActionListener, Runnable {
JScrollPane scrollPane;
public JScrollPaneToTopAction(JScrollPane scrollPane) {
if (scrollPane == null) {
throw new IllegalArgumentException("JScrollPaneToTopAction: null JScrollPane");
}
this.scrollPane = scrollPane;
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
new Thread(this).start();
}
#Override
public void run() {
JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
int i = verticalBar.getMinimum();
while (i < verticalBar.getMaximum()) {
verticalBar.setValue(verticalBar.getMinimum() + i);
i += 50;
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
scrollPane.getParent().invalidate();
scrollPane.repaint();
scrollPane.invalidate();
}
});
System.out.println("changing " + i);
}
}
}
public class Draft20 {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea tr = new JTextArea();
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton bn = new JButton("Move");
bn.addActionListener(new JScrollPaneToTopAction(jScrollPane));
frame.add(bn, BorderLayout.SOUTH);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
I hope it helps.

GUI Animation: Slider Value between Action and Change classes?

My GUI frame comes up now but the slider value (speed) I get from my slider doesn't appear in my ActionLlistener class where I need use it as a delay in my timer. How do I bring that value over? The point is to run 12 images, like frames, at a speed that is determined by the value they slide on. Like if they slide to 12, there will be 12 milliseconds between each image.
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.*;
public class SliderGUI {
public static JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 1);
public static JLabel label = new JLabel ();
public static JPanel panel = new JPanel();
public static int delay;
public static int speed;
public static ImageIcon imageIcon;
public static Timer timer = new Timer (delay, new SliderListener());
public static void main(String[] args) {
JFrame frame = new JFrame("Legend Of Zelda");
panel.setLayout(new GridLayout(5, 5, 5, 25));
slider.setPaintLabels(true);
slider.addChangeListener(new SliderListener());
System.out.println (speed);
timer.addActionListener (new SliderListener());
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(label);
panel.add(slider);
frame.setContentPane(panel);
frame.pack();
}
private static class SliderListener implements ChangeListener, ActionListener {
public void stateChanged(ChangeEvent e) {
speed = slider.getValue();
slider.setMajorTickSpacing(25);
}
public void actionPerformed (ActionEvent e) {
for (int i = 1; i < 13; i++) {
if (i == 12){
i = 1;
}
imageIcon = new ImageIcon(i + ".jpg");
label.setIcon(imageIcon);
}
System.out.println ("Hi");
timer = new Timer(speed, new SliderListener());
timer.start();
}
}
}
Don't rely on static, it will blow up in your face...
You are creating multiple instances SliderListener when you really should be only creating one and applying it to the JSlider (and in your case) the Timer.
Having said that, I'd (personally) separate them...
You're also creating a new Timer each time the ActionListener is called (so like a thousand times a second! So after 1 second, you could have 1001 Timers running!) all of which are going to be calling SliderListener at the same time, and because it's all linked via global variables...face in explosion...
But I didn't actually see any where you were stating the Timer to start with...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderGUI {
public static void main(String[] args) {
new SliderGUI();
}
public SliderGUI() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public JSlider slider = new JSlider(JSlider.HORIZONTAL, 10, 100, 10);
public JLabel label;
public int delay;
public int speed;
public ImageIcon imageIcon;
public Timer timer;
public TestPane() {
setLayout(new GridLayout(5, 5, 5, 25));
slider.setPaintLabels(true);
label = new JLabel();
try {
BufferedImage frameImage = ImageIO.read(getClass().getResource("/Run-0.png"));
label.setIcon(new ImageIcon(frameImage));
} catch (IOException ex) {
ex.printStackTrace();
}
SliderListener sliderListener = new SliderListener();
timer = new Timer(delay, sliderListener);
slider.addChangeListener(sliderListener);
System.out.println(speed);
timer.addActionListener(sliderListener);
timer.start();
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(label);
add(slider);
}
private class SliderListener implements ChangeListener, ActionListener {
public void stateChanged(ChangeEvent e) {
int value = slider.getValue();
timer.setDelay(value);
}
private int frame = 0;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Tick " + ((Timer) e.getSource()).getDelay());
try {
BufferedImage frameImage = ImageIO.read(getClass().getResource("/Run-" + frame + ".png"));
label.setIcon(new ImageIcon(frameImage));
} catch (IOException exp) {
exp.printStackTrace();
}
frame++;
if (frame > 11) {
frame = 0;
}
}
}
}
}
Also, remember, a Timer is like a loop, each time the ActionListener is called, you should treat it as an iteration of a loop and update the state accordingly...

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