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.
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 am trying to build a quiz app and I managed to build the database. I created a GUI using the card layout to switch between panels and I tried to retrieve the questions and options from from the database to a JtextArea with no success. My question is how do I get the visual components (jtext area,jbutton to display the content from the database) I want them to automatically set the text according with the question number.
this is my code
package quizzGUI;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.List;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JRadioButton;
import javax.swing.JTextPane;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.management.Query;
import javax.swing.ButtonGroup;
public class quizzMain {
private JFrame frame;
private JPanel Menu;
private JPanel Playing;
private JPanel Score;
private final ButtonGroup buttonGroup = new ButtonGroup();
public JTextPane textPane;
public JButton btnA;
public JRadioButton rdbtnB;
public JRadioButton rdbtnC;
public JRadioButton rdbtnD;
public JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
quizzMain window = new quizzMain();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
Connection connection = null;
public quizzMain() {
initialize();
connection = sqlConnection.dbConnector();
}
private void initialize() {
Connection connection = sqlConnection.dbConnector();
Statement stmt=null;
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel Menu = new JPanel();
frame.getContentPane().add(Menu, "name_668313932787145");
Menu.setLayout(null);
Menu.setVisible(true);
final JPanel Playing = new JPanel();
Playing.setBackground(Color.CYAN);
frame.getContentPane().add(Playing, "name_668321772390383");
Playing.setLayout(null);
Playing.setVisible(false);
final JPanel Score = new JPanel();
frame.getContentPane().add(Score, "name_668324579994343");
Score.setLayout(null);
Score.setVisible(false);
JLabel lblNewLabel = new JLabel("C QUIZZ");
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD | Font.ITALIC, 14));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(123, 47, 169, 40);
Menu.add(lblNewLabel);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Integer i=0;
Playing.setVisible(true);
Menu.setVisible(false);
try{
String query = ("SELECT * FROM Question ");
PreparedStatement pst=connection.prepareStatement(query);
ResultSet rs=pst.executeQuery();
do {
btnA.setText(rs.getString("ANSWERA"));
}while(rs.next());
}catch(Exception e ){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
});
btnStart.setFont(new Font("Tahoma", Font.BOLD, 12));
btnStart.setBounds(167, 176, 89, 23);
Menu.add(btnStart);
JButton btnFinish = new JButton("Finish");
btnFinish.setBounds(335, 227, 89, 23);
Playing.add(btnFinish);
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Score.setVisible(true);
Playing.setVisible(false);
}
});
JButton btnNextQuestion = new JButton("Next");
btnNextQuestion.setBounds(10, 227, 89, 23);
Playing.add(btnNextQuestion);
JTextArea textArea = new JTextArea();
textArea.setBounds(20, 11, 387, 41);
Playing.add(textArea);
JButton btnA = new JButton("New button");
btnA.setBounds(20, 84, 381, 41);
Playing.add(btnA);
JTextArea txtrScore = new JTextArea();
txtrScore.setBounds(87, 74, 244, 43);
txtrScore.setText("Score:");
Score.add(txtrScore);
}
}
Since you didn't mention your code, its difficult to give you a short precise example. I would recommend you to go through this tutorial which retrieves information (name and number) and display it in JTextArea.
Extracting the key points from the tutorial below:
Database connection establishment and fetching information
String url = "jdbc:mysql://localhost:3306/";
String db = "databasename";
String driver = "com.mysql.jdbc.Driver";
String user = "xxxx";
String pass = "xxxx";
Connection con = null;
PreparedStatement pstatement = null;
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db , user, pass);
pstatement = con.prepareStatement("SELECT name, phonenumber FROM tablename");
con = DriverManager.getConnection(url + db, user, pass);
ResultSet rs = pstatement.executeQuery();
while(rs.next()){
String name = rs.getString(1);
int phonenumber = rs.getInt(2);
}
Set text in JTextArea
Then use setText method of JTextArea to set the text. For example, recordTextArea.setText(name + " " + phonenumber);.
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();
}
Am trying to create login page for my application and i did it well but i couldn't able to add a image to my JFrame, here is my code for login page....
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.*;
public class log extends JFrame {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://sqldatabase.com/databasename";
// Database credentials
static final String USER = "usernamr";
static final String PASS = "pass";
public static void main(String[] args) throws IOException {
log frameTabel = new log();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JLabel label = new JLabel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
log() throws IOException{
super("Login Autentification");
setSize(500,500);
setLocation(300,280);
panel.setLayout (null);
//ImageIcon image = new ImageIcon("image.jpeg");
//JLabel hangman = new JLabel(new ImageIcon(urlOfImageFile));
//panel.add(image, BorderLayout.NORTH);
//Image image = ImageIO.read(new File("F:\\IModubytes\\Images\\1.jpg"));
//JLabel picLabel = new JLabel(new ImageIcon(image));
//panel.add(picLabel);
//panel.repaint();
txuser.setBounds(300,100,150,20);
pass.setBounds(300,135,150,20);
blogin.setBounds(380,170,80,20);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin(){
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String puname = txuser.getText();
String ppaswd = pass.getText();
String sql = "SELECT * FROM EmpDetails WHERE id="+puname;
System.out.println(puname);
ResultSet rs = stmt.executeQuery(sql);
String pw = null;
while(rs.next()) {
pw = rs.getString("pass");
}
rs.close();
//if(puname.equals("test") && ppaswd.equals(pw)) {
if(ppaswd.equals(pw)) {
newFrame regFace =new newFrame();
regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Can anyone please help me how to add image in this....
You already have the code to load the image and add the label to your frame.
So the next step is to add your components to the label and then add the label to the content pane, instead of adding the components to the panel and adding the panel to the content pane.
Also, don't use a null layout!!! Swing was designed to be used with layout mangers. Read the section from the Swing tutorial on Layout Managers for more information and working examples.
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();
}
}