I'm trying to make a program which the user signs up and his information gets output to a file using simple text output?
Here is my whole class..
package malkawi.login;
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.swing.*;
import malkawi.login.JTextFieldLimit;
/**
*
* #author Defiledx1
* sign up
*/
public class SignUp extends JFrame implements EventListener {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton complete = new JButton("Next");
JLabel fname = new JLabel("Name: ");
JLabel Mname = new JLabel("Middle Name: ");
JLabel Lname = new JLabel("Last Name: ");
JLabel user = new JLabel("Username: ");
JLabel pass = new JLabel("Password: ");
JLabel info = new JLabel("Click Next to Continue");
JLabel email = new JLabel("Email: ");
JLabel scode = new JLabel("Secret Code: ");
JTextField fname1 = new JTextField();
JTextField Mname1 = new JTextField();
JTextField Lname1 = new JTextField();
JTextField user1 = new JTextField();
JPasswordField pass1 = new JPasswordField();
JTextField email1 = new JTextField();
JTextField scode1 = new JTextField();
JRadioButton showPass = new JRadioButton("Show Pass");
public SignUp() {
super("Sign Up - Flare By Malkawi");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 400);
setResizable(false);
setVisible(true);
setVisible(true);
setLayout(new GridLayout(0, 2, 10, 10));
setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
/*
* Limitations
*/
fname1.setDocument(new JTextFieldLimit(10));
Mname1.setDocument(new JTextFieldLimit(1));
Lname1.setDocument(new JTextFieldLimit(10));
user1.setDocument(new JTextFieldLimit(15));
email1.setDocument(new JTextFieldLimit(80));
scode1.setDocument(new JTextFieldLimit(5));
/*
* End Of Limitations
*/
/*
* RadioButton Checked : Unchecked
*/
showPass.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
showPassword(e.getStateChange() == 1 ? true : false);
}
});
/*
* End of RadioButton Checked : UnChecked
*/
/*
* Action of registration
*/
complete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try {
outPutInformation();
} catch (FileNotFoundException | UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("Flare is unable at the moment!");
}
}
});
/*
* End of Action of registration
*/
// Dimension labelSize = info.getPreferredSize();
/*
* Start of placements
*/
//add(info);
add(fname);
add(fname1);
add(Mname);
add(Mname1);
add(Lname);
add(Lname1);
add(user);
add(user1);
add(pass);
add(pass1);
add(email);
add(email1);
add(scode);
add(scode1);
add(complete);
add(showPass);
add(info);
pack();
}
public void showPassword(boolean showP) {
if (showP == true) {
pass1.setEchoChar((char)0);
} else {
pass1.setEchoChar('*');
}
}
/*
* File Output Requirements
*/
String filename = user1.getText();
String firstname = fname1.getText();
String middlename = Mname1.getText();
String lastname = Lname1.getText();
String username = user1.getText();
#SuppressWarnings("deprecation")
String password = pass1.getText();
String hotmail = email1.getText();
String secretcode = scode1.getText();
/*
* File Output done
*/
public void outPutInformation() throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(filename+".txt", "UTF-8");
writer.println(firstname);
writer.println(middlename);
writer.println(lastname);
writer.println(username);
writer.println(password);
writer.println(hotmail);
writer.println(secretcode);
writer.close();
}
}
the problem is that it's not outputting anything out.
How is it possible to output the file like 2 folder behind
Thank you!
This is not outputting anything because your variables are initialized before entering anything in the text fields. you need to do like this, or directly write textfield values to the file instead if first saving to variables and then writing to file:
public void outPutInformation() throws FileNotFoundException, UnsupportedEncodingException {
String filename = user1.getText();
String firstname = fname1.getText();
String middlename = Mname1.getText();
String lastname = Lname1.getText();
String username = user1.getText();
#SuppressWarnings("deprecation")
String password = pass1.getText();
String hotmail = email1.getText();
String secretcode = scode1.getText();
PrintWriter writer = new PrintWriter(filename+".txt", "UTF-8");
writer.println(firstname);
writer.println(middlename);
writer.println(lastname);
writer.println(username);
writer.println(password);
writer.println(hotmail);
writer.println(secretcode);
writer.close();
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to compare the inputs of a login form (email and password ) to a text file content(the data are separated with a comma)
the text file looks like this :
email#gmail.com,password,name
my code that I have tried looks like this (the jTextField4 is for the email and jPasswordField1 is for the password) :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
boolean d = false;
Scanner read = new Scanner("data.txt");
read.useDelimiter(",");
while(read.nextLine() !=null){
String user = read.next();
String pass = read.next();
read.next();
if(jTextField4.getText().equals(user)&&jPasswordField1.getText().equals(pass)){
d=true;
break;
}
}
if(d)
JOptionPane.showMessageDialog(null, "Welcome");
else {
JOptionPane.showMessageDialog(null, "Incorrect username or password");
}
}
but it keeps giving me errors
You are using Scanner incorrectly.
Read a line from the file.
Split it on the comma. This will give you an array of two elements where the first element is the username and the second element is the password.
Then compare each element with its corresponding text component.
The while loop should look like the following.
boolean d = false;
while (read.hasNextLine()) {
String line = read.nextLine();
String[] parts = line.split(",");
d = jTextField4.getText().equals(parts[0]) && jPasswordField1.getText().equals(parts[1]);
if (d) {
break;
}
}
According to the javadoc for class java.util.Scanner, method nextLine throws NoSuchElementException when there are no more lines to be read. Hence the while loop calls method hasNextLine in order to make sure that there is another line to be read.
Similarly, method next throws NoSuchElementException when there are no more "tokens" to be read.
You are getting the exception because you are not checking for the end of the file. So if the username and password entered by the user (via the GUI) does not exist in the file, the while loop tries to read past the end of the file and that causes NoSuchElementException to be thrown.
EDIT
Here's how I would do it.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
import javax.swing.BorderFactory;
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;
public class PwChecks implements ActionListener, Runnable {
private static final String CHECK = "Check";
private JFrame frame;
private JPasswordField passwordField;
private JTextField textField;
public void actionPerformed(ActionEvent event) {
Path path = Paths.get("logindtl.txt");
try (Stream<String> lines = Files.lines(path)) {
String name = lines.filter(this::checkLine)
.map(line -> line.split(",")[2])
.findFirst()
.orElseThrow();
JOptionPane.showMessageDialog(frame,
"Welcome " + name,
"Login Successful",
JOptionPane.PLAIN_MESSAGE);
}
catch (IOException xIo) {
JOptionPane.showMessageDialog(frame,
xIo,
"ERROR",
JOptionPane.ERROR_MESSAGE);
}
catch (NoSuchElementException xNoSuchElement) {
JOptionPane.showMessageDialog(frame,
"Incorrect username or password",
"ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
public void run() {
createAndDisplayGui();
}
private boolean checkLine(String line) {
String[] fields = line.split(",");
String eMail = textField.getText();
char[] letters = passwordField.getPassword();
String password = new String(letters);
return eMail.equals(fields[0]) && password.equals(fields[1]);
}
private void createAndDisplayGui() {
frame = new JFrame("Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createLogin(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JButton createButton(String text, int mnemonic) {
JButton button = new JButton(text);
button.setMnemonic(mnemonic);
button.addActionListener(this);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton(CHECK, KeyEvent.VK_C));
return buttonsPanel;
}
private JPanel createLogin() {
JPanel login = new JPanel(new GridBagLayout());
login.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets.bottom = 5;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.insets.top = 5;
JLabel eMailLabel = new JLabel("eMail");
login.add(eMailLabel, gbc);
gbc.gridx = 1;
textField = new JTextField(12);
login.add(textField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
JLabel passwordLabel = new JLabel("Password");
login.add(passwordLabel, gbc);
gbc.gridx = 1;
passwordField = new JPasswordField(12);
login.add(passwordField, gbc);
return login;
}
public static void main(String[] args) {
EventQueue.invokeLater(new PwChecks());
}
}
Here is file logindtl.txt
email#gmail.com,password,name
Here is a screen capture of the GUI.
I've been trying to link my login code with a java gui that i created however i've been having problems when it comes to running it.
1) The code doesn't read the text file i have created
2) When i press the login for my gui, it does nothing. I want it to check the entered Username and password with the usernames and passwords in the text file.
Please help me, I've checked for other solutions but i couldn't find anything relevant to my problem.
I don't think i linked the code right so if anyone could help with that, that would be great.
First Class:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Login extends JFrame{
public JFrame frame;
public JPasswordField passwordField;
public JTextField textField;
public JButton blogin;
public JButton btnNewUser;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
frame = new JFrame();
frame.getContentPane().setLayout(null);
passwordField = new JPasswordField();
passwordField.setBounds(90, 114, 105, 22);
frame.getContentPane().add(passwordField);
textField = new JTextField();
textField.setBounds(90, 79, 105, 22);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(220, 82, 76, 16);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(220, 117, 66, 16);
frame.getContentPane().add(lblPassword);
JButton blogin = new JButton("Login");
blogin.setBounds(144, 158, 97, 25);
frame.getContentPane().add(blogin);
JButton btnNewUser = new JButton("New User ?");
btnNewUser.setBounds(144, 196, 97, 25);
frame.getContentPane().add(btnNewUser);
frame.add(blogin);
frame.add(passwordField);
frame.add(textField);
}
Logincode lc = new Logincode();
public void actionlogin(){
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
Scanner sc;
try {
sc = new Scanner(new File("Logincode.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scan = new Scanner(new File("Logincode.txt"));
Scanner keyboard = new Scanner (System.in);
String inpUser = keyboard.nextLine();
inpUser = textField.getText();
String inpPass = keyboard.nextLine();
inpPass = passwordField.getText();// gets input from user
String user = scan.nextLine();
String pass = scan.nextLine(); // looks at selected file in scan
if (inpUser.equals(user)&& inpPass.equals(pass)){
System.out.print("your login message");
}else {
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
}
}
});
}
}
And this is the second class:
import java.util.Scanner; // I use scanner because it's easier for me.
import java.io.File;
import java.io.FileNotFoundException;
public class Logincode{
public static void run() throws FileNotFoundException {
Scanner scan = new Scanner (new File("Logincode.txt"));
Scanner keyboard = new Scanner (System.in);
String inpUser = keyboard.nextLine();
String inpPass = keyboard.nextLine(); // gets input from user
String user = scan.nextLine();
String pass = scan.nextLine(); // looks at selected file in scan
if (inpUser.equals(user)&& inpPass.equals(pass)){
System.out.print("your login message");
} else {
System.out.print("your error message");
}
}
public static void main(String[] args){
try {
run();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Ok, there were too many errors to remember and list them all but here are a few:
One of the errors was creating a JFrame when your class already extended JFrame, essentially making it a JFrame.
You also only ever added the action listener for your login button in the actionlogin() method, which was never called.
There were multiple scanners pointing to the same file.
You tried to read input from the console and from the text fields then assign them to the same variable, twice.
You created a second class that has some of the same functionality as your "main" class, and both have main methods.
I left a bit of your code in so that you can see some of the errors and extra tidbits that you put in, that weren't needed. I also didn't fix your frame because there are many valuable lessons that can only be learned by trial and error when building a GUI.
Code:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Login extends JFrame{
//public JFrame frame; //Extends JFrame already so 'this' IS a frame
public JPasswordField passwordField;
public JTextField textField;
public JButton blogin;
public JButton btnNewUser;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //DO NOT forget this, the instance will continue to run if not.
setLayout(null);
setSize(350,300); // only added so I didn't have to expand window as often
passwordField = new JPasswordField();
passwordField.setBounds(90, 114, 105, 22);
add(passwordField);
textField = new JTextField();
textField.setBounds(90, 79, 105, 22);
add(textField);
textField.setColumns(10);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(220, 82, 76, 16);
add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(220, 117, 66, 16);
add(lblPassword);
JButton blogin = new JButton("Login");
blogin.setBounds(144, 158, 97, 25);
blogin.addActionListener(new ActionListener() { //moved from actionlogin()
public void actionPerformed(ActionEvent ae){
actionlogin();
}
});
add(blogin);
JButton btnNewUser = new JButton("New User ?");
btnNewUser.setBounds(144, 196, 97, 25);
add(btnNewUser);
add(blogin);
add(passwordField);
add(textField);
}
//Logincode lc = new Logincode(); Don't know why the second class was created or needed here.
public void actionlogin(){
//Scanner sc; not used
Scanner scan=null;
try {
//sc = new Scanner(new File("Logincode.txt")); not used
scan = new Scanner(new File("Change to the path where your file is located ofcourse")); //make sure to add your path
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Scanner keyboard = new Scanner (System.in);
//String inpUser = keyboard.nextLine();
String inpUser;
inpUser = textField.getText();
//String inpPass = keyboard.nextLine();
String inpPass;
inpPass = passwordField.getText();// gets input from user
String user="";
if(scan.hasNextLine()) //added to check if there is another line to read
user = scan.nextLine();
String pass="";
if(scan.hasNextLine())
pass = scan.nextLine(); // looks at selected file in scan
if (inpUser.equals(user)&& inpPass.equals(pass)){
System.out.print("your login message");
}else {
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
}
}
}
Hope this helps.
Sorry if I'm double positing but I totally suck at Java.
I am trying to make my form have the ability to change dynamically if you select a radio button. The functions save, delete, new will remain the same but the contents of the body e.g. the UPC will change to ISBN of the novel and the other fields.
Is there a way to when you press Novel to load the items from Novel to replace Comic book items?
I tried to separate but I've hit a block and with my limited skills unsure what to do.
I just want it to be able to change it so that it works.
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.MenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
public class FormFictionCatelogue extends JFrame implements ActionListener {
// Constants
// =========
private final String FORM_TITLE = "Fiction Adiction Catelogue";
private final int X_LOC = 400;
private final int Y_LOC = 80;
private final int WIDTH = 600;
private final int HEIGHT = 450;
private String gradeCode;
//final static String filename = "data/comicBookData.txt";
private JButton firstPageButton;
private JButton backPageButton;
private JButton forwardPageButton;
private JButton lastPageButton;
private JRadioButton comicBookRadioButton;
private JRadioButton novelRadioButton;
private final String FIRSTPAGE_BUTTON_TEXT = "|<";
private final String BACKPAGE_BUTTON_TEXT = "<";
private final String FORWARDPAGE_BUTTON_TEXT = ">";
private final String LASTPAGE_BUTTON_TEXT = ">|";
private final String COMICBOOK_BUTTON_TEXT = "Comic";
private final String NOVEL_BUTTON_TEXT = "Novel";
private final String SAVE_BUTTON_TEXT = "Save";
private final String EXIT_BUTTON_TEXT = "Exit";
private final String CLEAR_BUTTON_TEXT = "Clear";
private final String FIND_BUTTON_TEXT = "Find";
private final String DELETE_BUTTON_TEXT = "Delete";
private final String ADDPAGE_BUTTON_TEXT = "New";
// Attributes
private JTextField upcTextField;
private JTextField isbnTextField;
private JTextField titleTextField;
private JTextField issueNumTextField;
private JTextField bookNumTextField;
private JTextField writerTextField;
private JTextField authorTextField;
private JTextField artistTextField;
private JTextField publisherTextField;
private JTextField seriesTextField;
private JTextField otherBooksTextField;
private JTextField gradeCodeTextField;
private JTextField charactersTextField;
private JButton saveButton;
private JButton deleteButton;
private JButton findButton;
private JButton clearButton;
private JButton exitButton;
private JButton addPageButton;
FictionCatelogue fc;
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) {
try {
FormFictionCatelogue form = new FormFictionCatelogue();
form.fc = new FictionCatelogue();
form.setVisible(true);
//comicBook selected by default
form.populatefields(form.fc.returnComic(0));
//if novel is selected change fields to novel and populate
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
/**
*
*/
public FormFictionCatelogue() {
// Set form properties
// ===================
setTitle(FORM_TITLE);
setSize(WIDTH, HEIGHT);
setLocation(X_LOC, Y_LOC);
// Create and set components
// -------------------------
// Create panels to hold components
JPanel menuBarPanel = new JPanel();
JPanel fieldsPanel = new JPanel();
JPanel buttonsPanel = new JPanel();
JPanel navigationPanel = new JPanel();
//JPanel radioButtonsPanel = new JPanel();
ButtonGroup bG = new ButtonGroup();
// Set the layout of the panels
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
// Menu
JMenuBar menubar = new JMenuBar();
ImageIcon icon = new ImageIcon("exit.png");
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenu about = new JMenu("About");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit", icon);
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JMenuItem eMenuItem1 = new JMenuItem("Reports", icon);
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Reports are located here");
eMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
//calls reports
//System.exit(0);
}
});
file.add(eMenuItem);
about.add(eMenuItem1);
menubar.add(file);
menubar.add(about);
setJMenuBar(menubar);
setTitle("Menu");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//if comic is selected
ComicBookFields(fieldsPanel);
//else
//NovelFields(fieldsPanel);
// Buttons
comicBookRadioButton = new JRadioButton(COMICBOOK_BUTTON_TEXT);
novelRadioButton = new JRadioButton(NOVEL_BUTTON_TEXT);
bG.add(comicBookRadioButton);
bG.add(novelRadioButton);
this.setLayout(new FlowLayout());
this.add(comicBookRadioButton);
this.add(novelRadioButton);
comicBookRadioButton.setSelected(true);
bG.add(comicBookRadioButton);
bG.add(novelRadioButton);
addPageButton = new JButton(ADDPAGE_BUTTON_TEXT);
buttonsPanel.add(addPageButton);
saveButton = new JButton(SAVE_BUTTON_TEXT);
buttonsPanel.add(saveButton);
clearButton = new JButton(CLEAR_BUTTON_TEXT);
buttonsPanel.add(clearButton);
deleteButton = new JButton(DELETE_BUTTON_TEXT);
buttonsPanel.add(deleteButton);
findButton = new JButton(FIND_BUTTON_TEXT);
buttonsPanel.add(findButton);
exitButton = new JButton(EXIT_BUTTON_TEXT);
buttonsPanel.add(exitButton);
firstPageButton = new JButton(FIRSTPAGE_BUTTON_TEXT);
navigationPanel.add(firstPageButton);
backPageButton = new JButton(BACKPAGE_BUTTON_TEXT);
navigationPanel.add(backPageButton);
forwardPageButton = new JButton(FORWARDPAGE_BUTTON_TEXT);
navigationPanel.add(forwardPageButton);
lastPageButton = new JButton(LASTPAGE_BUTTON_TEXT);
navigationPanel.add(lastPageButton);
// Get the container holding the components of this class
Container con = getContentPane();
// Set layout of this class
con.setLayout(new BorderLayout());
con.setLayout( new FlowLayout());
// Add the fieldsPanel and buttonsPanel to this class.
// con.add(menuBarPanel, BorderLayout);
con.add(fieldsPanel, BorderLayout.CENTER);
con.add(buttonsPanel, BorderLayout.LINE_END);
con.add(navigationPanel, BorderLayout.SOUTH);
//con.add(radioButtonsPanel, BorderLayout.PAGE_START);
// Register listeners
// ==================
// Register action listeners on buttons
saveButton.addActionListener(this);
clearButton.addActionListener(this);
deleteButton.addActionListener(this);
findButton.addActionListener(this);
exitButton.addActionListener(this);
firstPageButton.addActionListener(this);
backPageButton.addActionListener(this);
forwardPageButton.addActionListener(this);
lastPageButton.addActionListener(this);
addPageButton.addActionListener(this);
comicBookRadioButton.addActionListener(this);
novelRadioButton.addActionListener(this);
// Exit program when window is closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void Radiobutton (){
this.add(comicBookRadioButton);
this.add(novelRadioButton);
comicBookRadioButton.setSelected(true);
this.setVisible(true);
}
// Populate the fields at the start of the application
public void populatefields(ComicBook cb) {
String gradecode;
// radio button selection = comic do this
if (cb != null) {
upcTextField.setText(cb.getUpc());
titleTextField.setText(cb.getTitle());
issueNumTextField.setText(Integer.toString(cb.getIssuenumber()));
writerTextField.setText(cb.getWriter());
artistTextField.setText(cb.getArtist());
publisherTextField.setText(cb.getPublisher());
gradecode = cb.getGradeCode();
gradeCodeTextField.setText(cb.determineCondition(gradecode));
charactersTextField.setText(cb.getCharacters());
}
//radio button selection = novel do this
// Exit program when window is closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
/**
*
*/
public void actionPerformed(ActionEvent ae) {
try {
if(ae.getActionCommand().equals(COMICBOOK_BUTTON_TEXT)){
//FormFictionCatelogue form = new FormFictionCatelogue();
//form.populatefields(form.fc.returnObject(0));
//ComicBookFields(fieldsPanel);
populatefields(fc.returnComic(0));
} else if (ae.getActionCommand().equals(NOVEL_BUTTON_TEXT)) {
} else if (ae.getActionCommand().equals(SAVE_BUTTON_TEXT)) {
save();
} else if (ae.getActionCommand().equals(CLEAR_BUTTON_TEXT)) {
clear();
} else if (ae.getActionCommand().equals(ADDPAGE_BUTTON_TEXT)) {
add();
} else if (ae.getActionCommand().equals(DELETE_BUTTON_TEXT)) {
delete();
} else if (ae.getActionCommand().equals(FIND_BUTTON_TEXT)) {
find();
} else if (ae.getActionCommand().equals(EXIT_BUTTON_TEXT)) {
exit();
} else if (ae.getActionCommand().equals(FIRSTPAGE_BUTTON_TEXT)) {
// first record
populatefields(fc.firstRecord());
} else if (ae.getActionCommand().equals(FORWARDPAGE_BUTTON_TEXT)) {
// next record
populatefields(fc.nextRecord());
} else if (ae.getActionCommand().equals(BACKPAGE_BUTTON_TEXT)) {
// previous record
populatefields(fc.previousRecord());
} else if (ae.getActionCommand().equals(LASTPAGE_BUTTON_TEXT)) {
// last record
populatefields(fc.lastRecord());
} else {
throw new Exception("Unknown event!");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error!",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
void clear() {
upcTextField.setText("");
titleTextField.setText("");
issueNumTextField.setText("");
writerTextField.setText("");
artistTextField.setText("");
gradeCodeTextField.setText("");
publisherTextField.setText("");
charactersTextField.setText("");
}
private void exit() {
System.exit(0);
}
void add() {
try{
clear();
ComicBook cb = new ComicBook();
fc.add(cb);
fc.lastRecord();
} catch (Exception e){
e.printStackTrace();
}
}
void save() throws Exception {
// if radio button = comic do this
ComicBook cb = new ComicBook();
String condition;
if (upcTextField.getText().length() == 16) {
//searches if there is another record if()
cb.setUpc(upcTextField.getText());
} else {
throw new Exception("Upc is not at required length ");
}
cb.setTitle(titleTextField.getText());
cb.setIssuenumber(Integer.parseInt(issueNumTextField.getText()));
cb.setWriter(writerTextField.getText());
cb.setArtist(artistTextField.getText());
cb.setPublisher(publisherTextField.getText());
condition = cb.determineString(gradeCodeTextField.getText());
if (condition.equals("Wrong Input")) {
throw new Exception("Grade code is not valid");
} else {
cb.setGradeCode(condition);
}
cb.setCharacters(charactersTextField.getText());
fc.save(cb);
// if radio button = novels do this
}
private void delete() throws Exception {
fc.delete();
populatefields(fc.getCurrentRecord());
}
private void find() {
// from
// http://www.roseindia.net/java/example/java/swing/ShowInputDialog.shtml
String str = JOptionPane.showInputDialog(null, "Enter some text : ",
"Comic Book Search", 1);
if (str != null) {
ComicBook cb = new ComicBook();
cb = fc.search(str);
if (cb != null) {
populatefields(cb);
} else {
JOptionPane.showMessageDialog(null, "No comic books found ",
"Comic Book Search", 1);
}
}
}
public JPanel ComicBookFields(JPanel fieldsPanel) {
// Create components and add to panels for ComicBook
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
fieldsPanel.setLayout(fieldsPanelLayout);
fieldsPanel.add(new JLabel("UPC: "));
upcTextField = new JTextField(20);
fieldsPanel.add(upcTextField);
fieldsPanel.add(new JLabel("Title: "));
titleTextField = new JTextField(20);
fieldsPanel.add(titleTextField);
fieldsPanel.add(new JLabel("Issue Number: "));
issueNumTextField = new JTextField(20);
fieldsPanel.add(issueNumTextField);
fieldsPanel.add(new JLabel("Writer: "));
writerTextField = new JTextField(20);
fieldsPanel.add(writerTextField);
fieldsPanel.add(new JLabel("Artist: "));
artistTextField = new JTextField(20);
fieldsPanel.add(artistTextField);
fieldsPanel.add(new JLabel("Publisher: "));
publisherTextField = new JTextField(20);
fieldsPanel.add(publisherTextField);
fieldsPanel.add(new JLabel("Grade Code: "));
gradeCodeTextField = new JTextField(20);
fieldsPanel.add(gradeCodeTextField);
fieldsPanel.add(new JLabel("Characters"));
charactersTextField = new JTextField(20);
fieldsPanel.add(charactersTextField);
return fieldsPanel;
}
public JPanel NovelFields(JPanel fieldsPanel) {
// Create components and add to panels for ComicBook
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
fieldsPanel.setLayout(fieldsPanelLayout);
fieldsPanel.add(new JLabel("ISBN: "));
isbnTextField = new JTextField(20);
fieldsPanel.add(isbnTextField);
fieldsPanel.add(new JLabel("Title: "));
titleTextField = new JTextField(20);
fieldsPanel.add(titleTextField);
fieldsPanel.add(new JLabel("Book Number: "));
bookNumTextField = new JTextField(20);
fieldsPanel.add(bookNumTextField);
fieldsPanel.add(new JLabel("Author: "));
authorTextField = new JTextField(20);
fieldsPanel.add(authorTextField);
fieldsPanel.add(new JLabel("Publisher: "));
publisherTextField = new JTextField(20);
fieldsPanel.add(publisherTextField);
fieldsPanel.add(new JLabel("Series: "));
seriesTextField = new JTextField(20);
fieldsPanel.add(seriesTextField);
fieldsPanel.add(new JLabel("Other Books"));
otherBooksTextField = new JTextField(20);
fieldsPanel.add(otherBooksTextField);
return fieldsPanel;
}
}
To swap forms you can use a CardLayout.
Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
The example from the tutorial switches when you make a selection from a combo box. In your case you would change the panel when you click on the radio button. So you might also want to read the section from the tutorial on How to Use Buttons.
Otherwise you can switch JPanels on JRadioButton selection like this:
You've got a JPanel called displayPanel which contains the ComicPanel by default, if you select the Novel RadioButton the displayPanel gets cleared and the NovelPanel will be added.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class AddNovelOrComicPanel extends JPanel implements ActionListener {
private JPanel selectPanel;
private JPanel displayPanel;
private JPanel buttonPanel;
private JRadioButton comic;
private JRadioButton novel;
// we need this ButtonGroup to take care about unselecting the former selected JRadioButton
ButtonGroup radioButtons;
public AddNovelOrComicPanel() {
this.setLayout(new BorderLayout());
initComponents();
this.add(selectPanel, BorderLayout.NORTH);
this.add(displayPanel, BorderLayout.CENTER);
}
/**
* Initializes all Components
*/
private void initComponents() {
selectPanel = new JPanel(new GridLayout(1, 2));
comic = new JRadioButton("Comic");
comic.setSelected(true);
comic.addActionListener(this);
novel = new JRadioButton("Novel");
novel.addActionListener(this);
radioButtons = new ButtonGroup();
radioButtons.add(comic);
radioButtons.add(novel);
selectPanel.add(comic);
selectPanel.add(novel);
displayPanel = new JPanel();
displayPanel.add(new ComicPanel());
}
#Override
public void actionPerformed(ActionEvent e) {
// if comic is selected show the ComicPanel in the displayPanel
if(e.getSource().equals(comic)) {
displayPanel.removeAll();
displayPanel.add(new ComicPanel());
}
// if novel is selected show the NovelPanel in the displayPanel
if(e.getSource().equals(novel)) {
displayPanel.removeAll();
displayPanel.add(new NovelPanel());
}
// revalidate all to show the changes
revalidate();
}
}
/**
* The NovelPanel class
* it contains all the Items you need to register a new Novel
*/
class NovelPanel extends JPanel {
public NovelPanel() {
this.add(new JLabel("Add your Novel components here"));
}
}
/**
* The ComicPanel class
*/
class ComicPanel extends JPanel {
public ComicPanel() {
this.add(new JLabel("Add your Comic components here"));
}
}
So it is your choice what you want to do. Possible is nearly everything ;)
Patrick
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I don't know much about SQL, but I'm fine with Java, I just wanted to know how I can retrieve a variable from my SQL database: 'EasyDirectory'. Like:
String test = con.getQuery(query1).get(username);
Obviously that doesn't work but I would like a snippet of code that does that. Heres all of my code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.ImageIcon;
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.JProgressBar;
import javax.swing.JTextField;
public class Directory {
public static void main(String args[]) throws IOException, SQLException {
Connection con = null;
try {
// Load the JDBC driver
String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);
// Create a connection to the database
String serverName = "www.freesql.org";
String mydatabase = "EasyDirectory";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
String username = "*********";
String password = "*********";
con = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
}
final JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
final JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(200, 30));
searchprogress.setPreferredSize(new Dimension(280, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
final List<String> housetypes = new ArrayList<String>();
String line = "";
BufferedReader br = new BufferedReader(new FileReader("Index.txt"));
while (line != null) {
line = br.readLine();
housetypes.add(line);
String seperation = br.readLine();
}
/* Finish Buffered Reader */
/* Start Content Code */
final JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
done.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchfield.setEnabled(true);
done.setVisible(false);
searchbutton.setVisible(true);
searchprogress.setValue(0);
}
});
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchprogress.setValue(100);
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
done.setVisible(true);
searchbutton.setVisible(false);
for (String housetype : housetypes) {
if (searchquery.equals(housetype)) {
String housepath = housetype + "/" + housetype + ".txt";
System.out.println(housepath);
try {
BufferedReader housebr = new BufferedReader(new FileReader(housepath));
String housename_query = housebr.readLine();
String housenumber_query = housebr.readLine();
String housestreet_query = housebr.readLine();
String houselocality_query = housebr.readLine();
String housepostal_query = housebr.readLine();
System.out.println(housepostal_query);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.setResizable(false);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(false);
/* Start Login Window */
int passtimes = 3;
final JFrame login = new JFrame("Login");
JPanel login_panel = new JPanel();
JLabel userlabel = new JLabel("Username: ");
JLabel passlabel = new JLabel(" Password: ");
JButton loginuser = new JButton("Login");
JButton cancel = new JButton("Cancel");
final JTextField user_field = new JTextField();
user_field.setPreferredSize(new Dimension(100,30));
final JPasswordField pass_field = new JPasswordField();
pass_field.setPreferredSize(new Dimension(100,30));
ImageIcon icon = new ImageIcon("Images/Logo.png");
ImageIcon space = new ImageIcon("Images/Spacing.png");
JLabel logo = new JLabel();
JLabel spacing = new JLabel();
logo.setIcon(icon);
login.setPreferredSize(new Dimension(200,212));
login_panel.add(logo);
login_panel.add(userlabel);
login_panel.add(user_field);
login_panel.add(passlabel);
login_panel.add(pass_field);
login_panel.add(spacing);
login_panel.add(loginuser);
login_panel.add(cancel);
login.add(login_panel);
login.pack();
login.setVisible(true);
login.setLocationRelativeTo(null);
loginuser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String user_input = user_field.getText();
String pass_input = pass_field.getText();
String username = "Tom";
String password = "******";
if(user_input.equals(username)){
if(pass_input.equals(password)){
user_field.setEnabled(false);
pass_field.setEnabled(false);
frame.setVisible(true);
login.setVisible(false);
}
else{//If Password AND Username is incorrect
JOptionPane.showMessageDialog(panel, "Password and/or Username Is Incorrect.", "Failed Login", JOptionPane.ERROR_MESSAGE);
}
}
else{ //If Username is incorrect
JOptionPane.showMessageDialog(panel, "Password and/or Username Is Incorrect.", "Failed Login", JOptionPane.ERROR_MESSAGE);
}
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
}
}
Thanks, Helping is greatly appreciated!
By reading the API of Connection (here: http://docs.oracle.com/javase/6/docs/api/java/sql/Connection.html) I would assume that it would have to be something like:
final Statement statement = con.createStatement();
final ResultSet result = statement.executeQuery(query1);
//do stuff with the resultset
//result.getString(something), see http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html
On a side-note. I don't really like the fact that you have put both the GUI and the database logic in the same class. You really should separate concerns, by applying the MVC pattern or something similar. For instance, you could create one class for the GUI, one class for to the connection the database, and one class for starting the application and tying the two others together.
I am looking for a quick fix to this problem I have: Here is my code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory{
public static void main(String args[]) throws IOException{
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300,300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(100,30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
String housetype = br.readLine();
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if(searchquery.equals(housetype)){
System.out.println("We Have Found A Record!!");
}}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
Basically After I wrote this code, Eclipse told me I had to change the modifier of housetype, to final. Which truly won't do, because I need to be a changing value if its going to go trough different records.
PLEASE HELP ME! D:
You have several options here:
The quickest would be to do what Eclipse tells you, actually it is Java that tells you that. In order to be able to use method local variables inside inner classes inside the method, the variables must be final.
Another option is to declare the housetype variable as an instance variable, immediately after the class definition. But, using it in the static main method means that the variable needs to be static too, which makes it a class variable.
Another one would be to keep the code as you have, but declare an extra variable like below and then use the house variable inside the inner class instead of housetype. See the entire code below:
public class Directory {
public static void main(String args[]) throws IOException {
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(100, 30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
final List<String> housetypes = new ArrayList<String>();
String line = "";
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
while (line != null) {
line = br.readLine();
housetypes.add(line);
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
}
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
for (String housetype : housetypes) {
if (searchquery.equals(housetype)) {
System.out.println("We Have Found A Record!!");
}
}
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
There are even more options, but these are the quickest.
One workaround is that you create a new method inside your class Directory that is being called from the ActionListener and does your tasks:
private void searchButtonAction() {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if(searchquery.equals(housetype)){
System.out.println("We Have Found A Record!!");
}
}
and then call it like this:
public void actionPerformed(ActionEvent ae)
{
searchButtonAction();
});
This only works if you create a constructor in the class and call it from the main method. Furthermore all variables used inside the searchButtonAction method must be class visible.
Full code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory {
private final JTextField searchfield = new JTextField();
private final JProgressBar searchprogress = new JProgressBar();
private String housetype;
public Directory() throws IOException {
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
searchfield.setPreferredSize(new Dimension(100, 30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
housetype = br.readLine();
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchButtonAction();
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private void searchButtonAction() {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if (searchquery.equals(housetype)) {
System.out.println("We Have Found A Record!!");
}
}
public static void main(String args[]) throws IOException {
new Directory();
}
}