So I wrote the following code:
package myProject;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.*;
public class GuiTest extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField user = new JTextField();
JTextField pass = new JTextField();
JLabel title = new JLabel("Login");
JLabel usernameGui = new JLabel("Username:");
JLabel passwordGui = new JLabel("Password:");
public String userName;
public String passWord;
//Non GUI variables
public String username;
public String password;
File dir = new File("C:\\Users\\User\\Desktop\\account1.txt");
public boolean pressed = false;
public GuiTest(){
JFrame window = new JFrame("Position");
//window.setSize(600, 600);
window.setBounds(500,200,600,600);
window.setResizable(false);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
window.add(panel);
//Labels
panel.add(title);
title.setBounds(290, 110, 100, 100);
panel.add(usernameGui);
usernameGui.setBounds(150,200,150,30);
panel.add(passwordGui);
passwordGui.setBounds(150,240,150,30);
//Text fields
panel.add(user);
user.setBounds(230,240,150,30);
panel.add(pass);
pass.setBounds(230,200,150,30);
//Button
JButton btn = new JButton("Login");
btn.setBounds(250, 290, 100, 30);
panel.add(btn);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
userName = user.getText();
passWord = pass.getText();
pressed = true;
System.out.println(passWord+" "+password+" "+userName+" "+username);
//System.out.println(mn.passWord+" "+mn.password+" "+mn.userName+" "+mn.username);
}
});
}
public static void main(String[] args){
GuiTest test = new GuiTest();
GuiTest mn = new GuiTest();
try{
mn.Write("MyUser", "MyPass");
Scanner scan = new Scanner(mn.dir);
String text = scan.nextLine();
scan.close();
System.out.println(text);
String[] sep = text.split(" ");
mn.username = sep[0];
mn.password = sep[1];
System.out.println("User: " + mn.username + " pass: " + mn.password);
}catch(Exception e){
System.out.println("Error! File didn't create.");
}
Scanner usernameIn = new Scanner(System.in);
Scanner passwordIn = new Scanner(System.in);
String userIn = usernameIn.nextLine();
String passIn = passwordIn.nextLine();
if(mn.userName.equals(mn.username) && mn.passWord.equals(mn.password)){
System.out.print("Access Granted");
}else{
System.out.println("Access Denied");
System.out.println(mn.passWord+" "+mn.password+" "+mn.userName+" "+mn.username);
}
}
public void Write(String user, String pass){
String userONE = user;
String passONE = pass;
try{
PrintWriter file = new PrintWriter(dir);
file.print(userONE+" "+passONE);
file.close();
}catch(Exception e){
System.out.println("Error! File didn't create.");
}
}
}
When I run it two windows pop up (instead of 1) and I cant test the input as both of them somehow use the variables i guess. Does anyone know how to fix it?
Thanks in advance.
When I run it two windows pop up (instead of 1)
Since you are creating two objects of same class.
GuiTest test = new GuiTest();
GuiTest mn = new GuiTest();
Just remove one of them GuiTest test = new GuiTest();. Since you are not using test object.
Related
I've got an error while validating username and password in this Java Swing code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class LoginForm extends JFrame implements ActionListener {
private JButton login;
private JTextField name;
private JPasswordField pw;
private LoginForm() {
super("Log in");
login = new JButton("Log in");
name = new JTextField(20);
pw = new JPasswordField(20);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel fields = new JPanel(new BorderLayout());
fields.add(name, "North");
fields.add(new JScrollPane(), "Center");
fields.add(pw, "South");
add(fields, "Center");
add(new JPanel(), "South");
add(new JPanel(), "North");
JPanel j = new JPanel();
j.setSize(100, 400);
j.add(login);
//j.add(new JLabel("|\n|\n|-> Username"));
setSize(600, 400);
add(j, "West");
login.addActionListener(this);
setVisible(true);
}
public static void main(String[] args) {
new LoginForm();
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == login) {
if (!validUser(name.getText(), pw.getPassword())) JOptionPane.showMessageDialog(null, "This user not exists.\nFor create a user,\n edit 'database.lfrm' file."
, "Error!", JOptionPane.ERROR_MESSAGE);
else JOptionPane.showMessageDialog(null, "This user is valid! Congraulations!");
} else throw new RuntimeException("Event source isn't be a " + login.toString());
}
private static boolean validUser(String name, char[] pwd) {
boolean res = false;
try {
BufferedReader br = new BufferedReader(new FileReader("database.lfrm"));
String all = "", lines[], user[], line;
while ((line = br.readLine()) != null) all += line;
lines = all.split("\n");
user = Arrays.asList(lines).get(Arrays.asList(lines).indexOf(name + " $ " + new String(pwd))).split(" $ ");
if (user == new String[]{name, new String(pwd)}) res = true;
} catch (IOException e) {e.printStackTrace();}
return res;
}
}
I compiled and run this code, and I had this "error":
"
This user not exists.
For create a user, edit 'database.lfrm' file.
"
My 'database.lfrm' file is likes this:
"
JavaUser $ adimn
"
I guess the problem is here:
if (user == new String[]{name, new String(pwd)}) res = true;
When you do this, you are checking if "user" and the String[] element are the same object, which is not true, because the String[] element is a different object you are creating just for this validation.
What you want to check is if the contents of the "user" array and the next array are the same, which you can solve replacing this line by:
if (Arrays.equals(user, new String[] {name, new String(pwd)})) res = true;
first and foremost I want to point out I'm a novice programmer without much experience, so excuse me if this question seems obvious to some. Also, since I am not sure what the problem is, I will try to give as much information as possible so sorry I seem to ramble. Anyway what I am trying to do is create a java application with a Jframe, and have it interact with a database. I don't really have any experience with databases or mysql, but I was able to follow along a youtube video, and created a java project which successfully connects to a database, creates a table, and inserts information into that table. I figured I would be able to use the same connection function in my project with my frame.
However when I tried this,the program does not connect or display anything in the console, just simply launches my jframe. Its as if the connection part isn't even there? Connection function I used is :
public static Connection getConnection() throws Exception{
try {String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("connected");
return conn;
}catch(Exception e){System.out.println(e);}
return null;
}
here is my full code, sorry if it is hard to read, I did most of my initial coding in eclipse's window builder. The functions to get a connection and to post to the DB are at the bottom after the main (had them before the main but moved them hoping it would make a difference) any and all help is appreciated !
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import com.toedter.calendar.JDateChooser;
public class TemplatePractice extends JFrame {
private JTextField HTHoursWorked;
private JTextField HTHourlyRate;
private JTextField HTCCTips;
private JTextField PCHours;
private JTextField PCTotal;
private JTextField DisplayTP;
private JTextField DispGPPP;
private JTextField DispBnqtPay;
private JTextField DispEstPay;
JTextField DispActualPC;
private final Action action = new SwingAction();
private TemplatePractice() {
final JTextField PCTotal;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(3, 1, 0, 0));
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblNewLabel_1 = new JLabel("Date Worked");
panel.add(lblNewLabel_1);
JDateChooser PCDateWorked = new JDateChooser();
panel.add(PCDateWorked);
JLabel lblHoursWorked = new JLabel("Hours Worked:");
panel.add(lblHoursWorked);
HTHoursWorked = new JTextField();
panel.add(HTHoursWorked);
HTHoursWorked.setColumns(10);
JRadioButton rdbtnRestaruant = new JRadioButton("Restaruant:");
panel.add(rdbtnRestaruant);
JRadioButton rdbtnBanquet = new JRadioButton("Banquet");
panel.add(rdbtnBanquet);
JLabel lblHoursWorked_1 = new JLabel("Hourly Rate: $");
panel.add(lblHoursWorked_1);
HTHourlyRate = new JTextField();
panel.add(HTHourlyRate);
HTHourlyRate.setColumns(10);
JLabel lblCreditCardTips = new JLabel("Credit Card Tips:");
panel.add(lblCreditCardTips);
HTCCTips = new JTextField();
panel.add(HTCCTips);
HTCCTips.setColumns(10);
JButton HTAddBtn = new JButton("Add");
panel.add(HTAddBtn);
JLabel label = new JLabel("");
panel.add(label);
JLabel label_1 = new JLabel("");
panel.add(label_1);
JPanel PCPanel = new JPanel();
getContentPane().add(PCPanel);
JLabel lblPayPeriodStart = new JLabel("Pay Period Start:");
PCPanel.add(lblPayPeriodStart);
JDateChooser PCStartDate = new JDateChooser();
PCPanel.add(PCStartDate);
JLabel lblPayPeriodEnd = new JLabel("Pay Period End");
PCPanel.add(lblPayPeriodEnd);
JDateChooser dateChooser_2 = new JDateChooser();
PCPanel.add(dateChooser_2);
JLabel lblTotalHours = new JLabel("Total Hours:");
PCPanel.add(lblTotalHours);
PCHours = new JTextField();
PCPanel.add(PCHours);
PCHours.setColumns(10);
JLabel lblP = new JLabel("Paycheck Amount: $");
PCPanel.add(lblP);
PCTotal = new JTextField();
PCPanel.add(PCTotal);
PCTotal.setColumns(10);
JButton PCAddBtn = new JButton("Add");
PCAddBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double paydoub = Double.parseDouble(PCTotal.getText());
int i;
for (i=0;i<1000;i++){
double paycheckdouble=0;
paycheckdouble+=paydoub;
double paycheckTotal=paycheckdouble;
String paytotal= String.valueOf(paycheckTotal);
DisplayTP.setText(paytotal);
}
}
});
PCAddBtn.setAction(action);
PCPanel.add(PCAddBtn);
JPanel panel_1 = new JPanel();
getContentPane().add(panel_1);
JButton btnCalculate = new JButton("Calculate");
panel_1.add(btnCalculate);
JLabel lblTotalPay = new JLabel("total pay:");
panel_1.add(lblTotalPay);
DisplayTP = new JTextField();
panel_1.add(DisplayTP);
DisplayTP.setColumns(10);
JLabel lblGratPerParty = new JLabel("Grat Per Party");
panel_1.add(lblGratPerParty);
DispGPPP = new JTextField();
panel_1.add(DispGPPP);
DispGPPP.setColumns(10);
JLabel lblBanquetPay = new JLabel("Banquet Pay");
panel_1.add(lblBanquetPay);
DispBnqtPay = new JTextField();
panel_1.add(DispBnqtPay);
DispBnqtPay.setColumns(10);
DispEstPay = new JTextField("");
panel_1.add(DispEstPay);
DispEstPay.setColumns(10);
DispActualPC = new JTextField();
panel_1.add(DispActualPC);
DispActualPC.setColumns(10);
}
public static void main(String args[]) throws Exception{
getConnection();
post();
TemplatePractice frame = new TemplatePractice();
frame.setVisible(true);
frame.setSize(600,400);
}
public static Connection getConnection() throws Exception{
try {String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("connected");
return conn;
}catch(Exception e){System.out.println(e);}
return null;
}
public static void post() throws Exception{
final String var1 = "john";
final String var2 = "smith";
try{
Connection Con = getConnection();
PreparedStatement posted = Con.prepareStatement("INSERT INTO tablename(first,last) VALUES ('"+var1+"','"+var2+"')");
posted.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally {System.out.println("Insert Completed");}
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "SwingAction");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
}
I am receiving this error when i change items in the Jcombobox, nothing breaks it just shows this error, is there anyway to just throw it so it doesn't show up. everything still works fine, but if you wish to have a look at the code. i will post below.
Error message:
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:2056)
at java.awt.Component.getLocationOnScreen(Component.java:2030)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:395)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:393)
at sun.lwawt.macosx.LWCToolkit$CallableWrapper.run(LWCToolkit.java:538)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:301)
And my code which i don't know which section to show so its all their.
import javax.swing.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
public class TouchOn extends JDialog {
private JPanel mainPanel;
public ArrayList Reader(String Txtfile) {
try {
ArrayList<String> Trains = new ArrayList<String>();
int count = 0;
String testing = "";
File file = new File(Txtfile);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
count += count;
if(!line.contains("*")){
Trains.add(line + "\n");
}
stringBuffer.append("\n");
}
fileReader.close();
//Arrays.asList(Trains).stream().forEach(s -> System.out.println(s));
return Trains;
} catch (IOException e) {
e.printStackTrace();
}
//return toString();
return null;
}
public TouchOn()
{
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
public void setPanels()
{
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
JTextField sYear = new JTextField("2015");
String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
JTextField touchOnTimeFieldhour = new JTextField();
JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]));
JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
apply.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if(belgrave.isSelected()){
String trainline = belgrave.getText();
}
if(glenwaverly.isSelected()){
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10,10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}
Don't create multiple JComboBoxes and then swap visibility. Instead use one JComboBox and create multiple combo box models, such as by using DefaultComboBoxModel<String>, and then swap out the model that it holds by using its setModel(...) method. Problem solved.
Note that using a variation on your code -- I'm not able to reproduce your problem:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestFoo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndDisplayGui();
}
});
}
public static void createAndDisplayGui() {
final JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton button = new JButton(new AbstractAction("Press Me") {
#Override
public void actionPerformed(ActionEvent evt) {
TouchOn2 touchOn2 = new TouchOn2(frame);
touchOn2.setVisible(true);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class TouchOn2 extends JDialog {
private JPanel mainPanel;
#SuppressWarnings({ "rawtypes", "unused" })
public ArrayList Reader(String Txtfile) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add("Data String Number " + (i + 1));
}
// return toString();
// !! return null;
return list;
}
public TouchOn2(Window owner) {
super(owner);
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
#SuppressWarnings("unchecked")
public void setPanels() {
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
final JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
final JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
final JTextField sYear = new JTextField("2015");
final String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
final JTextField touchOnTimeFieldhour = new JTextField();
final JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
final JComboBox<String> cb = new JComboBox<>(
stations.toArray(new String[stations.size()]));
final JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
final JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
apply.addActionListener(new ActionListener() {
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent e) {
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy")
.format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if (belgrave.isSelected()) {
// !! ***** note you're shadowing variables here!!!! ****
String trainline = belgrave.getText();
}
if (glenwaverly.isSelected()) {
// !! and here too
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10, 10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}
i am trying to implement GUI features to my java coding which i am trying out for the first time. But i tried a "Create Player Feature" in my code but it is not writing to file can someone help? thanks
private class createListener implements ActionListener{
public void actionPerformed(ActionEvent event){
JFrame frame = new JFrame("Create Player");
JPanel panel = new JPanel();
JPanel mainpanel = new JPanel();
JButton create;
JLabel welcome = new JLabel("Create Player");
JLabel name = new JLabel("Enter Player Name");
nameP = new JTextField();
JLabel pass = new JLabel("Enter Player Password");
password = new JTextField();
JLabel chips = new JLabel("Enter Player Chips");
chipsP = new JTextField();
buttonCreate = new JButton("Create Player");
setSize(400,350);
setLocation(500,280);
panel.setLayout(new GridLayout(0,1,10,10));
panel.add(name);
panel.add(nameP);
panel.add(pass);
panel.add(password);
panel.add(chips);
panel.add(chipsP);
panel.add(buttonCreate);
mainpanel.add(panel);
getContentPane().removeAll();
getContentPane().add(mainpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buttonCreate.addActionListener(new createListener());
}
}
private class playerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String username = nameP.getText();
String userpass = password.getText();
String hasheduserP = Utility.getHash(userpass);
String userchip = chipsP.getText();
String userContent = username + "|" + hasheduserP + "|" + userchip;
File file = new File("players.dat");
try{
//adding of user details
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("players.dat", true)));
out.println(userContent);
out.close();
JOptionPane.showMessageDialog(null,"User Created");
} catch (IOException ex){
System.out.println("Error Writing to File");
}
}
}
The file related part of your code works without any problem.
Hint: Improve it like this:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class SOPlayground {
public static void main(String[] args) throws Exception {
String userContent = "foo";
try {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/tmp/players.dat", true)))) {
out.println(userContent);
}
} catch (IOException ex) {
System.err.println("Error Writing to File: " + ex.getMessage());
}
}
}
The content of /tmp/players.dat now is
foo
I have a GUI that verifies a username and password. The other part of the assignment is to read from a file that contains a username and a password and checks to see if it matches what the user put in the text field. If it does match then it will hide the Login page and another page will appear with a "Welcome" message. I have zero experience with text files, where do I put that block of code? I assume it would go in the ActionListener method and not the main method but i'm just lost. I just need a little push in the right direction. Here is what I have so far. Any help would be greatly appreciated. Thanks!
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
/**
*/
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
listener = new ClickListener();
}
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
}
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}
import javax.swing.*;
import java.awt.*;
/**
*/
public class PassWordFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new PassWordFrame();
frame.setTitle("Password Verification");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
First of all you initialize the listener (listener = new ClickListener()) after the call to #createComponents() method so this means you will add a null listener to the login button. So your constructor should look like this:
public PassWordFrame() {
listener = new ClickListener();
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
Then, because you want to change the GUI with a welcome message, you should use a SwingWorker, a class designed to perform GUI-interaction tasks in a background thread. In the javadoc you can find nice examples, but here is also a good tutorial: Worker Threads and SwingWorker.
Below i write you only the listener implementation (using a swing worker):
class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
new SwingWorker<Boolean, Void>() {
#Override
protected Boolean doInBackground() throws Exception {
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
BufferedReader reader = new BufferedReader(new FileReader(userFile));
String user;
String pass;
try {
user = reader.readLine();
pass = reader.readLine();
}
catch (IOException e) {
//
// in case something is wrong with the file or his contents
// consider login failed
user = null;
pass = null;
//
// log the exception
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// ignore, nothing to do any more
}
}
if (usertext.getText().equals(user) && passtext.getText().equals(pass)) {
return true;
} else {
return false;
}
}
#Override
protected void done() {
boolean match;
try {
match = get();
}
//
// this is a learning example so
// mark as not matching
// and print exception to the standard error stream
catch (InterruptedException | ExecutionException e) {
match = false;
e.printStackTrace();
}
if (match) {
// show another page with a "Welcome" message
}
}
}.execute();
}
}
Another tip: don't add components to a JFrame, so replace this:
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
with:
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(panel1, BorderLayout.NORTH);
contentPane.add(panel2, BorderLayout.WEST);
contentPane.add(panel3, BorderLayout.CENTER);
contentPane.add(panel4, BorderLayout.SOUTH);
setContentPane(contentPane);
assume there is a textfile named password.txt in g driver and it contain usename and password separate by # symbol.
like following
password#123
example code
package homework;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
String info = ReadFile();
System.out.println(info);
String[] split = info.split("#");
String uname=split[0];
String pass =split[1];
if(usertext.getText().equals(uname) && passtext.getText().equals(pass)){
instruct.setText("access granted");
}else{
instruct.setText("access denided");
}
}
});
}
private static String ReadFile(){
String line=null;
String text="";
try{
FileReader filereader=new FileReader(new File("G:\\password.txt"));
//FileReader filereader=new FileReader(new File(path));
BufferedReader bf=new BufferedReader(filereader);
while((line=bf.readLine()) !=null){
text=text+line;
}
bf.close();
}catch(Exception e){
e.printStackTrace();
}
return text;
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}