How to Show text retrieved from database on JButton, JTextArea in Java? - java

I am trying to build a quiz app and I managed to build the database. I created a GUI using the card layout to switch between panels and I tried to retrieve the questions and options from from the database to a JtextArea with no success. My question is how do I get the visual components (jtext area,jbutton to display the content from the database) I want them to automatically set the text according with the question number.
this is my code
package quizzGUI;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.List;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JRadioButton;
import javax.swing.JTextPane;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.management.Query;
import javax.swing.ButtonGroup;
public class quizzMain {
private JFrame frame;
private JPanel Menu;
private JPanel Playing;
private JPanel Score;
private final ButtonGroup buttonGroup = new ButtonGroup();
public JTextPane textPane;
public JButton btnA;
public JRadioButton rdbtnB;
public JRadioButton rdbtnC;
public JRadioButton rdbtnD;
public JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
quizzMain window = new quizzMain();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
Connection connection = null;
public quizzMain() {
initialize();
connection = sqlConnection.dbConnector();
}
private void initialize() {
Connection connection = sqlConnection.dbConnector();
Statement stmt=null;
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel Menu = new JPanel();
frame.getContentPane().add(Menu, "name_668313932787145");
Menu.setLayout(null);
Menu.setVisible(true);
final JPanel Playing = new JPanel();
Playing.setBackground(Color.CYAN);
frame.getContentPane().add(Playing, "name_668321772390383");
Playing.setLayout(null);
Playing.setVisible(false);
final JPanel Score = new JPanel();
frame.getContentPane().add(Score, "name_668324579994343");
Score.setLayout(null);
Score.setVisible(false);
JLabel lblNewLabel = new JLabel("C QUIZZ");
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD | Font.ITALIC, 14));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(123, 47, 169, 40);
Menu.add(lblNewLabel);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Integer i=0;
Playing.setVisible(true);
Menu.setVisible(false);
try{
String query = ("SELECT * FROM Question ");
PreparedStatement pst=connection.prepareStatement(query);
ResultSet rs=pst.executeQuery();
do {
btnA.setText(rs.getString("ANSWERA"));
}while(rs.next());
}catch(Exception e ){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
});
btnStart.setFont(new Font("Tahoma", Font.BOLD, 12));
btnStart.setBounds(167, 176, 89, 23);
Menu.add(btnStart);
JButton btnFinish = new JButton("Finish");
btnFinish.setBounds(335, 227, 89, 23);
Playing.add(btnFinish);
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Score.setVisible(true);
Playing.setVisible(false);
}
});
JButton btnNextQuestion = new JButton("Next");
btnNextQuestion.setBounds(10, 227, 89, 23);
Playing.add(btnNextQuestion);
JTextArea textArea = new JTextArea();
textArea.setBounds(20, 11, 387, 41);
Playing.add(textArea);
JButton btnA = new JButton("New button");
btnA.setBounds(20, 84, 381, 41);
Playing.add(btnA);
JTextArea txtrScore = new JTextArea();
txtrScore.setBounds(87, 74, 244, 43);
txtrScore.setText("Score:");
Score.add(txtrScore);
}
}

Since you didn't mention your code, its difficult to give you a short precise example. I would recommend you to go through this tutorial which retrieves information (name and number) and display it in JTextArea.
Extracting the key points from the tutorial below:
Database connection establishment and fetching information
String url = "jdbc:mysql://localhost:3306/";
String db = "databasename";
String driver = "com.mysql.jdbc.Driver";
String user = "xxxx";
String pass = "xxxx";
Connection con = null;
PreparedStatement pstatement = null;
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db , user, pass);
pstatement = con.prepareStatement("SELECT name, phonenumber FROM tablename");
con = DriverManager.getConnection(url + db, user, pass);
ResultSet rs = pstatement.executeQuery();
while(rs.next()){
String name = rs.getString(1);
int phonenumber = rs.getInt(2);
}
Set text in JTextArea
Then use setText method of JTextArea to set the text. For example, recordTextArea.setText(name + " " + phonenumber);.

Related

Java GUI Swing Passing Parameter From Another Class

Im bulding a GUI using eclipse plugin WindowsBuilder, im trying to pass a variable "comboBox kombo" from the initialize() method. I cant call the method to run my passed variable. The method supposed to get the data from my database to the comboBox.
Below i have attached my coding, any help will be appreciated ,Thank you!
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Label;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JTextField;
public class book extends JFrame {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
private JFrame mdetail;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
book window = new book();
window.mdetail.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public book() {
initialize();
comboBox(kombo);
}
private void comboBox(JComboBox kombo) {
try
{
con= DriverManager.getConnection("jdbc:mysql://localhost/oop_project", "root","");
String sql = "select movieName from movie ";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next())
{
String name = rs.getString("movieName");
kombo.addItem(name);
}
}catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
mdetail = new JFrame();
mdetail.setTitle("Book Ticket");
mdetail.setBounds(100, 100, 450, 336);
mdetail.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mdetail.getContentPane().setLayout(null);
Label label = new Label("Movie Details");
label.setForeground(Color.BLACK);
label.setFont(new Font("Dialog", Font.PLAIN, 21));
label.setBounds(135, 10, 184, 54);
mdetail.getContentPane().add(label);
JComboBox kombo = new JComboBox();
kombo.setBounds(155, 70, 226, 22);
mdetail.getContentPane().add(kombo);
Label label_1 = new Label("Select Movie");
label_1.setBounds(74, 70, 75, 22);
mdetail.getContentPane().add(label_1);
Label label_1_1 = new Label("Select Date");
label_1_1.setBounds(74, 103, 75, 22);
mdetail.getContentPane().add(label_1_1);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"11-12-2022", "12-12-2022", "13-12-2022"}));
comboBox_1.setBounds(155, 103, 226, 22);
mdetail.getContentPane().add(comboBox_1);
Label label_1_1_1 = new Label("Select Time");
label_1_1_1.setBounds(74, 136, 75, 22);
mdetail.getContentPane().add(label_1_1_1);
JComboBox comboBox_1_1 = new JComboBox();
comboBox_1_1.setModel(new DefaultComboBoxModel(new String[] {"7.00am", "10.00am", "1.00pm", "5.00pm", "8.00pm"}));
comboBox_1_1.setBounds(155, 136, 226, 22);
mdetail.getContentPane().add(comboBox_1_1);
Label label_1_1_2 = new Label("Select Seat");
label_1_1_2.setBounds(74, 169, 75, 22);
mdetail.getContentPane().add(label_1_1_2);
JComboBox comboBox_1_2 = new JComboBox();
comboBox_1_2.setModel(new DefaultComboBoxModel(new String[] {"A(01)", "B(02)", "B(03)"}));
comboBox_1_2.setBounds(155, 169, 226, 22);
mdetail.getContentPane().add(comboBox_1_2);
JButton btnNewButton = new JButton("SUBMIT");
btnNewButton.setBounds(155, 241, 89, 23);
mdetail.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("View Seat Position");
lblNewLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
seatposition.main(null);
mdetail.setVisible(false);
}
});
lblNewLabel.setBounds(282, 245, 112, 14);
mdetail.getContentPane().add(lblNewLabel);
Label label_1_2 = new Label("Welcome \"user\"");
label_1_2.setBounds(10, 10, 89, 22);
mdetail.getContentPane().add(label_1_2);
Label label_1_1_2_1_1 = new Label("Number of ticket");
label_1_1_2_1_1.setBounds(53, 202, 101, 22);
mdetail.getContentPane().add(label_1_1_2_1_1);
JComboBox comboBox_1_2_1 = new JComboBox();
comboBox_1_2_1.setBounds(155, 202, 226, 22);
mdetail.getContentPane().add(comboBox_1_2_1);
JMenuBar menuBar = new JMenuBar();
mdetail.setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Option");
menuBar.add(mnNewMenu);
JMenuItem mntmNewMenuItem = new JMenuItem("Logout");
mnNewMenu.add(mntmNewMenuItem);
JMenuItem exitmenu = new JMenuItem("Exit");
exitmenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int exit = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit", "Exit", JOptionPane.YES_NO_OPTION);
if(exit==JOptionPane.YES_OPTION) {
System.exit(0);
}else {
mdetail.setVisible(true);
}
}
});
mnNewMenu.add(exitmenu);
}
}

How to show the Oracle table list in a JTable?

So I am trying to build a CRUD app, I am able to perform all the operations in a console app and now I want to use the same methods in my GUI application. I have setup all the necessary fields and a table, the add button works and I can implement the others too! my question is how to work with the JTable?
Here is the code for my window builder. You can see that I have set columns for the tables too.
this is what the GUI looks like
package clientGUI;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import bus.Student;
import data.ConnectionDB;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class DbTester1 {
private JFrame frame;
private JTextField textID;
private JTextField textFN;
private JTextField txtLN;
private JTable table;
private JTable table_1;
ArrayList<Student> studentList= null;
String query = "" ;
Statement stmt = null;
ResultSet rs = null;
Student aStudent = null;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
DbTester1 window = new DbTester1();
window.frame.setVisible(true);
}
});
}
public DbTester1() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 732, 695);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblID = new JLabel("ID");
lblID.setBounds(10, 11, 46, 14);
frame.getContentPane().add(lblID);
JLabel lblFN = new JLabel("FN");
lblFN.setBounds(11, 42, 57, 14);
frame.getContentPane().add(lblFN);
JLabel lblLN = new JLabel("LN");
lblLN.setBounds(10, 79, 46, 14);
frame.getContentPane().add(lblLN);
textID = new JTextField();
textID.setBounds(78, 8, 86, 20);
frame.getContentPane().add(textID);
textID.setColumns(10);
textFN = new JTextField();
textFN.setBounds(78, 39, 86, 20);
frame.getContentPane().add(textFN);
textFN.setColumns(10);
txtLN = new JTextField();
txtLN.setBounds(78, 76, 86, 20);
frame.getContentPane().add(txtLN);
txtLN.setColumns(10);
ArrayList<Student> studList = new ArrayList<Student>();
JButton btnAdd = new JButton("Add");
btnAdd.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Student aStudent = new Student(Integer.parseInt(textID.getText()) ,
textFN.getText(), txtLN.getText());
studList.add(aStudent);
}
});
btnAdd.setBounds(0, 103, 89, 23);
frame.getContentPane().add(btnAdd);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(174, 11, 250, 292);
frame.getContentPane().add(scrollPane);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"ID", "FN", "LN"
}
));
scrollPane.setViewportView(table);
table_1 = new JTable();
scrollPane.setColumnHeaderView(table_1);
JButton btnConnect = new JButton("Connect");
btnConnect.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
con = ConnectionDB.getConnection();
JOptionPane.showMessageDialog(null, "Connection
Established!");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "Connection failed!");
}
}
});
btnConnect.setBounds(0, 128, 89, 23);
frame.getContentPane().add(btnConnect);
JButton btnSearch = new JButton("Search");
btnSearch.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnSearch.setBounds(0, 153, 89, 23);
frame.getContentPane().add(btnSearch);
JButton btnUpdate = new JButton("Update");
btnUpdate.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnUpdate.setBounds(0, 178, 89, 23);
frame.getContentPane().add(btnUpdate);
JButton btnRefresh = new JButton("Refresh");
btnRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
con = ConnectionDB.getConnection();
String id, fn, ln;
query = "select * from student";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
studentList = new ArrayList<Student> ();
while(rs.next())
{
id = rs.getString(1);
fn = rs.getString(2);
ln = rs.getString(3);
aStudent = new Student(Integer.parseInt(id) , fn, ln);
studentList.add(aStudent);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "Connection read
data!!!!!");
}
}
});
btnRefresh.setFont(new Font("Tahoma", Font.PLAIN, 8));
btnRefresh.setBounds(0, 205, 89, 23);
frame.getContentPane().add(btnRefresh);
}
}

I can't make an object of this class from another class

I'm trying to open this gui from an action listener in another class but for whatever reason it's not doing it, any and all help appreciated.
package gui;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.table.DefaultTableModel;
import database.DBConnection;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JTextArea;
import javax.swing.JTable;
public class OrderExample {
static JFrame frame;
public static void main(String[] args){
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
JFrame frame = new JFrame();
JTable table= new JTable();
table.setBounds(428, 445, 396, -328);
Object[] columns = {"Product Id", "Product Name", "Description", "Price"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
table.setModel(model);
table.setBackground(Color.white);
table.setForeground(Color.black);
Font font = new Font("", 1, 22);
table.setRowHeight(30);
JTextField prodId = new JTextField();
JTextField prodName = new JTextField();
JTextField prodPrice = new JTextField();
JButton btnAdd = new JButton("Add");
JButton btnDelete = new JButton("Delete");
JButton btnExit = new JButton("Exit");
prodId.setBounds(20, 56, 230, 38);
prodName.setBounds(20, 129, 230, 38);
prodPrice.setBounds(21, 201, 229, 39);
btnAdd.setBounds(20, 451, 100, 38);
btnDelete.setBounds(150, 451, 100, 38);
btnExit.setBounds(20, 511, 100, 39);
JScrollPane pane = new JScrollPane(table);
pane.setBounds(281, 32, 440, 518);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(pane);
frame.getContentPane().add(prodId);
frame.getContentPane().add(prodName);
frame.getContentPane().add(prodPrice);
frame.getContentPane().add(btnAdd);
frame.getContentPane().add(btnDelete);
frame.getContentPane().add(btnExit);
JLabel lblAddId = new JLabel("Product ID");
lblAddId.setBounds(20, 32, 79, 14);
frame.getContentPane().add(lblAddId);
JLabel lblProduct = new JLabel("Product Name");
lblProduct.setBounds(20, 105, 100, 14);
frame.getContentPane().add(lblProduct);
JLabel lblProductPrice = new JLabel("Product Price");
lblProductPrice.setBounds(20, 178, 90, 14);
frame.getContentPane().add(lblProductPrice);
JButton btnListProducts = new JButton("List Products");
btnListProducts.setBounds(150, 511, 100, 39);
frame.getContentPane().add(btnListProducts);
JTextArea description = new JTextArea();
description.setBounds(20, 276, 230, 164);
frame.getContentPane().add(description);
JLabel lblDescription = new JLabel("Description");
lblDescription.setBounds(20, 251, 116, 14);
frame.getContentPane().add(lblDescription);
Object[] row = new Object[4];
btnAdd.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
row[0] = prodId.getText();
row[1] = prodName.getText();
row[2] = description.getText();
row[3] = prodPrice.getText();
model.addRow(row);
try{
Connection connection = DBConnection.getConnection();
PreparedStatement ps = connection.prepareStatement("insert into stock(sname, description, quantity , price) values(?,?,20,?);");
ps.setString(1, prodName.getText());
ps.setString(2, description.getText());
ps.setDouble(3, Double.parseDouble( prodPrice.getText()));
ps.executeUpdate();
}
catch(SQLException sqle){
sqle.printStackTrace();
}
}
});
btnDelete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow();
if(i >= 0){
model.removeRow(i);
}
else{
System.out.print("Delete ");
}
}
});
table.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
int i = table.getSelectedRow();
prodId.setText(model.getValueAt(i, 0). toString());
prodName.setText(model.getValueAt(i, 1).toString());
prodPrice.setText(model.getValueAt(i, 3).toString());
description.setText(model.getValueAt(i, 2).toString());
}
});
btnListProducts.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int i = table.getSelectedRow();
try{
Connection connection = DBConnection.getConnection();
Statement statement = connection.createStatement();
ResultSet rs;
if(prodId.getText().equalsIgnoreCase(""))
rs = statement.executeQuery("select * from stock;");
else
rs = statement.executeQuery("select * from stock where stockID = " + prodId.getText() + ";");
while(rs.next()){
row[0] = rs.getInt("stockID");
row[1] = rs.getString("sname");
row[2] = rs.getString("description");
row[3] = rs.getDouble("price");
model.addRow(row);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnExit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
frame.dispose();
}
});
frame.setSize(771, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
This is the actionlistener code
btnStock.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
OrderExample window = new OrderExample();
}
});
I've tried to set window to visible but it just gives me an error.
The class OrderExamplehas all of its functionality in its (static) main method which is never been called by your Actionlistener implementation.
You could simply add the call to OrderExample.main to your Actionlistener implementation, but you should better first move the content of main to a non static method (e.g.: init) and call that.

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!

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