import java.awt.*;
public class MainWindow {
private JFrame frmMainwindow;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JTextField textField_7;
private JTextField textField_8;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frmMainwindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
*/
Connection conn = null;
Connection conn1 = null;
public MainWindow() {
initialize();
MainPage mp = new MainPage();
mp.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
public void Reset(){
textField.setText(null);
textField_1.setText(null);
textField_2.setText(null);
textField_3.setText(null);
textField_4.setText(null);
textField_5.setText(null);
textField_6.setText(null);
textField_7.setText(null);
textField_8.setText(null);
}
public void DBCreation(){
conn = CreatingDb.CreateDb();
String DBName = textField.getText();
try{
String query = "CREATE DATABASE " + DBName ;
PreparedStatement pst = conn.prepareStatement(query);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "DB Created Successful.....");
pst.close();
}catch(Exception R){
JOptionPane.showMessageDialog(null, R);
}
}
public void Insert(){
String DBName = textField.getText();
conn1 = SqlConnection.InsertDB(DBName);
try{
String Table1 = "CREATE TABLE PERSONALINFO (PersonName VARCHAR(25),DoorNO VARCHAR(10),Street VARCHAR(25),Village VARCHAR(25),PhoneNo LONGINT(10),UserName VARCHAR(15),Password VARCHAR(10),Hint VARCHAR(50))";
String Insert1 = "INSERT INTO PERSONALINFO (PersonName,DoorNO,Street,Village,PhoneNo,UserName,Password,Hint) VALUES (?,?,?,?,?,?,?,?)";
PreparedStatement pstt = conn.prepareStatement(Table1);
PreparedStatement psti = conn.prepareStatement(Insert1);
psti.setString(1, textField_1.getText());
psti.setString(2, textField_2.getText());
psti.setString(3, textField_3.getText());
psti.setString(4, textField_4.getText());
psti.setString(5, textField_5.getText());
psti.setString(6, textField_6.getText());
psti.setString(7, textField_7.getText());
psti.setString(8, textField_8.getText());
pstt.execute();
psti.execute();
JOptionPane.showMessageDialog(null, "Table Created and Data Inserted Successfully....");
psti.close();
pstt.close();
}catch(Exception R){
JOptionPane.showMessageDialog(null, R);
}
}
private void initialize() {
frmMainwindow = new JFrame();
frmMainwindow.getContentPane().setBackground(Color.WHITE);
frmMainwindow.getContentPane().setFont(new Font("Times New Roman", Font.BOLD, 14));
frmMainwindow.setTitle("Create DataBase");
frmMainwindow.setBounds(100, 100, 668, 416);
frmMainwindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height;
int width = screenSize.width;
frmMainwindow.setSize(width/2, height/2);
// center the jframe on screen
frmMainwindow.setLocationRelativeTo(null);
frmMainwindow.getContentPane().setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.WHITE);
panel_1.setBounds(120, 70, 426, 205);
frmMainwindow.getContentPane().add(panel_1);
panel_1.setLayout(null);
panel_1.setVisible(false);
JLabel lblDatabaseName = new JLabel("DataBase Name");
lblDatabaseName.setBounds(0, 3, 107, 14);
panel_1.add(lblDatabaseName);
lblDatabaseName.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblPersonName = new JLabel("Person Name");
lblPersonName.setBounds(0, 32, 89, 14);
panel_1.add(lblPersonName);
lblPersonName.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblDoorNo = new JLabel("Door No");
lblDoorNo.setBounds(0, 57, 79, 14);
panel_1.add(lblDoorNo);
lblDoorNo.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblStreet = new JLabel("Street");
lblStreet.setBounds(0, 85, 46, 14);
panel_1.add(lblStreet);
lblStreet.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblVillage = new JLabel("Village");
lblVillage.setBounds(0, 110, 46, 14);
panel_1.add(lblVillage);
lblVillage.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblPhoneNo = new JLabel("Phone No");
lblPhoneNo.setBounds(0, 135, 58, 14);
panel_1.add(lblPhoneNo);
lblPhoneNo.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblUserbame = new JLabel("UserName");
lblUserbame.setBounds(232, 3, 79, 14);
panel_1.add(lblUserbame);
lblUserbame.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(232, 32, 68, 14);
panel_1.add(lblPassword);
lblPassword.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblHint = new JLabel("Hint");
lblHint.setBounds(232, 57, 46, 14);
panel_1.add(lblHint);
lblHint.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField = new JTextField();
textField.setBounds(117, 0, 105, 20);
panel_1.add(textField);
textField.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(117, 29, 105, 20);
panel_1.add(textField_1);
textField_1.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(117, 54, 105, 20);
panel_1.add(textField_2);
textField_2.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(117, 82, 105, 20);
panel_1.add(textField_3);
textField_3.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(117, 107, 105, 20);
panel_1.add(textField_4);
textField_4.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(117, 132, 105, 20);
panel_1.add(textField_5);
textField_5.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_5.setColumns(10);
textField_6 = new JTextField();
textField_6.setBounds(321, 0, 105, 20);
panel_1.add(textField_6);
textField_6.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_6.setColumns(10);
textField_7 = new JTextField();
textField_7.setBounds(321, 29, 105, 20);
panel_1.add(textField_7);
textField_7.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_7.setColumns(10);
textField_8 = new JTextField();
textField_8.setBounds(321, 54, 105, 20);
panel_1.add(textField_8);
textField_8.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_8.setColumns(10);
JButton btnReset = new JButton("Reset");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Reset();
}
});
btnReset.setBounds(232, 171, 89, 23);
panel_1.add(btnReset);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DBCreation();
Insert();
Reset();
}
});
btnSave.setBounds(327, 171, 89, 23);
panel_1.add(btnSave);
panel_1.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{lblDatabaseName, textField_1, lblPersonName, lblDoorNo, lblStreet, lblVillage, lblPhoneNo, lblUserbame, lblPassword, lblHint, textField_2, textField_3, textField_4, textField_5, textField_6, textField_7, textField_8, btnSave, btnReset, textField}));
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(217, 122, 233, 101);
frmMainwindow.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblCreateDatabase = new JLabel("Create DataBase");
lblCreateDatabase.setBounds(0, 4, 120, 14);
panel.add(lblCreateDatabase);
lblCreateDatabase.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblOpenDatabase = new JLabel("Open DataBase");
lblOpenDatabase.setBounds(0, 42, 120, 14);
panel.add(lblOpenDatabase);
lblOpenDatabase.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblNewLabel = new JLabel("Delete DataBase");
lblNewLabel.setBounds(0, 82, 120, 14);
panel.add(lblNewLabel);
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 14));
JButton btnNew = new JButton("New");
btnNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(false);
panel_1.setVisible(true);
}
});
btnNew.setBounds(144, 0, 89, 23);
panel.add(btnNew);
btnNew.setFont(new Font("Times New Roman", Font.BOLD, 14));
JButton btnSelect = new JButton("Select");
btnSelect.setBounds(144, 38, 89, 23);
panel.add(btnSelect);
btnSelect.setFont(new Font("Times New Roman", Font.BOLD, 14));
JButton btnRemove = new JButton("Remove");
btnRemove.setBounds(144, 78, 89, 23);
panel.add(btnRemove);
btnRemove.setFont(new Font("Times New Roman", Font.BOLD, 14));
}
}
My Second java file
public class SqlConnection {
Connection conn1 = null;
public static Connection InsertDB(String DBName){
String value = DBName;
try{
Class.forName("com.mysql.jdbc.Driver");
String DB = "jdbc:mysql://localhost:3306/";
Connection conn = DriverManager.getConnection(DB+value,"root","");
JOptionPane.showMessageDialog(null,value);
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
return null;
}
}
}
MY Third java File
public class CreatingDb {
Connection conn = null;
public static Connection CreateDb(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/","root","");
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
return null;
}
}
}
MY Forth java File..
public class MainPage extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainPage frame = new MainPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainPage() {
setExtendedState(Frame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmNew = new JMenuItem("New");
mnFile.add(mntmNew);
JMenuItem mntmOpen = new JMenuItem("Open");
mnFile.add(mntmOpen);
JMenuItem mntmSave = new JMenuItem("Save");
mnFile.add(mntmSave);
JMenuItem mntmSaveAs = new JMenuItem("Save As...");
mnFile.add(mntmSaveAs);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
I Have imported required packages...
In the above code I am creating database using textfield at beginning of application. DataBase is created successfully but i am unable to access the created dataBase . It show java.sql.Exception: Unknown database Selection.
please any one help me ....
String DB = "jdbc:mysql://localhost:3306/";
Connection conn = DriverManager.getConnection(DB+value,"root","");
i think your problem appending. you do not append DB + value. give password.
The MySQL manual says this:
If the database is not specified, the connection is made with no default database. In this case, either call the setCatalog() method on the Connection instance, or fully specify table names using the database name (that is, SELECT dbname.tablename.colname FROM dbname.tablename...) in your SQL. Opening a connection without specifying the database to use is generally only useful when building tools that work with multiple databases, such as GUI database managers.
Note
Always use the Connection.setCatalog() method to specify the desired database in JDBC applications, rather than the USE database statement.
It doesn't specify what happens if you don't call setCatalog() but given your problem I guess "nothing good." You should add a schema to your connect string or call setCatalog().
Related
how can I create a bar chart by retrieving data from database using eclipse in java ? I have to retrieve data from (mySql) DB Browser and should connect to the graph . So here is the code below .Graph should shows lecture room and the Laboratory incrementation , Statistics is the package name and the class name is StatisticsGraph
package Locations;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
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.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import Connection.DBConnection;
import Lecturers_Management.AddingLecturers;
import java.awt.EventQueue;
public class AddLocations {
private JFrame frame;
PreparedStatement pstd=null;
PreparedStatement pst = null;
PreparedStatement ptsID=null;
ResultSet rs = null;
Connection conn;
private JTextField BuildingName;
private JTextField RoomName;
private JTextField Capacity;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddLocations window = new AddLocations();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddLocations() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 1254, 739);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setLayout(null);
panel_1.setBackground(Color.LIGHT_GRAY);
panel_1.setBounds(10, 88, 233, 615);
frame.getContentPane().add(panel_1);
JButton btnNewButton = new JButton("Home");
btnNewButton.setForeground(Color.BLACK);
btnNewButton.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton.setBackground(Color.CYAN);
btnNewButton.setBounds(10, 10, 213, 38);
panel_1.add(btnNewButton);
JButton btnNewButton_1= new JButton("Lecturers");
btnNewButton_1.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_1.setBackground(Color.CYAN);
btnNewButton_1.setBounds(10, 65, 213, 38);
panel_1.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Students");
btnNewButton_2.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_2.setBackground(Color.CYAN);
btnNewButton_2.setBounds(10, 124, 213, 38);
panel_1.add(btnNewButton_2);
JButton btnNewButton_3= new JButton("Subjects");
btnNewButton_3.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_3.setBackground(Color.CYAN);
btnNewButton_3.setBounds(10, 181, 213, 38);
panel_1.add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("Working days/Hours");
btnNewButton_4.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_4.setBackground(Color.CYAN);
btnNewButton_4.setBounds(10, 235, 213, 38);
panel_1.add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Sessions");
btnNewButton_5.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_5.setBackground(Color.CYAN);
btnNewButton_5.setBounds(10, 289, 213, 38);
panel_1.add(btnNewButton_5);
JButton btnNewButton_6 = new JButton("Locations");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddLocations addlocations=new AddLocations();
addlocations.main(null);
frame.setVisible(false);
}
});
btnNewButton_6.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_6.setBackground(Color.CYAN);
btnNewButton_6.setBounds(10, 344, 213, 38);
panel_1.add(btnNewButton_6);
JButton btnNewButton_7 = new JButton("Tags");
btnNewButton_7.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_7.setBackground(Color.CYAN);
btnNewButton_7.setBounds(10, 400, 213, 38);
panel_1.add(btnNewButton_7);
JButton btnNewButton_8 = new JButton("Session Rooms");
btnNewButton_8.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_8.setBackground(Color.CYAN);
btnNewButton_8.setBounds(10, 456, 213, 38);
panel_1.add(btnNewButton_8);
JButton btnNewButton_9 = new JButton("Generate Timetables");
btnNewButton_9.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_9.setBackground(Color.CYAN);
btnNewButton_9.setBounds(10, 512, 213, 38);
panel_1.add(btnNewButton_9);
JButton btnNewButton_10 = new JButton("Statistics");
btnNewButton_10.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_10.setBackground(Color.CYAN);
btnNewButton_10.setBounds(10, 567, 213, 38);
panel_1.add(btnNewButton_10);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.CYAN);
panel.setBounds(10, 10, 1216, 68);
frame.getContentPane().add(panel);
JLabel lblNewLabel = new JLabel("TIMETABLE MANAGEMENT");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setForeground(Color.BLUE);
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 22));
lblNewLabel.setBackground(Color.BLUE);
lblNewLabel.setBounds(430, 0, 329, 68);
panel.add(lblNewLabel);
JPanel panel_2 = new JPanel();
panel_2.setLayout(null);
panel_2.setBackground(Color.BLUE);
panel_2.setBounds(253, 88, 973, 76);
frame.getContentPane().add(panel_2);
JButton btnNewButton_11 = new JButton("Add Location");
btnNewButton_11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddLocations addlocations=new AddLocations();
addlocations.main(null);
frame.setVisible(false);
}
});
btnNewButton_11.setForeground(Color.BLACK);
btnNewButton_11.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_11.setBackground(Color.LIGHT_GRAY);
btnNewButton_11.setBounds(10, 10, 266, 56);
panel_2.add(btnNewButton_11);
JButton btnNewButton_12 = new JButton("Manage Location");
btnNewButton_12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ManageLocations managelocations=new ManageLocations();
managelocations.main(null);
frame.setVisible(false);
}
});
btnNewButton_12.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_12.setBackground(Color.LIGHT_GRAY);
btnNewButton_12.setBounds(697, 9, 266, 58);
panel_2.add(btnNewButton_12);
JPanel panel_3 = new JPanel();
panel_3.setBounds(253, 174, 973, 529);
frame.getContentPane().add(panel_3);
panel_3.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Building Name");
lblNewLabel_1.setFont(new Font("Times New Roman", Font.BOLD, 19));
lblNewLabel_1.setBackground(new Color(148, 0, 211));
lblNewLabel_1.setBounds(10, 10, 148, 41);
panel_3.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("Room Name");
lblNewLabel_2.setFont(new Font("Times New Roman", Font.BOLD, 19));
lblNewLabel_2.setBackground(new Color(148, 0, 211));
lblNewLabel_2.setBounds(10, 90, 148, 41);
panel_3.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("Room Type[![enter image description here][1]][1]");
lblNewLabel_3.setFont(new Font("Times New Roman", Font.BOLD, 19));
lblNewLabel_3.setBounds(10, 168, 148, 41);
panel_3.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("Capacity");
lblNewLabel_4.setFont(new Font("Times New Roman", Font.BOLD, 19));
lblNewLabel_4.setBounds(10, 248, 148, 41);
panel_3.add(lblNewLabel_4);
JTextField BuildingName = new JTextField();
BuildingName.setBackground(Color.LIGHT_GRAY);
BuildingName.setFont(new Font("Times New Roman", Font.BOLD, 20));
BuildingName.setBounds(145, 12, 730, 41);
panel_3.add(BuildingName);
BuildingName.setColumns(10);
JTextField RoomName = new JTextField();
RoomName.setBackground(Color.LIGHT_GRAY);
RoomName.setFont(new Font("Times New Roman", Font.BOLD, 20));
RoomName.setBounds(145, 90, 730, 41);
panel_3.add(RoomName);
RoomName.setColumns(10);
JComboBox RoomType = new JComboBox();
RoomType.setModel(new DefaultComboBoxModel(new String[] {"Lecture Hall", "Laboratory"}));
RoomType.setFont(new Font("Times New Roman", Font.BOLD, 20));
RoomType.setBackground(Color.LIGHT_GRAY);
RoomType.setBounds(145, 168, 730, 41);
panel_3.add(RoomType);
JTextField Capacity = new JTextField();
Capacity.setBackground(Color.LIGHT_GRAY);
Capacity.setFont(new Font("Times New Roman", Font.BOLD, 20));
Capacity.setBounds(145, 248, 730, 41);
panel_3.add(Capacity);
Capacity.setColumns(10);
JButton btnNewButton_14 = new JButton("Clear");
btnNewButton_14.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BuildingName.setText(null);
RoomName.setText(null);
RoomType.setSelectedItem(null);
Capacity.setText(null);
}
});
btnNewButton_14.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_14.setBackground(Color.CYAN);
btnNewButton_14.setBounds(435, 452, 157, 41);
panel_3.add(btnNewButton_14);
JButton btnNewButton_15 = new JButton("Save");
btnNewButton_15.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if(BuildingName.getText().equals("") ||RoomName.getText().equals("")||RoomType.getSelectedItem().equals("")||Capacity.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Please fill the form and then save it");
}else if(!(Capacity.getText().trim().matches("^[0-9]{3}"))){
JOptionPane.showMessageDialog(null, "Invalid capacity amount");
}else{
Connection connec = DBConnection.connect();
String BName=BuildingName.getText();
String RName=RoomName.getText();
String RType=RoomType.getSelectedItem().toString();
String capacity=Capacity.getText();
String msg = "" + BName;
msg += " \n";
Connection con = DBConnection.connect();
String query = "INSERT INTO Locations values(null,'" + BName + "','" + RName + "','" + RType + "','" +
capacity + "')";
java.sql.Statement sta = con.createStatement();
int xx = sta.executeUpdate(query);
JOptionPane.showMessageDialog(null,
"Your , " + msg + "has succesfully inserted");
con.close();
BuildingName.setText(null);
RoomName.setText(null);
RoomType.setSelectedItem(null);
Capacity.setText(null);
}
}
catch(Exception w){
JOptionPane.showMessageDialog(null, w );
}
finally{
try{
Connection pst = null;
pst.close();
Connection rs = null;
rs.close();
}catch(Exception r){
}
}
}
});
btnNewButton_15.setFont(new Font("Times New Roman", Font.BOLD, 20));
btnNewButton_15.setBackground(Color.CYAN);
btnNewButton_15.setBounds(719, 452, 157, 41);
panel_3.add(btnNewButton_15);
}
}
When I run this code ( having simple buttons and a LOGIN button with an action listener), it terminates without running and without showing screen.
I have tried System.exit(0); in main function to overcome this terminating issue but all in vain
public class HOme extends JFrame{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) screenSize.getWidth();
int height = (int) screenSize.getHeight();
Color cardinal = new Color(194, 35, 38);
int w=155;
int h=50;
public HOme(String title) {
super(title);
getContentPane().setSize(width,height);
getContentPane().setBackground(Color.WHITE);
getContentPane().setLayout(null);
final JPanel panel2 = new JPanel();
panel2.setBounds(364, 33, 664, 344);
getContentPane().add(panel2);
JPanel panel3 = new JPanel();
panel3.setBackground(Color.WHITE);
panel3.setBounds(81, 382, 947, 243);
getContentPane().add(panel3);
panel3.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnHome.setForeground(Color.WHITE);
btnHome.setBackground(cardinal);
btnHome.setBounds(517, 33, w, h);
btnHome.setContentAreaFilled(false);
btnHome.setOpaque(true);
panel3.add(btnHome);
JButton btnClients = new JButton("Clients");
btnClients.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnClients.setForeground(Color.WHITE);
btnClients.setBounds(690, 33, w, h);
btnClients.setBackground(cardinal);
btnClients.setContentAreaFilled(false);
btnClients.setOpaque(true);
panel3.add(btnClients);
JButton btnClose = new JButton("Close");
btnClose.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnClose.setForeground(Color.WHITE);
btnClose.setBounds(690, 198, w, h);
btnClose.setBackground(cardinal);
btnClose.setContentAreaFilled(false);
btnClose.setOpaque(true);
panel3.add(btnClose);
JButton btnLogin = new JButton("Admin Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login l=new Login();
panel2.add(l);
}
});
btnLogin.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnLogin.setForeground(Color.WHITE);
btnLogin.setBounds(517, 116, w, h);
btnLogin.setBackground(cardinal);
btnLogin.setContentAreaFilled(false);
btnLogin.setOpaque(true);
panel3.add(btnLogin);
JPanel panel1 = new JPanel();
panel1.setBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(204, 51, 0), null));
panel1.setBackground(Color.WHITE);
panel1.setBounds(81, 33, 263, 344);
getContentPane().add(panel1);
panel1.setLayout(null);
JButton btnStartMonitoring = new JButton("");
btnStartMonitoring.setIcon(new ImageIcon(path1));
btnStartMonitoring.setBackground(cardinal);
btnStartMonitoring.setForeground(Color.WHITE);
btnStartMonitoring.setFont(new Font("Tahoma", Font.PLAIN, 15));
btnStartMonitoring.setBounds(10, 274, 239, 59);
panel1.add(btnStartMonitoring);
JLabel lblLogo = new JLabel("New label");
lblLogo.setIcon(new ImageIcon(path2));
lblLogo.setBounds(0, 11, 263, 253);
panel1.add(lblLogo);
}
public static void main(String args[]) {
new HOme("HOme");
//System.exit(0);
}
}
Edited
I have a login class extended from JPanel. When I click on Login Button from Home. It is not showing Login panel
Login.class
public class Login extends JPanel {
private JTextField txtPassword;
private JTextField txtID;
Color cardinal = new Color(194, 35, 38);
int w=155;
int h=50;
public Login() {
setBackground(Color.WHITE);
setLayout(null);
JLabel lblLogin = new JLabel("Login ");
lblLogin.setBackground(Color.ORANGE);
lblLogin.setHorizontalAlignment(SwingConstants.RIGHT);
lblLogin.setFont(new Font("Trajan Pro", Font.BOLD, 36));
lblLogin.setBounds(125, 0, 424, 59);
lblLogin.setBackground(cardinal);
//lblLogin.setContentAreaFilled(false);
lblLogin.setOpaque(true);
lblLogin.setForeground(Color.white);
add(lblLogin);
JLabel lblId = new JLabel("ID");
lblId.setHorizontalAlignment(SwingConstants.RIGHT);
lblId.setFont(new Font("Tekton Pro", Font.PLAIN, 23));
lblId.setBounds(181, 127, 66, 28);
add(lblId);
JLabel lblPassword = new JLabel("Password");
lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
lblPassword.setFont(new Font("Tekton Pro", Font.PLAIN, 23));
lblPassword.setBounds(136, 188, 111, 28);
add(lblPassword);
txtPassword = new JTextField();
lblPassword.setLabelFor(txtPassword);
txtPassword.setBounds(266, 183, 256, 41);
lblPassword.setForeground(cardinal);
add(txtPassword);
txtPassword.setColumns(10);
txtID = new JTextField();
lblId.setLabelFor(txtID);
txtID.setBounds(266, 123, 256, 39);
lblId.setForeground(cardinal);
add(txtID);
txtID.setColumns(10);
JButton btnLogin = new JButton("Login");
btnLogin.setForeground(Color.WHITE);
btnLogin.setFont(new Font("Times New Roman", Font.PLAIN, 20));
btnLogin.setBounds(324, 294, w, h);
btnLogin.setBackground(cardinal);
btnLogin.setContentAreaFilled(false);
btnLogin.setOpaque(true);
add(btnLogin);
setVisible(true);
}
You are not making your JFrame visible.
You can do either -
In your constructor, make it visible by adding the following line at the end -
setVisible(true);
Or in your main() function you can do -
HOme h = new HOme("HOme");
h.setVisible(true);
Answer to second part:
Import MouseListener, import java.awt.event.MouseListener;
Construct a MouseListener somewhere, include action of the button
Where you define btnLogin, add a line btnLogin.addMouseListener(<name of MouseListener>);
An example: http://www.java2s.com/Code/Java/Swing-JFC/ButtonActionSample.htm
Add something like setVisible(true); at the end of the HOme method.
I am having a problem with opening a new window. If I comment out the if(e.getsource() == btnAddBook) the action performed opens the window. As soon as I add the if statement in and try to open the window, nothing happens.
/* this is the code that adds the button and the action listner
JButton btnAddBook = new JButton("Add Book");
btnAddBook.setFont(new Font("Tahoma", Font.BOLD, 8));
btnAddBook.setBounds(10, 327, 86, 23);
btnAddBook.addActionListener(this);
getContentPane().add(btnAddBook);
*/
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == btnAddBook){
ChildWindowAdd child = new ChildWindowAdd(this);
this.setVisible(true);
child.setVisible(true);
child.setSize(450,400);
child.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
}
class ChildWindowAdd extends JFrame implements ActionListener {
LibraryDatabase parent;
Container c;
JLabel lblTitle, lblaName, lblISBN, lblDate,lbl1,lbl5,lbl10;
JTextField txtTitle, txtaName, txtISBN, txtDate;
JButton btnSave;
JSlider sRating;
JCheckBox chkSci, chkFant, chkRomance, chkAction, chkThriller, chkHorror;
public ChildWindowAdd(LibraryDatabase parent){
this.parent = parent;
getContentPane().setLayout(null);
txtTitle = new JTextField();
txtTitle.setBounds(46, 29, 146, 20);
getContentPane().add(txtTitle);
txtTitle.setColumns(10);
JLabel lblTitle = new JLabel("Book Title");
lblTitle.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblTitle.setBounds(36, 11, 72, 14);
getContentPane().add(lblTitle);
JLabel lblaName = new JLabel("Author Name");
lblaName.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblaName.setBounds(36, 60, 89, 14);
getContentPane().add(lblaName);
txtaName = new JTextField();
txtaName.setBounds(46, 85, 146, 20);
getContentPane().add(txtaName);
txtaName.setColumns(10);
JLabel lblIsbnNumber = new JLabel("ISBN Number");
lblIsbnNumber.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblIsbnNumber.setBounds(36, 116, 86, 14);
getContentPane().add(lblIsbnNumber);
txtISBN = new JTextField();
txtISBN .setBounds(46, 143, 146, 20);
getContentPane().add(txtISBN );
txtISBN .setColumns(10);
JLabel lblDate = new JLabel("Date Added yyyy/mm/dd");
lblDate.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblDate.setBounds(36, 174, 177, 20);
getContentPane().add(lblDate);
txtDate = new JTextField();
txtDate.setBounds(46, 199, 146, 20);
getContentPane().add(txtDate);
txtDate.setColumns(10);
JPanel genreP = new JPanel();
genreP.setBounds(239, 29, 158, 194);
genreP.setBorder(new TitledBorder(null, "Genre's", TitledBorder.LEADING, TitledBorder.TOP, null, null));
getContentPane().add(genreP);
genreP.setLayout(null);
final JCheckBox chkSci = new JCheckBox("Sci - Fi");
chkSci.setBounds(23, 22, 97, 23);
genreP.add(chkSci);
final JCheckBox chkFant = new JCheckBox("Fantasy");
chkFant.setBounds(23, 48, 97, 23);
genreP.add(chkFant);
final JCheckBox chkRomance = new JCheckBox("Romance");
chkRomance.setBounds(23, 74, 97, 23);
genreP.add(chkRomance);
final JCheckBox chkAction = new JCheckBox("Action");
chkAction.setBounds(23, 100, 97, 23);
genreP.add(chkAction);
final JCheckBox chkThriller = new JCheckBox("Thriller");
chkThriller.setBounds(23, 126, 97, 23);
genreP.add(chkThriller);
final JCheckBox chkHorror = new JCheckBox("Horror");
chkHorror.setBounds(23, 152, 97, 23);
genreP.add(chkHorror);
final JSlider sRating = new JSlider();
sRating.setBounds(118, 280, 200, 26);
getContentPane().add(sRating);
JLabel lbl1 = new JLabel("1");
lbl1.setBounds(118, 257, 7, 14);
getContentPane().add(lbl1);
JLabel lbl10 = new JLabel("10");
lbl10.setBounds(301, 257, 17, 14);
getContentPane().add(lbl10);
JLabel lbl5 = new JLabel("5");
lbl5.setBounds(214, 257, 7, 14);
getContentPane().add(lbl5);
JButton btnSave = new JButton("Save Book");
btnSave.addActionListener(this);
btnSave.setBounds(164, 317, 110, 23);
getContentPane().add(btnSave);
JLabel lblRating = new JLabel("Rate the book");
lblRating.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblRating.setBounds(118, 226, 95, 20);
getContentPane().add(lblRating);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PrintWriter fileWriter = null;
try {
fileWriter = new PrintWriter(new BufferedWriter(new FileWriter("c:\\temp\\database.dat", true)));
} catch (IOException e) {
e.printStackTrace();
}
fileWriter.println( txtTitle.getText()+" , "+txtaName.getText()+" , "+txtISBN.getText()+" , "+txtDate.getText()+" , "+String.valueOf(chkSci.isSelected())+" , "+String.valueOf(chkFant.isSelected())+" , "+String.valueOf(chkRomance.isSelected())+" , "+String.valueOf(chkAction.isSelected())+" , "+String.valueOf(chkThriller.isSelected())+" , "+String.valueOf(chkHorror.isSelected())+" , "+sRating.getValue());
fileWriter.close();
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
parent.setVisible(true);
this.dispose();
}
public void actionPerformed1(ActionEvent e) {
// TODO Auto-generated method stub
}
}
Check on the basis of button text
((JButton)source).getText().equals("Add Book")
here is complete code
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton && ((JButton) source).getText().equals("Add Book")) {
...
}
}
This worked for me. I had to match the String as the e.getsource was not working.
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
String test = ((JButton)source).getText();
if(test == "Add Book"){
ChildWindowAdd child = new ChildWindowAdd(this);
this.setVisible(true);
child.setVisible(true);
child.setSize(450,400);
child.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
I am having a problem with my Java GUI application. It for some reason says that it cannot find or load the main class. I have checked all the brackets and don't see a problem. I had originally copied this over from another file as I wanted to start over with some things, maybe that is the problem. Here is the code:
public class GradeAverage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField textField;
int numAverage = 0;
double average;
Container c;
JLabel gradelbl;
class AnswerHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
numAverage++;
gradelbl.setText("" + numAverage);
}
}
public GradeAverage() {
super("Final Grades");
c = getContentPane();
JLabel lblNewLabel = new JLabel("Grade: ");
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 14));
lblNewLabel.setBounds(30, 50, 46, 14);
textField = new JTextField();
textField.setBounds(81, 47, 86, 20);
textField.setColumns(10);
JLabel gradeLbl = new JLabel("0");
gradeLbl.setFont(new Font("Times New Roman", Font.BOLD, 14));
gradeLbl.setBounds(91, 92, 15, 14);
JLabel gradeTextLbl = new JLabel("Grades Recorded");
gradeTextLbl.setFont(new Font("Times New Roman", Font.BOLD, 14));
gradeTextLbl.setBounds(106, 92, 123, 14);
JButton recordBtn = new JButton("Record");
AnswerHandler ah = new AnswerHandler();
recordBtn.addActionListener(ah);
recordBtn.setBounds(177, 47, 86, 20);
JButton displayAverageBtn = new JButton("New button");
displayAverageBtn.setBounds(30, 117, 233, 23);
JPanel finalGradePanel = new JPanel();
finalGradePanel.setBorder(new TitledBorder(null, "Enter Your Final Grades", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 128)));
finalGradePanel.setBounds(10, 21, 264, 131);
JPanel avgGradePanel = new JPanel();
avgGradePanel.setFont(new Font("Times New Roman", Font.BOLD, 16));
avgGradePanel.setBounds(10, 178, 264, 61);
avgGradePanel.setBorder(new TitledBorder(null, "Average Grade", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 128)));
c.add(avgGradePanel);c.add(finalGradePanel);c.add(displayAverageBtn);c.add(recordBtn);c.add(gradeTextLbl);c.add(gradeLbl);
}
public static void main(String[] args) {
GradeAverage app = new GradeAverage();
app.setSize(300, 300);
app.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
app.setVisible(true);
}
}
I have two problem now.
My First Problem is when i click the confirm button, it will insert the data two times into ms access database.
My Second Problem is why joptionpane also popup two times.
I have the main login page when open the program.
When i click the sign up button, it will remove all the component inside the center jpanel.
Then it will add again component to use in registration form like jtextfield,jlabel,icon for username,password,tel no and others.I already checked, that the statement to execute insert statement and joptionpanes only have one times only.
This is the full code of my program
package userForm;
import java.sql.*;
import java.util.logging.Handler;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class loginForm extends JFrame implements ActionListener{
private JPanel centerPanel,bottomPanel;
private JLabel titleLabel, descriptionLabel;
private JLabel usernameLabel, passwordLabel, signInLabel, iconUsername, iconPassword;
private JLabel signUpLabel, fullNameLabel, staffIDLabel, usernameRegLabel, passwordRegLabel, telNoLabel, emailLabel;
private JLabel iconFullName, iconStaffID, iconUsernameReg, iconPasswordReg, iconTelNo, iconEmail;
private JTextField usernameField, fullNameField, staffIDField, usernameRegField, telNoField, emailField;
private JPasswordField passwordField, passwordRegField;
private JButton loginButton, signUpButton,confirmButton,exitButton;
private String username;
private String password;
userDatabase db;
userDatabase db1;
handler handle;
public loginForm(String title) {
db=new userDatabase();
handle =new handler();
//create label to use in topPanel
titleLabel = new JLabel("ABC Burger Inventory System");
titleLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 23));
titleLabel.setForeground(Color.white);
Border empty = new EmptyBorder(30, 20, 0, 0);
titleLabel.setBorder(empty);
descriptionLabel = new JLabel("Please Login To Use This System");
Border empty1 = new EmptyBorder(-30, 20, 0, 0);
descriptionLabel.setBorder(empty1);
descriptionLabel.setFont(new Font("Calibri", Font.HANGING_BASELINE, 14));
descriptionLabel.setForeground(Color.white);
//create label to use in centerPanel
signInLabel = new JLabel("SIGN IN");
usernameLabel = new JLabel("Username:");
passwordLabel = new JLabel("Password");
//create textfield to use in center Panel
usernameField = new JTextField("Required");
passwordField = new JPasswordField("Required");
//create label to use in registration form
signUpLabel = new JLabel("SIGN UP");
fullNameLabel = new JLabel("Full Name:");
staffIDLabel = new JLabel("Staff ID:");
usernameRegLabel = new JLabel("Username:");
passwordRegLabel = new JLabel("Password");
telNoLabel = new JLabel("Tel No:");
emailLabel = new JLabel("Email:");
//create textfield to use in registration form
fullNameField = new JTextField(30);
staffIDField = new JTextField(30);
usernameRegField = new JTextField(30);
passwordRegField = new JPasswordField(30);
telNoField = new JTextField(30);
emailField = new JTextField(30);
//create button to use in bottom Panel
loginButton = new JButton("Login");
signUpButton = new JButton("Sign Up");
confirmButton = new JButton("Confirm");
confirmButton.addActionListener(this);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
//create panel to use in frame
topPanelWithBackground topPanel = new topPanelWithBackground();
topPanel.setLayout(new GridLayout(2,1));
centerPanel = new JPanel();
centerPanel.setLayout(null);
bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 40, 10));
//add component to top panel
topPanel.add(titleLabel);
topPanel.add(descriptionLabel);
//add component to center panel
signInLabel.setBounds(270, 30, 100, 20);
signInLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 20));
centerPanel.add(signInLabel);
usernameLabel.setBounds(200, 60, 100, 20);
usernameLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameLabel);
ImageIcon imageUser = new ImageIcon("user.png");
iconUsername = new JLabel(imageUser, JLabel.CENTER);
iconUsername.setBounds(160, 90, 32, 32);
centerPanel.add(iconUsername);
usernameField.setBounds(200, 90, 200, 32);
usernameField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameField);
passwordLabel.setBounds(200, 140, 100, 20);
passwordLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordLabel);
ImageIcon imagePassword = new ImageIcon("password.png");
iconUsername = new JLabel(imagePassword, JLabel.CENTER);
iconUsername.setBounds(160, 170, 32, 32);
centerPanel.add(iconUsername);
passwordField.setBounds(200, 170, 200, 32);
passwordField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordField);
loginButton.setFont(new Font("Calibri", Font.BOLD, 14));
loginButton.addActionListener(handle);
bottomPanel.add(loginButton);
signUpButton.setFont(new Font("Calibri", Font.BOLD, 14));
signUpButton.addActionListener(this);
bottomPanel.add(signUpButton);
//add confirm button
exitButton.setFont(new Font("Calibri", Font.BOLD, 14));
exitButton.addActionListener(this);
bottomPanel.add(exitButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topPanel, BorderLayout.NORTH );
getContentPane().add(centerPanel, BorderLayout.CENTER);
getContentPane().add(bottomPanel, BorderLayout.SOUTH);
//frame behaviour
super.setTitle(title);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit
setSize(600,500);
}
class handler implements ActionListener{
public void actionPerformed(ActionEvent as) {
if(as.getSource()==loginButton){
centerPanel.removeAll();
centerPanel.revalidate();
centerPanel.repaint();
//add component to center panel
signInLabel.setBounds(270, 30, 100, 20);
signInLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 20));
centerPanel.add(signInLabel);
usernameLabel.setBounds(200, 60, 100, 20);
usernameLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameLabel);
ImageIcon imageUser = new ImageIcon("user.png");
iconUsername = new JLabel(imageUser, JLabel.CENTER);
iconUsername.setBounds(160, 90, 32, 32);
centerPanel.add(iconUsername);
usernameField.setBounds(200, 90, 200, 32);
usernameField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameField);
passwordLabel.setBounds(200, 140, 100, 20);
passwordLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordLabel);
ImageIcon imagePassword = new ImageIcon("password.png");
iconUsername = new JLabel(imagePassword, JLabel.CENTER);
iconUsername.setBounds(160, 170, 32, 32);
centerPanel.add(iconUsername);
passwordField.setBounds(200, 170, 200, 32);
passwordField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordField);
char[] temp_pwd=passwordField.getPassword();
String pwd=null;
pwd=String.copyValueOf(temp_pwd);
System.out.println("Username,Pwd:"+usernameField.getText()+","+pwd);
//The entered username and password are sent via "checkLogin()" which return boolean
if(db.checkLogin(usernameField.getText(), pwd))
{
newFrame regFace =new newFrame();
regFace.setVisible(true);
dispose();
}
else if(usernameField.getText().equals("") || passwordField.getText().equals("")){
JOptionPane.showMessageDialog(null, "Please fill out the form","Error!!",
JOptionPane.ERROR_MESSAGE);
}
else
{
//a pop-up box
JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==signUpButton){
centerPanel.removeAll();
//sign up label
signUpLabel.setBounds(270, 30, 100, 20);
signUpLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 20));
centerPanel.add(signUpLabel);
//fullname label,icon and field
fullNameLabel.setBounds(80, 60, 100, 20);
fullNameLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(fullNameLabel);
ImageIcon imageFullname = new ImageIcon("fullname.png");
iconUsernameReg = new JLabel(imageFullname, JLabel.CENTER);
iconUsernameReg.setBounds(40, 90, 32, 32);
centerPanel.add(iconUsernameReg);
fullNameField.setBounds(80, 90, 200, 32);
fullNameField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(fullNameField);
//staffID label,icon and field
staffIDLabel.setBounds(80, 140, 100, 20);
staffIDLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(staffIDLabel);
ImageIcon imageStaffID = new ImageIcon("staffID.png");
iconStaffID = new JLabel(imageStaffID, JLabel.CENTER);
iconStaffID.setBounds(40, 170, 32, 32);
centerPanel.add(iconStaffID);
staffIDField.setBounds(80, 170, 200, 32);
staffIDField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(staffIDField);
//usernameReg label,icon and field
usernameRegLabel.setBounds(80, 220, 100, 20);
usernameRegLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameRegLabel);
ImageIcon imageUsernameReg = new ImageIcon("user.png");
iconUsernameReg = new JLabel(imageUsernameReg, JLabel.CENTER);
iconUsernameReg.setBounds(40, 250, 32, 32);
centerPanel.add(iconUsernameReg);
usernameRegField.setBounds(80, 250, 200, 32);
usernameRegField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(usernameRegField);
//passwordReg label,icon and field
passwordRegLabel.setBounds(350, 60, 100, 20);
passwordRegLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordRegLabel);
ImageIcon imagePasswordReg = new ImageIcon("password.png");
iconPasswordReg = new JLabel(imagePasswordReg, JLabel.CENTER);
iconPasswordReg.setBounds(310, 90, 32, 32);
centerPanel.add(iconPasswordReg);
passwordRegField.setBounds(350, 90, 200, 32);
passwordRegField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(passwordRegField);
//telNo label,icon and field
telNoLabel.setBounds(350, 140, 100, 20);
telNoLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(telNoLabel);
ImageIcon imagetelNo = new ImageIcon("phone.png");
iconTelNo = new JLabel(imagetelNo, JLabel.CENTER);
iconTelNo.setBounds(310, 170, 32, 32);
centerPanel.add(iconTelNo);
telNoField.setBounds(350, 170, 200, 32);
telNoField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(telNoField);
//Email label,icon and field
emailLabel.setBounds(350, 220, 100, 20);
emailLabel.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(emailLabel);
ImageIcon imageEmail = new ImageIcon("mail.png");
iconEmail = new JLabel(imageEmail , JLabel.CENTER);
iconEmail .setBounds(310, 250, 32, 32);
centerPanel.add(iconEmail );
emailField.setBounds(350, 250, 200, 32);
emailField.setFont(new Font("Calibri", Font.BOLD, 14));
centerPanel.add(emailField);
//add confirm button
confirmButton.setFont(new Font("Calibri", Font.BOLD, 14));
confirmButton.addActionListener(this);
bottomPanel.add(confirmButton);
centerPanel.revalidate();
centerPanel.repaint();
}
else if(ae.getSource()==confirmButton){
char[] temp_pwd1=passwordRegField.getPassword();
String pwd=null;
pwd=String.copyValueOf(temp_pwd1);
if(fullNameField.getText().equals("") || staffIDField.getText().equals("") || usernameRegField.getText().equals("") || passwordRegField.getPassword().length == 0 || telNoField.getText().equals("") || emailField.getText().equals("")){
JOptionPane.showMessageDialog(null, "Please Fill Out Any Field", "Error",
JOptionPane.ERROR_MESSAGE);
}
else {
db1 = new userDatabase();
try {
db1.insertData(fullNameField.getText(), staffIDField.getText(), usernameRegField.getText(), pwd, telNoField.getText(), emailField.getText());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else if(ae.getSource()==exitButton){
System.exit(0);
}
}
}
When you click the sign up button you are adding listener to the confirm button again. So when you click the confirm button it is executed twice.
Remove the following line in the actionPerformed method of LoginForm
confirmButton.addActionListener(this);