Which timer to use for GUI in Java - java

I have been trying to find the best timer to use for the following code (note this is a simplified version of my overall program). My hope is to run a method after 3 seconds.
The problem is with the actionPerformed, checkBlankLogin, and resetLoginBlank and putting a timer to delay resetLoginBlank from happening 3 seconds after checkBlankLogin has happened. But I want all methods in the class Outerframe to continuously run. So checkBlankLogin will keep checking if its blank until the person inputs the information for a "Valid Input" and the Login innerframe will close. But I don't know how to do that... Any help there also?
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import java.io.*;
import java.io.File;
import java.util.*;
import java.io.FileNotFoundException;
class OuterFrame extends JFrame implements ActionListener
{
Container pane; // container
JDesktopPane outframe; // outer frame
JInternalFrame login; // login frame
//pieces of login frame
JLabel loginLBLtitle;
JPanel loginPanel;
JLabel loginLBLname;
JLabel loginBlankName;
JLabel loginLBLpass;
JLabel loginBlankPass;
JTextField loginTXT;
JPasswordField loginPASS;
JButton loginBUT;
JInternalFrame apple;
OuterFrame()
{
//set up for Outer Frame
super("Application");
setSize(450,240);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outframe = new JDesktopPane();
outframe.setBackground(Color.BLUE);
//set up for Container
pane = getContentPane();
setContentPane(pane);
pane.add(outframe);
//Login Inner Frame
login = new JInternalFrame();
login.setSize(400,200);
login.setLocation(20,20);
login.setTitle("Member Login");
loginLBLtitle = new JLabel("Sign in with netid and your password.");
Font loginFontbody = new Font("SansSerif", Font.PLAIN, 12);
Font loginFonthead = new Font("SansSerif", Font.BOLD, 13);
loginLBLtitle.setFont(loginFonthead);
loginLBLname=new JLabel("User Name:");
loginLBLname.setFont(loginFontbody);
loginLBLpass=new JLabel("Password: ");
loginLBLpass.setFont(loginFontbody);
loginBUT=new JButton("Login");
loginBUT.setFont(loginFontbody);
loginBUT.addActionListener(this);
loginTXT=new JTextField(20);
loginPASS=new JPasswordField(20);
loginBlankName=new JLabel("");
loginBlankPass=new JLabel("");
loginPanel=new JPanel();
loginPanel.add(loginLBLtitle);
loginPanel.add(loginLBLname);
loginPanel.add(loginTXT);
loginPanel.add(loginBlankName);
loginPanel.add(loginLBLpass);
loginPanel.add(loginPASS);
loginPanel.add(loginBlankPass);
loginPanel.add(loginBUT);
//panel.add(lblmess);
login.add(loginPanel);
login.setVisible(true);
//Add Login to Outer Frame
outframe.add(login);
outframe.setSelectedFrame(login);
pane.add(outframe, BorderLayout.CENTER);
setVisible(true);
loginTXT.requestFocus();
}
public void actionPerformed(ActionEvent e)
{
//problem area
if(e.getSource()==loginBUT)
{
String uname=loginTXT.getText();
String passw=new String(loginPASS.getPassword());
int i=0;
while(i!=5)
{
if(checkBlankLogin(uname,passw,loginBlankName,loginBlankPass))
{
resetLoginBlank(loginBlankName,loginBlankPass);
}
else
{
if(!validateUser("accounts.txt",uname,passw,loginLBLtitle))
{
}
}
}
}
public void resetLoginBlank(JLabel loginBlankName, JLabel loginBlankPass)
{
loginBlankName.setText("");
loginBlankPass.setText("");
}
public void resetLoginTitle(JLabel loginBlankTitle)
{
loginBlankTitle.setText("Sign in with netid and your password.");
loginBlankTitle.setForeground(Color.BLACK);
}
public boolean checkBlankLogin(String name, String passw, JLabel loginBlankName, JLabel loginBlankPass)
{
boolean isBlank=false;
if(name.length()<1)
{
loginBlankMess("User name is required.",loginBlankName);
isBlank=true;
}
if(passw.length()<1)
{
loginBlankMess("Password is required.",loginBlankPass);
isBlank=true;
}
return isBlank;
}
public void loginBlankMess(String mess, JLabel lbl)
{
lbl.setText(mess);
lbl.setForeground(Color.RED);
}
public boolean validateUser(String filename, String name, String password, JLabel title)
{
boolean valid = false;
try
{
File file = new File(filename);
Scanner scanner = new Scanner(file);
ArrayList<String> fileInfo = new ArrayList<String>();
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
fileInfo.add(line);
}
String fullLogin = name + " " + password;
if(fileInfo.contains(fullLogin))
{
//loginBlankMess("Valid login",namemess);
valid=true;
}
if(!valid)
{
loginBlankMess("Please enter valid netid and password.", title);
resetLoginTitle(title);
}
}
catch(Exception ie)
{
System.exit(1);
}
return valid;
}
}
public class TheProgram
{
public static void main(String[] args)
{
new OuterFrame();
}
}`

I would check out the following resource (assuming you using Swing for your UI):
How to Use Swing Timers (Oracle)

Swing timers are the easiest in your case. You make your class implement ActionListener, and create a timer object. The timer will call the actionPerformed method when it expires.
import javax.swing.Timer;
class OuterFrame extends JFrame implements ActionListener{
Timer timer = null;
public void actionPerformed(ActionEvent e) {
if(e.getSource()==loginBUT){
//If the action came from the login button
if (checkBlankLogin()){
timer = new Timer(3000, this);
timer.setRepeats(false);
timer.setInitialDelay(3000);
timer.start();
} else if (timer != null){
timer.stop();
}
}else if(e.getSource()==timer){
//If the action came from the timer
resetLoginBlank(namemess,passwmess));
}
}
}

Related

Java : Wait for user input on swing window [duplicate]

This question already has answers here:
Swing GUI doesn't wait for user input
(2 answers)
Closed 6 years ago.
So, I started studying java about a week ago, I'm running into a few issues with a little program I'm building to train with swing and oop/java in general.
The program (so far) has a MainClass and a Window class.
The MainClass creates an instance of the Window class, which creates a JFrame and saves the user input in a field .
At this point, MainClass prints the output, which I get through getters methods.
The problem is that I still think in a procedural way: MainClass prints null, because it doesn't wait for the istance of window to get user input.
How can I fix it, thus getting main to wait for the istance of window to accept user input, before printing?
Nb. The Jframe stuff works, the window appears, it's just that MainClass doesn't wait for it to do what it's supposed to. I could (I think?) use some sleep command to wait but it seems utterly wrong.
here's the code of MainClass.java
import java.util.Arrays;
public class MainClass {
private char[] password;
private String pin;
public static void main(String[] args) {
Window w = new Window();
System.out.println(w.getPin() + Arrays.toString(w.getPassword()) + '1');
}
}
and Window.java
import java.awt.*;
import javax.swing.*;
import java.awt.Window.Type;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import net.miginfocom.swing.MigLayout;
public class Window extends JFrame{
private JTextField textField_1;
private JButton btnNewButton;
private JPanel panel;
private JPasswordField passwordField;
private char[] password = new char[10];
private String pin;
public Window() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setSize(370, 150);
this.setForeground(new Color(192, 192, 192));
this.setTitle("Access Password Manager");
this.setResizable(false);
panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new MigLayout("", "[70.00][132.00,grow][44.00][67.00,grow][61.00][]", "[19.00][34.00][]"));
JLabel lblNewLabel = new JLabel("Password");
panel.add(lblNewLabel, "cell 0 1,alignx trailing,aligny center");
passwordField = new JPasswordField();
passwordField.setColumns(13);
panel.add(passwordField, "cell 1 1,alignx center");
JLabel lblNewLabel_1 = new JLabel("Key");
panel.add(lblNewLabel_1, "cell 2 1,alignx center,aligny center");
textField_1 = new JTextField();
panel.add(textField_1, "cell 3 1,alignx left,aligny center");
textField_1.setColumns(4);
btnNewButton = new JButton("Log In");
ListenForButton listener = new ListenForButton();
btnNewButton.addActionListener(listener);
panel.add(btnNewButton, "cell 4 1");
this.setVisible(true);
}
private class ListenForButton implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnNewButton){
if (passwordField.getPassword().length < 10){
password = passwordField.getPassword().clone();
}
pin = textField_1.getText();
}
}
}
public char[] getPassword(){
return password;
}
public String getPin(){
return pin;
}
}
EDIT:
It's not just about printing, which I know I could do directly into Window.class.
I'm sorry if I explained myself poorly. Please consider the println as a "I need to access and work on those fields once window has saved them form the input".
You could use a modal dialog to get user input, the dialog will block the code execution at the point it is made visible and continue when it's made invisible (it's magic), have a look at How to Make Dialogs for more details
Updated
The modal dialog will only block the Event Dispatching Thread (technically it doesn't block it, it simply circumvents it), see Initial Threads for more details
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.miginfocom.swing.MigLayout;
public class MainClass {
private char[] password;
private String pin;
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();
}
System.out.println("Before Window");
Window w = new Window();
System.out.println("After Window");
System.out.println(w.getPin() + Arrays.toString(w.getPassword()) + '1');
}
});
}
public static class Window extends JDialog {
private JTextField textField_1;
private JButton btnNewButton;
private JPanel panel;
private JPasswordField passwordField;
private char[] password = new char[10];
private String pin;
public Window() {
this.setModal(true);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setSize(370, 150);
this.setForeground(new Color(192, 192, 192));
this.setTitle("Access Password Manager");
this.setResizable(false);
panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new MigLayout("", "[70.00][132.00,grow][44.00][67.00,grow][61.00][]", "[19.00][34.00][]"));
JLabel lblNewLabel = new JLabel("Password");
panel.add(lblNewLabel, "cell 0 1,alignx trailing,aligny center");
passwordField = new JPasswordField();
passwordField.setColumns(13);
panel.add(passwordField, "cell 1 1,alignx center");
JLabel lblNewLabel_1 = new JLabel("Key");
panel.add(lblNewLabel_1, "cell 2 1,alignx center,aligny center");
textField_1 = new JTextField();
panel.add(textField_1, "cell 3 1,alignx left,aligny center");
textField_1.setColumns(4);
btnNewButton = new JButton("Log In");
ListenForButton listener = new ListenForButton();
btnNewButton.addActionListener(listener);
panel.add(btnNewButton, "cell 4 1");
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnNewButton) {
if (passwordField.getPassword().length < 10) {
password = passwordField.getPassword().clone();
}
pin = textField_1.getText();
}
}
}
public char[] getPassword() {
return password;
}
public String getPin() {
return pin;
}
}
}
you should be using events. your main class could listen for an event, if the button in the window is pressed. e.g.
public static void main(String[] args) {
Window w = new Window();
w.getBtnNewButton().addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(w.getPin() + Arrays.toString(w.getPassword()) + '1');
}
});
}
in this case you have to make a public getter for the button, so you can access it from the main class.
If you want the result to be printed on button click, then you could print it in the button's action listener. If you want it to be printed as soon as user enters anything, you can add action listeners to your password text field.
Window / View
public class Window extends JFrame{
private Controller controller;
private Model model;
public Window(Controller controller, Model model) {
this.controller = controller;
this.model = model;
}
Model
public class Model {
private String password;
//getters and setters
}
Controller
public class Controller {
public void doSomething() {
// do anything. Views could invoke controller methods to do things and is usually invoked when certain events happen.
}
Main
public class Main {
public static void main(String[] args) {
new Window(new Controller(), new Model());
}

Close one JFrame before opening another JFrame

I want to close completely one JFrame before opening another .
Consider the code :
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
/**
*
* #author X
*
*/
class ServerConnect extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
/**
* Ctor
*/
ServerConnect()
{
this.setTitle("Sever Side Listener");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
gui.setSize(m_sizeX , m_sizeY);
this.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
this.setLocation(m_centerX , m_centerY);
this.setSize(m_sizeX , m_sizeY);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new ServerConnect();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton)
{
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try
{
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try
{
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
this.setVisible(false);
new ServerGUI(ip , s_port);
}
}
}
In actionPerformed() after the user had entered the IP number and port , I set the window to false , i.e :
this.setVisible(false); // don't show the current window
new ServerGUI(ip , s_port); // open another JFrame
I want to close the current JFrame completely, not to set its visibility to false.
How can I do that ?
Regards
Your problem appears that if you call close on the JFrame, the program will exit since you've set its setDefaultCloseOperation to setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);.
Options:
Use a different defaultCloseOperation, one that doesn't close the application, perhaps JFrame.DISPOSE_ON_CLOSE.
Use a JDialog initially instead of a JFrame. These types of windows can't shut down the application. Here is the JDialog and JOptionPane Tutorial
Don't swap JFrames at all, but rather swap views by using a CardLayout. The CardLayout Tutorial link
My own preference is to use a CardLayout as much as possible to avoid annoying the user who usually doesn't appreciate having a bunch of windows flung at him. I also use modal JDialogs when I want to get information from the user in a modal fashion, i.e., where the application absolutely cannot move forward until the user gives the requested information, and non-modal dialogs to present program state monitoring information for the user. I almost never use multiple JFrames in a single application.
Edit
As an aside, I almost never create classes that extend JFrame or any top-level window since I find that much too restricting. Instead most of my GUI type classes are geared towards creating JPanels. The advantage to this is then I can decide when and where I want to put the JPanel, and can change my mind at any time. It could go into a JFrame, a JDialog, a JOptionPane, be a card that is swapped in a CardLayout,... anywhere.
Edit 2
For example, here's a small program that uses your code, slightly modified, and puts it into a JDialog:
My code:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MyServerMain extends JPanel {
private JTextField serverIp = new JTextField(8);
private JTextField serverPort = new JTextField(8);
private ServerConnect serverConnect = new ServerConnect();
private JDialog serverConnectDialog = null;
public MyServerMain() {
serverIp.setFocusable(false);
serverPort.setFocusable(false);
add(new JLabel("Server IP:"));
add(serverIp);
add(new JLabel("Server Port:"));
add(serverPort);
add(new JButton(new SetUpServerAction("Set Up Server", KeyEvent.VK_S)));
}
private class SetUpServerAction extends AbstractAction {
public SetUpServerAction(String name, int keyCode) {
super(name);
putValue(MNEMONIC_KEY, keyCode);
}
#Override
public void actionPerformed(ActionEvent evt) {
if (serverConnectDialog == null) {
Window owner = SwingUtilities.getWindowAncestor(MyServerMain.this);
serverConnectDialog = new JDialog(owner, "Server Set Up",
ModalityType.APPLICATION_MODAL);
serverConnectDialog.getContentPane().add(serverConnect);
serverConnectDialog.pack();
serverConnectDialog.setLocationRelativeTo(owner);
}
serverConnectDialog.setVisible(true);
// when here, the dialog is no longer visible
// so extract information from the serverConnect object
serverIp.setText(serverConnect.getServerIp());
serverPort.setText(serverConnect.getServerPort());
}
}
private static void createAndShowGui() {
MyServerMain mainPanel = new MyServerMain();
JFrame frame = new JFrame("My Server Main");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Your modified code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class ServerConnect extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
ServerConnect() {
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3, 3));
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
gui.setSize(m_sizeX, m_sizeY);
setLayout(new BorderLayout()); // !!
add(gui, BorderLayout.CENTER);
JPanel labels = new JPanel(new GridLayout(0, 1));
JPanel controls = new JPanel(new GridLayout(0, 1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
this.setLocation(m_centerX, m_centerY);
this.setSize(m_sizeX, m_sizeY);
// !! this.pack();
// !! this.setVisible(true);
}
public static void main(String[] args) {
new ServerConnect();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton) {
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try {
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try {
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
// !! this.setVisible(false);
// !! new ServerGUI(ip , s_port);
// !!
Window ownerWindow = SwingUtilities.getWindowAncestor(this);
ownerWindow.dispose();
}
}
// !!
public String getServerIp() {
return m_serverIP.getText();
}
// !!
public String getServerPort() {
return m_serverPort.getText();
}
}
Hope this another_Frame frm = new another_Frame();
frm.setVisible(true);
this.dispose();// this represent the fram to close

Java JDialogs How To Pass Information Between?

after looking for an answer for 3 hours, I am just about to give up on this idea:
I am making an application that displays the followers of a Twitch streamer.
A couple of features i am trying to add:
the display frame is a separate window from the controls frame.
I am trying to use (JFrame as display window) (JDialog as controls frame)
And furthermore: Settings is in another JDialog (this one has Modal(true))
Settings needs to be able to send the JFrame information such as: "username" and "text color"
And the settings JDialog will only pop up from clicking "settings" on the controls JDialog.
It will setVisible(false) when you click "save settings" or the X.
On the controls JDialog (b_console) needs to receive error messages and info like that.
And on the same JDialog, "filler" needs to receive follower count and things like that.
Here follows my code involving the transfers listed above:
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;
public class JavaFollowerNotifier extends JFrame implements ComponentListener
{
Settings settings = new Settings();
ControlPanel ctrlPnl = new ControlPanel();
public JavaFollowerNotifier()
{
try
{
settings.readSettings();
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabFollower()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabStats()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.filler.setText("Followers: " + totalFollowers + "\nLatest: " + lastFollower);
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void componentMoved(ComponentEvent arg0)
{
//this is only to *attach this JDialog to the JFrame and make it move together my plan is to have it undecorated as well
int x = this.getX() + this.getWidth();
int y = this.getY();
ctrlPnl.movePanel(x, y);
}
public void paint(Graphics g)
{
if(clearPaint == false)
{
//any "savedSettings[n]" are saved in Settings.java (just not in this version)
g.setColor(Color.decode(savedSettings[3]));
scaledFont = scaleFont(follower + " followed!", bounds, g, new Font(savedSettings[2], Font.PLAIN, 200));
}
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Settings extends JDialog implements ActionListener
{
JavaFollowerNotifier jfollow = new JavaFollowerNotifier();
ControlPanel ctrlPnl = new ControlPanel();
//here are the settings mention above
String[] savedSettings = {"imgs/b_b.jpg","username","font","color","Nightbot"};
public Settings()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void saveSettings()
{
savedSettings[4] = jfollow.lastFollower;
try
{
PrintWriter save = new PrintWriter("config.cfg");
ctrlPnl.b_console.setText("Saving...");
for(int i = 0; i < 5; i++)
{
save.println(savedSettings[i]);
}
save.close();
ctrlPnl.b_console.setText("Saved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
canClose = false;
}
readSettings();
this.repaint();
}
public void readSettings()
{
ctrlPnl.b_console.setText("Loading...");
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
jfollow.lastFollower = savedSettings[4];
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
ctrlPnl.b_console.setText("Loaded Settings");
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ControlPanel extends JDialog implements ActionListener
{
public ControlPanel()
{
try
{
}
catch (Exception e)
{
b_console.setText("Error");
System.out.println(e);
}
}
public void movePanel(int x, int y)
{
//here is where i *attach the JDialog to the JFrame
controlPanel.setLocation(x, y);
}
public void actionPerformed(ActionEvent ie)
{
if(ie.getSource() == b_settings)
{
settings.frame.setVisible(true);
}
}
}
I tried to fix your program, but I wasn't too sure about its flow. So I created another simple one. What I did was pass the labels from the main frame to the dialogs' constructors. In the dialog, I took those labels and changed them with text entered in their text fields. If you hit enter after writing text from the dialog, you'll see the text in the frame change
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
....
class ControlDialog extends JDialog {
private JLabel label;
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
....
class SettingsDialog extends JDialog {
private JLabel label;
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
Test it out and let me know if you have any questions
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private JButton showControl = new JButton("Show Control");
private JButton showSetting = new JButton("Show Settings");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
showControl.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
control.setVisible(true);
}
});
showSetting.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
settings.setVisible(true);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(showControl);
buttonPanel.add(showSetting);
add(buttonPanel, BorderLayout.SOUTH);
add(controlDialogLabel, BorderLayout.NORTH);
add(settingDialogLabel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JavaFollowerNotifier1();
}
});
}
}
class ControlDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Control Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
ControlDialog.this.setVisible(false);
}
});
}
}
class SettingsDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Settings Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
SettingsDialog.this.setVisible(false);
}
});
}
}
Typically when I build GUI's which use modal dialogs to gather user input, I build my own class, which extends the JDialog or in some cases a JFrame. In that class I expose a getter method for an object which I usually call DialgResult. This object acts as the Model for the input I gather from the user. In the class that has the button, or whatever control which triggers asking the user for the information, I create it, show it as a modal dialog, then when it is closed, I retrieve the object using that same getter.
This is a very primitive example:
package arg;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class asdfas extends JFrame {
public static void main(String[] args) {
asdfas ex = new asdfas();
ex.setVisible(true);
}
public asdfas() {
init();
}
private void init() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(100,100,200,200);
final JButton button = new JButton("Show modal dialog");
button.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Dialog d = new Dialog();
d.setVisible(true);
button.setText(d.getDialogResult().value);
revalidate();
repaint();
}
});
this.add(button);
}
class DialogResult {
public String value;
}
class Dialog extends JDialog {
JTextField tf = new JTextField(20);
private DialogResult result = new DialogResult();
public Dialog() {
super();
init();
}
private void init() {
this.setModal(true);
this.setSize(new Dimension(100,100));
JButton ok = new JButton("ok");
ok.addActionListener( new ActionListener () {
#Override
public void actionPerformed(ActionEvent arg0) {
result = new DialogResult();
result.value = tf.getText();
setVisible(false);
}
});
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(tf);
p.add(ok);
this.add(p);
}
public DialogResult getDialogResult() {
return result;
}
}
}

Java wrong username & password message cant seem to work

This is the coding on a button of jFrame a simple login form, username and password authentication working fine but if else condition dont execute i am stuck here if any of you guys help me out here just give me a hint
String u_id=jTextField1.getText();
String p_word=jPasswordField1.getText();
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433; databaseName=LoginForm; user=sa; password=aptech");
Statement st=con.createStatement();
ResultSet result=st.executeQuery("select pass_word from employee where user_name='"+u_id+"' ");
if(result.next())
{
String pwd = result.getString("pass_word");
if( p_word.equals(pwd))
{
jLabel4.setText("you are logged in");
}
else if (!p_word.equals(pwd))
{
jLabel4.setText("Your id password is Wrong");
}
}
else
{
jLabel4.setText("Enter your id password again");
jTextField1.setText("");
jPasswordField1.setText("");
}
}
catch (ClassNotFoundException a)
{
System.out.println(""+a);
}
catch (SQLException s)
{
System.out.println(""+s);
}
Try this one instead:
Create a new class called (I hope you're using and IDE!) "Log.java"
Copy & Paste following code into the class.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Log extends JFrame {
public static void main(String[] args) {
Log frameTable = new Log();
}
JButton Login = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
Log(){
super("Login Autentification");
setSize(300,200);
setLocation(500,280);
panel.setLayout (null);
txuser.setBounds(70,30,150,20);
pass.setBounds(70,65,150,20);
Login.setBounds(110,100,80,20);
panel.add(Login);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin(){
Login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = txuser.getText();
String ppaswd = pass.getText();
if(puname.equals("1") && ppaswd.equals("2")) {
newframe regFace =new newframe();
regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,"Wrong Password or Username!");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
}
Then, create a new class, "newframe.java", and fill it with this code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class newframe extends JFrame {
public static void main(String[] args) {
newframe frameTabel = new newframe();
}
JLabel welcome = new JLabel("Welcome to a New Frame");
JPanel panel = new JPanel();
newframe(){
super("Welcome");
setSize(300,200);
setLocation(500,280);
panel.setLayout (null);
welcome.setBounds(70,50,150,60);
panel.add(welcome);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
Now you should be good to go, if something is not clear, feel free to ask or figure out by yourself, this lovely community will try to help.
You have about ten time more code than you need. Do this instead (pseudo code):
Use this query instead:
select count(*)
from employee
where user_name = ?
and pass_word = ?
You will get exactly one row with one column returned.
The value of that column will be either 1 or 0
You should be able to handle the rest by yourself.

How do I get user input from a JTextField?

I am attempting a very simple form designed to take user input into a JTextField and show that same input via a pop up dialog.
I can hardcode the JTextField to have a preset number using setText(). If I do this, my program works flawlessly.
However, when I leave the field blank and try getText() to show the text in the pop up dialog, I either get an empty pop up frame, or I get an 'empty string' exception (I am attempting to parse String to Double.)
package buttontest;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import javax.swing.*;
import java.awt.event.ActionEvent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class ButtonTest
{
public static void main(String[] args)
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ButtonFrame extends JFrame
{
#SuppressWarnings("LeakingThisInConstructor")
public ButtonFrame()
{
setTitle("SunStream Loan Calculator v2.0");
setSize(900,900);
ButtonPanel panel = new ButtonPanel();
panel.add(new JLabel("Enter your loan amount:"));
loanAmt = new JTextField(40);
panel.add(loanAmt);
add(panel,BorderLayout.CENTER);
}
public JTextField loanAmt;
class ButtonPanel extends JPanel implements ActionListener
{
private Component frame;
public ButtonPanel()
{
final JButton b2 = new JButton("Calculate");
add(b2, BorderLayout.SOUTH);
b2.setActionCommand("calculate");
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
ButtonFrame bf = new ButtonFrame();
if("calculate".equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(frame, bf.loanAmt.getText());
}
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
Any help would be greatly appreciated. I am researching using a KeyListener or KeyEvent but I don't quite understand it well enough.
You're creating a "shadow" ButtonFrame variable inside of the b2's ActionListener. Yes the bf variable refers to a ButtonFrame object which is of the same class as the displayed ButtonFrame object, but it refers to a completely distinct and non-visualized object. The key to a solution is to get the text from the ButtonFrame object that is actually displayed, and this can be obtained from within an inner class via the ButtonFrame.this construct:
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//!! ButtonFrame bf = new ButtonFrame();
if ("calculate".equals(e.getActionCommand())) {
//!! note use of ButtonFrame.this:
JOptionPane.showMessageDialog(frame, ButtonFrame.this.loanAmt.getText());
}
}
});
Next consider using public getters rather than accessing fields such as the JTextField directly. This reduces the chances of the code causing side effects, such as changing the properties of the JTextField object inadvertently.
For instance (changes denoted by //!! comment):
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ButtonTest {
public static void main(String[] args) {
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ButtonFrame extends JFrame {
private JTextField loanAmt; // !! Make field private
#SuppressWarnings("LeakingThisInConstructor")
public ButtonFrame() {
setTitle("SunStream Loan Calculator v2.0");
setSize(900, 900);
ButtonPanel panel = new ButtonPanel();
panel.add(new JLabel("Enter your loan amount:"));
loanAmt = new JTextField(40);
panel.add(loanAmt);
add(panel, BorderLayout.CENTER);
}
// !! create a public method to get JTextField's text
// !! without exposing the JTextField itself.
public String getLoanAmtText() {
return loanAmt.getText();
}
class ButtonPanel extends JPanel implements ActionListener {
private Component frame;
public ButtonPanel() {
final JButton b2 = new JButton("Calculate");
add(b2, BorderLayout.SOUTH);
b2.setActionCommand("calculate");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// !! ButtonFrame bf = new ButtonFrame();
if ("calculate".equals(e.getActionCommand())) {
//!! call public method on ButtonFrame object
JOptionPane.showMessageDialog(frame,
ButtonFrame.this.getLoanAmtText());
}
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
The only way you can access your loanAmt is through ButtonPanel itself. Because you add loanAmt to this button right ?
So, if you want access loanAmt. You must get all component on this button panel. This is my psudeo code howto accessing your loanAmt from ButtonPanel class.
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonFrame bf = new ButtonFrame();
if("calculate".equals(e.getActionCommand())) {
// Get all component
java.awt.Component[] componentList = this.getComponents();
JTextField txtField;
String value;
for (int i = 0; i < componentList.length; i++) {
if (componentList[i].getClass().getName().equals("javax.swing.JTextField")) {
txtField = (JTextField) componentList[i];
value = textField.getText();
}
}
if (value != null) JOptionPane.showMessageDialog(frame, value);
}
}
});

Categories