Getting a table from my database to display in a JPanel - java

I am pretty new to Java, and I am dabbling in a small Point of Sale program just to teach myself how it works. My goal is to get a table from my database which stores the inventory data and display it within my JPanel I made. I thought what I did would work, but when I click my Load Database button, nothing displays. This is the first time I am working with java.sql so my knowledge of it is very basic. It may even be an obvious issue that I don't even see. Here's what I'm working with.
package gui;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import net.proteanit.sql.DbUtils;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class tableTest {
private JFrame frame;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tableTest window = new tableTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tableTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 804, 484);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 768, 382);
frame.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JButton tableBtn = new JButton("Load Data");
tableBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String tableQuery = "SELECT * FROM inventory";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bazaar", "root", "password");
PreparedStatement ps = con.prepareStatement(tableQuery);
ResultSet rs = ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e) {
e.printStackTrace();
}
}
});
tableBtn.setBounds(350, 411, 89, 23);
frame.getContentPane().add(tableBtn);
}
}
Just edited the code to make it a bit more simple to look at. I have data in the database, so I know that isn't the issue, but I cannot figure out how to get that data to display in the table.

Related

How to resolve the nullpointer exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
While working on a GUI project i am stuck with an error called null pointer error.
I am unable to resolve this problem.
The line which shows the error is closed by double asterisk on both sides(**).(line 80)
I have connected this with a SQL database and error erupts while assigning Jtable its value and structure.
package connectsqlite;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;
public class afterLogin extends JFrame {
public JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
afterLogin frame = new afterLogin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connect = null;
public afterLogin() {
connect = sqliteConnection.conn();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 695, 422);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnBack = new JButton("Log out");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connecting window = new Connecting();
window.frame.setVisible(true);
}
});
btnBack.setBounds(10, 62, 114, 23);
contentPane.add(btnBack);
JButton btnNewButton = new JButton("Load Details");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String query = "SELECT * FROM Appointments";
PreparedStatement pst = connect.prepareStatement(query);
ResultSet rs = pst.executeQuery();
**table.setModel(DbUtils.resultSetToTableModel(rs));**
}
catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(10, 28, 114, 23);
contentPane.add(btnNewButton);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(162, 57, 435, 305);
contentPane.add(scrollPane);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane.setViewportView(scrollPane_1);
}
}
You haven't instantiated your table, it's only declared. Therefore, when you call setModel on it it's going to cause a NullPointerException.

SQLite database not displaying on button click

Evening all,
So I've been working on creating a local database using SQLite. (As a plugin that is part of Firefox). It uses three classes:
databaseConnection
Login
Display
and two tables (which come under the database MyFilms) called:
Users
MyFilms
databaseConnection is used to simply just connect to my SQLite database MyFilms, which it does fine.
The second class, Login, access my Users table from my database so it can access the logins and proceed to my GUI called Display.
Display will load the following GUI, which consists of a button, which when clicked is supposed to load the data from my database table MyFilms into a JTable:
However, when I click the button, nothing loads... it even looks like the JTable is not there, but when I check my code it defiantly is!
The code where I think the problem might lie is:
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
Any idea why the database is not showing here? Please find the code to each class below:
databaseConnection:
import java.sql.*;
import javax.swing.*;
public class databaseConnection {
Connection conn = null;
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Joe\\workspace\\MyFilms.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!");
return conn;
}
catch(Exception anException)
{
JOptionPane.showMessageDialog(null, anException);
return null;
}
}
}
Login:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frmTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frmTest.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField textFieldUN;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
connection = databaseConnection.dbConnector();
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frmTest = new JFrame();
frmTest.setTitle("Database Login");
frmTest.setBounds(100, 100, 345, 184);
frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTest.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(34, 37, 64, 14);
frmTest.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Password:");
lblNewLabel_1.setBounds(34, 66, 64, 14);
frmTest.getContentPane().add(lblNewLabel_1);
textFieldUN = new JTextField();
textFieldUN.setBounds(126, 34, 151, 20);
frmTest.getContentPane().add(textFieldUN);
textFieldUN.setColumns(10);
JButton btnLogin = new JButton("Login");
frmTest.getRootPane().setDefaultButton(btnLogin);
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = "Select * from Users where username=? and password=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, textFieldUN.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()){
count = count +1;
}
if (count == 1){
frmTest.dispose();
Display GUI = new Display();
GUI.setVisible(true);
}
else if (count > 1){
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}
else{
JOptionPane.showMessageDialog(null, "Username or Password is not correct - Please try again..");
}
rs.close();
pst.close();
}
catch (Exception anException){
JOptionPane.showMessageDialog(null, anException);
}
}
});
btnLogin.setBounds(126, 111, 89, 23);
frmTest.getContentPane().add(btnLogin);
passwordField = new JPasswordField();
passwordField.setBounds(126, 64, 151, 17);
frmTest.getContentPane().add(passwordField);
}
}
Display:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class Display extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
btnLoadData.setBounds(596, 11, 89, 23);
contentPane.add(btnLoadData);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(684, 45, -675, 349);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
Any help would be greatly appreciated! Cheers..
However, when I run it in Eclipse I receive no errors at all. It runs fine, just does not display the database in the JTable.
Could you please replace your Display.java with the following:
Display.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
public class Display extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception anException) {
anException.printStackTrace();
}
}
});
// btnLoadData.setBounds(596, 11, 89, 23);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(btnLoadData, BorderLayout.EAST);
contentPane.add(buttonPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
// scrollPane.setBounds(684, 45, -675, 349);
table = new JTable();
scrollPane.setViewportView(table);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
}
and see the results?
Few changes have been made to your code. They are:
1) You first added scrollPane to the contentPane then you added table to scrollPane. I changed the order.
2) You used absolute layout. I changed that with BorderLayout.
The result displayed on my system is:
Hope this helps!

Java Combo Box Not Filling from SQL

In my Program I have a ComboBox in which the user can select the User he wishes to edit and currently the Class I use to fill the ComboBox is not doing it. I've look at some similar problems to this on the website but failed to see what I'm doing wrong. If someone can provide a fix to the problem it would be appreciated. I'm still quite new to most of this.
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class AdminPanelDelUser {
private String Host = "Hidden";
private String Name = "Hidden";
private String Pass = "Hidden";
private JComboBox<String> userPicker;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AdminPanelDelUser window = new AdminPanelDelUser();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AdminPanelDelUser() {
initialize();
getUserPicker();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 300, 352);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JComboBox<String> userPicker = new JComboBox<String>();
userPicker.setBounds(59, 6, 235, 27);
frame.getContentPane().add(userPicker);
}
public JComboBox<String> getUserPicker() {
try {
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT * From `table_1`");
ResultSet rs = pst.executeQuery();
while(rs.next()) {
String name =rs.getString("user_name");
userPicker.addItem(name);
}
}
catch (Exception e) {
//Place Pop Warning Later
}
return userPicker;
}
}
Also any suggestions on how I can further improve the code would be happily taken. Thanks for anyone who helps me solve this problem.
Your problem is that you are creating the userPicker JComboBox and assigning it to a variable with method level scope instead of using the variable with class level scope. The JComboBox you add to the content pane is different to the one you attempt to add items to (which incidentally is null when getUserPicker() is called).
JComboBox<String> userPicker = new JComboBox<String>();
should be
userPicker = new JComboBox<String>();
You might want to read http://www.java-made-easy.com/variable-scope.html to get a better understanding of what is going on.
Change done in initialize function. The values are not setting because you are creating a new object userPicker. The following code is working
package com.mylender.test;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class AdminPanelDelUser {
private JComboBox<String> userPicker;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AdminPanelDelUser window = new AdminPanelDelUser();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AdminPanelDelUser() {
initialize();
getUserPicker();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 300, 352);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//JComboBox<String> userPicker = new JComboBox<String>();
userPicker = new JComboBox<String>();
userPicker.setBounds(59, 6, 235, 27);
frame.getContentPane().add(userPicker);
}
public void getUserPicker() {
try {
String a[]= {"HELLO","WORLD"};
for(String s:a)
userPicker.addItem(s);
}
catch (Exception e) {
//Place Pop Warning Later
}
}
}

How to insert values from textfields into database in java

I want to insert values from jtextfields into my database. but following error is occured.. Access denied for user ''#'localhost' to database 'employee' any solution?
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
public class DataEntry implements ActionListener{
Connection conn = null;
Statement stmt = null;
// Database credentials
//Create and set up the window.
JFrame mainframe=new JFrame("Database Operation");
JPanel mainpanel=new JPanel();
JButton insertbtn=new JButton("Insert");
JButton viewbtn=new JButton("View");
JLabel label1=new JLabel("ID: ");
JLabel label2=new JLabel("Age: ");
JLabel label3=new JLabel("");
JFrame insertframe=new JFrame("Insert into Database");
JPanel insertpanel=new JPanel();
JLabel idlabel=new JLabel(" id");
JTextField idtext=new JTextField(20);
JLabel agelabel=new JLabel(" age");
JTextField agetext=new JTextField(20);
JButton insertsubmit=new JButton("Submit");
JFrame viewframe=new JFrame("View Database Data");
JPanel viewpanel=new JPanel();
Vector datacol=new Vector();
Vector datarow=new Vector();
JTable datatable;
JScrollPane viewdata;
public void init()
{
mainwindow();
}
public void mainwindow()
{
mainpanel.setBackground(Color.GRAY);
mainpanel.setLayout(null);
insertbtn.setBounds(300, 300, 100, 30);
viewbtn.setBounds(800, 300, 100, 30);
mainpanel.add(insertbtn);
mainframe.add(mainpanel);
mainframe.setSize(1350, 700);
mainframe.setVisible(true);
insertbtn.addActionListener(this); }
public void insertwindow()
{
insertpanel.setBackground(Color.GRAY);
idlabel.setForeground(Color.WHITE);
agelabel.setForeground(Color.WHITE);
insertpanel.setLayout(null);
idlabel.setBounds(400, 150, 100, 20);
idtext.setBounds(550, 150, 150, 30);
agelabel.setBounds(400, 200, 100, 20);
agetext.setBounds(550, 200, 150, 30);
insertsubmit.setBounds(490, 300, 100, 30);
insertpanel.add(idlabel);
insertpanel.add(idtext);
insertpanel.add(agelabel);
insertpanel.add(agetext);
insertpanel.add(insertsubmit);
insertframe.add(insertpanel);
insertframe.setSize(1350, 700);
insertframe.setVisible(true);
insertsubmit.addActionListener(this);
insertframe.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
mainframe.setVisible(true);
}
}
);
}
public void viewwindow()
{
datacol.removeAllElements();
datarow.removeAllElements();
OpenDatabase();
try
{
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select id,age from employee");
ResultSetMetaData rms=rs.getMetaData();
int cols=rms.getColumnCount();
for(int i=1;i<=cols;i++)
{
datacol.addElement(rms.getColumnName(i));
}
while(rs.next())
{
Vector row=new Vector(cols);
for(int i=1;i<=cols;i++)
{
row.addElement(rs.getObject(i));
}
datarow.addElement(row);
}
datatable=new JTable(datarow,datacol);
viewdata=new JScrollPane(datatable);
}
catch(Exception e)
{
JOptionPane.showConfirmDialog(null, "Problem in Database connectivity or Data", "Result", JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE);
}
viewpanel.setBackground(Color.GRAY);
viewpanel.setLayout(null);
viewdata.setBounds(20, 50, 1250, 600);
viewpanel.add(viewdata);
viewframe.add(viewpanel);
viewframe.setSize(1350, 700);
viewframe.setVisible(true);
viewframe.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
mainframe.setVisible(true);
}
});}
public void insertdata(String id, String age)
{
try
{
Statement st=conn.createStatement();
st.executeUpdate("insert into employee values("+id+",'"+age+")");
JOptionPane.showConfirmDialog(null, "Your Data Has been Inserted", "Result", JOptionPane.DEFAULT_OPTION,JOptionPane.PLAIN_MESSAGE);
}
catch(Exception e)
{
JOptionPane.showConfirmDialog(null, "Problem in Database connectivity or Data", "Result", JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE);
}
}
public void OpenDatabase()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost/employee");
}
catch(Exception e)
{
System.out.println(e);
}
}
public void CloseDatabase()
{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==insertbtn)
{
mainframe.setVisible(false);
insertwindow();
}
if(arg0.getSource()==viewbtn)
{
mainframe.setVisible(false);
viewwindow();
}if(arg0.getSource()==insertsubmit)
{
String id=idtext.getText();
String age=agetext.getText();
try
{
OpenDatabase();
insertdata(id,age);
CloseDatabase();
}
catch(Exception e)
{
System.out.println(e);
}
idtext.setText("");
agetext.setText("");}}
public static void main(String args[])
{
DataEntry dm=new DataEntry();
dm.init();
}
}
You have problem with
conn=DriverManager.getConnection("jdbc:mysql://localhost/employee");
DriverManager.getConnection() ' parameters setting should be like
DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
If your mysql have default settings and you use root user it should be as
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root", "your password");
Give user id and password in getConnection method
conn=DriverManager.getConnection("jdbc:mysql://localhost/employee","root","password");
"root" as user id of my sql(As in yor system)
and "password" as password of my sql (As in yor system)
Use user name & password of your mysql database in getConnection method
conn=DriverManager.getConnection("jdbc:mysql://localhost/employee");
as
conn=DriverManager.getConnection("jdbc:mysql://localhost/employee","root","password");

New Button Window and UI Alignment

I created a main window where the user will click if he's a system admin, an employee or a member a finance, one of my problem is that they are not centered in the screen, how would I do that? Second, I want it to work like, when I click the Finance Button, the Mainwindow Will close and it will bring me to my log in screen, how would I do that?? Here's my MainWindow Code
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JEditorPane;
import javax.swing.SpringLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JFormattedTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainWindow extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow frame = new MainWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 333, 191);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JButton btnNewButton = new JButton("Employee");
contentPane.add(btnNewButton, BorderLayout.WEST);
JButton btnNewButton_1 = new JButton("Finance");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login login = new Login();
}
});
contentPane.add(btnNewButton_1, BorderLayout.CENTER);
JButton btnNewButton_2 = new JButton("System Admin");
contentPane.add(btnNewButton_2, BorderLayout.EAST);
JLabel lblNewLabel = new JLabel("Welcome");
contentPane.add(lblNewLabel, BorderLayout.NORTH);
}
}
here is my code for a login form
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Login extends JFrame {
private JLabel label1, label2;
private JButton submit;
private JTextField textfield1;
private JPasswordField passfield;
private JPanel panel;
public Login() {
setSize(300, 100);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
label1 = new JLabel("User ID:");
textfield1 = new JTextField(15);
label2 = new JLabel("Password:");
passfield = new JPasswordField(15);
submit = new JButton("Submit");
panel = new JPanel(new GridLayout(3, 1));
panel.add(label1);
panel.add(textfield1);
panel.add(label2);
panel.add(passfield);
panel.add(submit);
add(panel, BorderLayout.CENTER);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}// end login constructor
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String user = textfield1.getText();
char[] passChars = passfield.getPassword();
Connection conn = Jdbc.dbConn();
PreparedStatement ps = null;
ResultSet rs = null;
String pass = new String(passChars);
if (passChars != null) {
String sql = "SELECT employee_ID, employee_password FROM user WHERE employee_ID = ? AND employee_password = ?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null,"Welcome! "+user);
} else {
JOptionPane.showMessageDialog(null, "Wrong Input");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}// end actionPerformed
}// End ButtonHandler
}// End of class
}
Some suggestions:
Do not use setBounds() for MainWindow (JFrame). Use some Layout and at end use pack(). If you want to set size manually then you can also use setSize().
To close current window and open Login frame add setVisible(false) or dispose() and create Login object and make it visible.
For making frame to be at center try setLocationRelativeTo(null);.
Do not use variable names like label1, textFiled2, btnNewButton, etc... Use proper names for proper variable that reflects it usage.
Example for point 2:
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
Login login = new Login();
}
});
You need to carefully choose a layout manager to suit your needs. You are currently using BorderLayout which doesn't seem to do what you want.
Try adding your three buttons to a JPanel and then setting that panel as your frame's content pane. JPanel uses FlowLayout by default which should do the trick.

Categories