I'm facing a problem in this program there are two GUI's.When user click on button it checks for a database connection when connection become successful then second GUI appear which has JComboBox. But the problem is it doesn't show the catalogs of mysql in JComboBox.
Main Method:
public class Main {
public static void main(String[] args) {
Gui obj = new Gui();
}
}
First Gui
public class Gui extends JFrame {
Connector c = new Connector();
private JButton b1;
public Gui() {
b1 = new JButton("Click To Connect");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (c.getConnect() == true) {
dispose();
new Gui2();
}
}
});
add(b1);
setLayout(new FlowLayout());
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Connection Class
public class Connector {
private Connection conn;
public boolean getConnect() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "john", "root");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
if (conn == null) {
System.out.println("Connection Failed");
return false;
}
System.out.println("Connection Success");
return true;
}
}
ComboBox GUI
public class Gui2 extends JFrame {
private JComboBox box;
Connection connection;
public Gui2() {
box = new JComboBox();
opencatalog();
add(box);
setLayout(new FlowLayout());
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private void opencatalog() {
try {
DatabaseMetaData meta = connection.getMetaData();
ResultSet rs = meta.getCatalogs();
List ct = new ArrayList();
while (rs.next()) {
ct.add(rs.getString(1));
}
rs.close();
box.setModel(new DefaultComboBoxModel(ct.toArray()));
box.setSelectedItem(connection.getCatalog());
box.setEnabled(ct.size() > 0);
}
catch (Exception e) {
System.out.println(e.toString());
}
box.setEnabled(false);
}
}
Connector class
change the return type to Connection and return conn.
public Connection getConnect() {
....
return conn
}
Gui class, change the condition
public void actionPerformed(ActionEvent arg0) {
Connection conn= c.getConnect();
if (conn!=null) {
new Gui2(conn);//pass connection object here
dispose();
}
}
Gui2 class, constructor should be
public Gui2(Connection conn)
{
connection=conn;
box = new JComboBox();
.................
}
Gui2 class,
box.setEnabled(true);//should be enabled,
Related
I want to enter data through textfields and save them. But buttons are not working. There are no errors while I'm compiling and not even in database connection. I guess there is a logical error.
public class Database {
private static JPanel panel;
private static JLabel sname;
private static JLabel saddress;
private static JTextField t;
private static JTextField t1;
private static JButton Delete = new JButton("Delete");
private static JButton update = new JButton("Update");
private static JButton save = new JButton("Save");
private static Container c;
private static Connection con;
private static Statement st;
private static ResultSet rs;
Database() {
connect();
}
public void connect(){
try{
System.out.println("Entered");
System.out.println("Database connection started...");
con=DriverManager.getConnection("jdbc:ucanaccess://D:\\test.mdb");
System.out.println("Hello satarted");
st = con.createStatement();
System.out.println("Connection ok.");
while(rs.next())
{
System.out.println(rs.getString("Student Name"));
System.out.println(rs.getString("Student Address"));
System.out.println();
}
catch (SQLException e){
System.err.println("Exception: " + e.getMessage());
}
}
public static void main(String[] args) {
Database gui = new Database();
JFrame f = new JFrame();
f.setTitle("School Management System");
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sname = new JLabel("Student Name");
t = new JTextField(10);
saddress = new JLabel("Student Address");
t1 = new JTextField(10);
panel = new JPanel();
panel.add(sname);
panel.add(t);
panel.add(saddress);
panel.add(t1);
// panel.add(insert);
panel.add(Delete);
panel.add(update);
panel.add(save);
f.add(panel);
try {
rs.next();
t.setText(rs.getString("Student Name"));
t1.setText(rs.getString("Student Address"));
} catch (Exception ex) {
}
}
public void btnAction() {
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = t.getText();
String address = t1.getText();
try {
rs.moveToInsertRow();
rs.updateString("Student Name", name);
rs.updateString("Student Address", address);
rs.insertRow();
rs.close();
} catch (Exception ex) {
}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String sname = t.getText();
String saddress = t1.getText();
try {
rs.updateString("Student name", sname);
rs.updateString("Student address", saddress);
rs.updateRow();
JOptionPane.showMessageDialog(null, "Record Updated!");
} catch (Exception e) {
}
}
});
}
}
when i removed static from each of these variables. I got so many errors
Yes, any time you see a class full of static variables you know the class is designed incorrectly.
Start with the working example from the Swing tutorial on How to Use Text Field. Download the TextDemo code and understand how it works and then make the changes for your logic.
Note how the class extends a JPanel where all the variables and components are defined and there is no need for any static variable. Your code should look something like this.
Once you have a better designed class you can then start to debug your code to figure out why the SQL isn't working.
In gui user enter username and password then click ok button.But the problem is i don't know how to connect with my Connector Class with ok button. And Give restriction to that button when user enter correct fields then connect to database.
Main Method
public class Main {
public static void main(String[] args) {
Gui obj = new Gui();
Connector conn = new Connector(obj.Setproperty());
}
}
Gui Class
public class Gui extends JFrame implements ActionListener{
private JLabel label1;
private JLabel label2;
private JTextField t1;
private JTextField t2;
private JButton ok;
private JPanel p1,p2;
Properties property;
public Gui(){
super("GUI");
p1 = new JPanel();
p1.setLayout(new GridLayout(0,2));
p2=new JPanel();
label1 = new JLabel("User Name");
t1 = new JTextField();
label2 = new JLabel("Password");
t2 = new JTextField();
ok= new JButton("OK");
ok.addActionListener(this);
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.SOUTH);
p1.add(label1);
p1.add(t1);
p1.add(label2);
p1.add(t2);
p2.add(ok);
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
property = new Properties();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==ok){
}
}
public Properties Setproperty(){
property.setProperty("UNAME",t1.getText());
property.setProperty("PWD",t2.getText());
return property;
}
}
Connector Class
public class Connector {
Connection conn;
Statement state;
String username;
String pass;
String url;
public Connector(Properties p) {
username = p.getProperty("UNAME");
pass = p.getProperty("PWD");
url= "jdbc:mysql://localhost/world";
}
public boolean open() {
try {
conn = DriverManager.getConnection(url, username, pass);
state = conn.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
e.printStackTrace();
}
if(conn==null){
System.out.println("Connection is NULL or server not connected");
return false;
}
System.out.println("Connection Successfull");
return true;
}
}
Try changing the actionPerformed method to this:
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==ok){
Properties prop = Setproperty();
Connector c = new Connector(prop);
c.open();
}
}
I've been working on building a chat server to learn about threading and using sockets. I used head first java as a guide (and I'm still confused about a couple of things, which is why I have this question probably :D) and the code below is what I have.
If you read my code, you'll see that I have clients connect to the server by clicking on a "connect" button. When they do that, a new jframe pops up that asks for their preferred name for the chat session. When they input that, it's saved in a String in the client code. My question is, how do I get this name over to the server, and make it so that every time the client sends a message, their name is displayed before their message?
Thank you for the help!!!
(ALSO, if anyone knows a good link that can explain sockets and how socket/client interaction occurs through threads, that would be great!)
server code:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class GameServerOne {
ArrayList clientOutputStreams;
String clientName;
private class ClientThreadHandler implements Runnable {
BufferedReader clientIncomingReader;
Socket socket1;
public ClientThreadHandler(Socket clientSocket2) {
try {
socket1 = clientSocket2;
InputStreamReader clientInputReader = new InputStreamReader(socket1.getInputStream());
clientIncomingReader = new BufferedReader(clientInputReader);
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
String message;
try {
while ((message = clientIncomingReader.readLine()) != null) {
tellEveryone(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void setUpServer() {
clientOutputStreams = new ArrayList();
try {
ServerSocket gameSocket = new ServerSocket(5151);
//System.out.println("Server Connected");
while (true) {
Socket clientSocket = gameSocket.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
writer.println("User connected");
writer.flush();
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientThreadHandler(clientSocket));
t.start();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
new GameServerOne().setUpServer();
}
}
Client code:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GameClientOne {
Socket gameSocket;
JFrame inputNameFrame;
JFrame clientFrame;
JTextArea chatArea;
JTextField messageInput;
BufferedReader gameChatReader;
PrintWriter gameChatWriter;
JTextField nameField;
boolean sessionNamePicked = false;
String userSessionName;
BufferedReader gameBufferedReader;
public GameClientOne () {
setUpGUI();
}
public void setUpGUI() {
clientFrame = new JFrame("Game Window");
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel southPanel = new JPanel(new BorderLayout());
JPanel centerPanel = new JPanel(new BorderLayout());
chatArea = new JTextArea();
chatArea.setWrapStyleWord(true);
chatArea.setLineWrap(true);
chatArea.setEditable(false);
JScrollPane chatScroller = new JScrollPane(chatArea);
messageInput = new JTextField();
messageInput.addKeyListener(new MessageInputFieldListener());
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
JPanel westPanel = new JPanel(/*new GridLayout(20, 1)*/);
JPanel eastPanel = new JPanel();
JButton connectButton = new JButton("Connect");
connectButton.addActionListener(new ConnectButtonListener());
connectButton.setPreferredSize(new Dimension(100, 28));
JPanel northPanel = new JPanel(new FlowLayout());
JLabel northTitleLabel = new JLabel("Game Screen");
westPanel.add(connectButton);
chatScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) ;
chatScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
northPanel.add(northTitleLabel);
centerPanel.add(BorderLayout.CENTER, chatScroller);
southPanel.add(BorderLayout.CENTER, messageInput);
southPanel.add(BorderLayout.EAST, sendButton);
mainPanel.add(BorderLayout.SOUTH, southPanel);
mainPanel.add(BorderLayout.CENTER, centerPanel);
mainPanel.add(BorderLayout.WEST, westPanel);
mainPanel.add(BorderLayout.EAST, eastPanel);
mainPanel.add(BorderLayout.NORTH, northPanel);
clientFrame.add(mainPanel);
clientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
clientFrame.setSize(450, 600);
clientFrame.setVisible(true);
messageInput.requestFocusInWindow();
}
public void setUpInputNameFrame() {
inputNameFrame = new JFrame("Insert Name");
JPanel mainPanel = new JPanel(new BorderLayout());
nameField = new JTextField();
nameField.addKeyListener(new NameFieldListener());
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(new SubmitButtonListener());
JLabel inputNameLabel = new JLabel("Please pick a name for the chat session");
JPanel northPanel = new JPanel(new FlowLayout());
JPanel southPanel = new JPanel(new BorderLayout());
northPanel.add(inputNameLabel);
southPanel.add(BorderLayout.CENTER, nameField);
southPanel.add(BorderLayout.EAST, submitButton);
mainPanel.add(BorderLayout.NORTH, northPanel);
mainPanel.add(BorderLayout.SOUTH, southPanel);
inputNameFrame.add(mainPanel);
inputNameFrame.setSize(300, 150);
inputNameFrame.setVisible(true);
nameField.requestFocusInWindow();
}
public void connectToGameServer() {
try {
gameSocket = new Socket("127.0.0.1", 5151);
InputStreamReader gameSocketReader = new InputStreamReader(gameSocket.getInputStream());
gameBufferedReader = new BufferedReader(gameSocketReader);
gameChatWriter = new PrintWriter(gameSocket.getOutputStream());
chatArea.append("Connected with name: " + userSessionName + "\n");
Thread incomingTextThread = new Thread(new IncomingTextReader());
incomingTextThread.start();
//System.out.println("Connected to Game");
} catch (Exception e) {
System.out.println("Could not connect to game...");
e.printStackTrace();
}
}
//ALL LISTENER CLASSES BELOW HERE
//main chat page listeners
private class ConnectButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!sessionNamePicked) {
setUpInputNameFrame();
} else {
chatArea.append("You already connected!\n");
}
}
}
private class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!sessionNamePicked) {
chatArea.append("Please connect first\n");
messageInput.setText("");
messageInput.requestFocusInWindow();
} else {
try {
gameChatWriter.println(messageInput.getText());
gameChatWriter.flush();
} catch (Exception ex2) {
ex2.printStackTrace();
}
//chatArea.append(userSessionName + ": " + messageInput.getText() + "\n");
messageInput.setText("");
messageInput.requestFocusInWindow();
}
}
}
private class MessageInputFieldListener implements KeyListener {
public void keyPressed(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (!sessionNamePicked) {
chatArea.append("Please connect first\n");
messageInput.setText("");
} else {
try {
gameChatWriter.println(messageInput.getText());
gameChatWriter.flush();
} catch (Exception ex2) {
ex2.printStackTrace();
}
//chatArea.append(userSessionName + ": " + messageInput.getText() + "\n");
messageInput.setText("");
}
}
}
}
//pick chat session name listeners: nameField/submitButton
private class NameFieldListener implements KeyListener {
public void keyPressed(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (!nameField.getText().isEmpty() && e.getKeyCode() == KeyEvent.VK_ENTER) {
userSessionName = nameField.getText();
sessionNamePicked = true;
connectToGameServer();
inputNameFrame.dispose();
messageInput.requestFocusInWindow();
}
}
}
private class SubmitButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (!nameField.getText().isEmpty()) {
userSessionName = nameField.getText();
sessionNamePicked = true;
connectToGameServer();
inputNameFrame.dispose();
messageInput.requestFocusInWindow();
}
}
}
//Runnable implementation for threads
private class IncomingTextReader implements Runnable {
public void run() {
String incomingMessage;
try {
while ((incomingMessage = gameBufferedReader.readLine()) != null) {
chatArea.append(incomingMessage + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
GameClientOne gameClient = new GameClientOne();
}
}
If you want to send more than just a message as you are now, you are going to need a protocol to decide what to do with the string you receive, instead of just sending it to all the other clients.
For example, on the client side to send the client's name you might write NAME:(client's name), and then on the server you would split the string at the : and check if the first part is NAME, and if so set the clients name to the rest of the string. You should think about what other types of data you might want to send aswell and design a protocol that works for it.
Here's an example of how to do the above:
On the client you could add the line gameChatWriter.write("NAME:"+name) (create name first of course) imediatly after the connection is made. Then on the server, instead of calling tellEveryone(message) when the message is recieved create a method called processInput and call it, which might look like this:
private void processInput(String message){
String[] commands=message.split(':');
if(commands[0].equals("NAME")){
clientName=commands[1];
}
else{
tellEveryone(message);
}
}
Right now you only have one String clientName and you will obviously need more for the other clients you want to talk to so I would recommend making the thread handler into a seperate class which you would instantiate for each client and could hold things like that.
After you get this to work you could also create a seperate method to write other things that you want to send to either the client or server and a method to process input on the client side as well. Hope this helps.
Trying to set up a JDBC that checks a database for a matching username and password, and they when the login button is pressed if matching the user is granted access, I've got my current code here, but I'm unsure what is missing when I launch the program it seems like its not checking the database for the correct information.
Updated:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class NewClass extends JFrame {
private JTextField jtfUsername, jtfPassword;
private JButton backButton, loginButton;
private JMenuItem jmiLogin, jmiBack, jmiHelp, jmiAbout;
NewClass() {
//create menu bar
JMenuBar jmb = new JMenuBar();
//set menu bar to the applet
setJMenuBar(jmb);
//add menu "operation" to menu bar
JMenu optionsMenu = new JMenu("Options");
optionsMenu.setMnemonic('O');
jmb.add(optionsMenu);
//add menu "help"
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
jmb.add(helpMenu);
//add menu items with mnemonics to menu "options"
optionsMenu.add(jmiLogin = new JMenuItem("Login", 'L'));
optionsMenu.addSeparator();
optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));
//panel p1 to holds text fields
JPanel p1 = new JPanel(new GridLayout(2, 2));
p1.add(new JLabel("Username"));
p1.add(jtfUsername = new JTextField(15));
p1.add(new JLabel("Password"));
p1.add(jtfPassword = new JPasswordField(15));
//panel p2 to holds buttons
JPanel p2 = new JPanel(new FlowLayout());
p2.add(backButton = new JButton("Back"));
p2.add(loginButton = new JButton("Login"));
//Panel with image??????
//add panels to frame
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(p1, BorderLayout.CENTER);
panel.add(p2, BorderLayout.SOUTH);
add(panel, BorderLayout.CENTER);
setTitle("Main Page");
//listners for exit menuitem and button
jmiBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
//listner for about menuitem
jmiAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This is the login panel"
+ "\n Assignment for University",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
//action listeners for Login in button and menu item
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText()); {
System.out.println("User is validated");
}
} catch (SQLException se) {
}
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
jmiLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
}
public static void main(String arg[]) {
log frame = new log();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class usernamecheck {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/test";
static final String USERNAME = "root";
static final String PASSWORD = "root";
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
}
Make your checkLogin method return boolean type and return true inside if (orPass.equals(password)) { block. Check whether the method true if so grant access.
You are missing a return type in your checkLogin method. You may return a boolean value to validate the user. Also add some logging/sysout to make sure what is happening in your code.
Update your method as :
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
rs.close();
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
And then update your user check as
try {
if(usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText())) {
System.out.println("User is validated");
} else {
return;
}
} catch (SQLException se) {
}
Every thing is right in the given program but connection to database is not established.
What could be the possible reason?Is it driver related problem. I want to do this without DSN.
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class FormAccess1 extends Frame implements ActionListener {
private static ResultSet rs;
Panel p1;
TextField t1, t2;
Button next;
public FormAccess1() {
super("Applicant Detail");
setLayout(new GridLayout(5, 1));
p1 = new Panel();
t1 = new TextField(10);
t2 = new TextField(10);
add(p1);
next = new Button("Next");
p1.add(new Label("book-id"));
p1.add(t1);
p1.add(new Label("book-title"));
p1.add(t2);
p1.add(next);
next.addActionListener(this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == next) {
try {
rs.next();
} catch (Exception em) {
}
showRecord(rs);
}
}
public void showRecord(ResultSet rs) {
try {
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
} catch (Exception ex) {
}
}
public static void main(String arg[]) {
FormAccess1 app = new FormAccess1();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.accdb)};DBQ=MyDatabase.accdb;DriverID=01";
Connection con = DriverManager.getConnection(database, "", "");
Statement state = con.createStatement();
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
rs.next();
app.showRecord(rs);
} catch (Exception ey) {
}
}
}
Verify you have de correct access drivers in the machine (Access 2013 redistributables). It could be x86 or x64. Jre/Jdk should be in concordance: x86 or x64