How to show the Oracle table list in a JTable? - java

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);
}
}

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);
}
}

Calling another JFrame after veryfing user identity

any help would be greatly appreciated.
I've created 2 JFrames, one is a login window which verifies user credentials and I've linked it with my website's mySQL(This works and was hard since I'm very new to Java), and the other one is my main window which contains the main user interface where the user will work from.
I am trying to find a way that when user credentials are verified, the login window closes and opens the Main window. The more I dig into this, the more I think I've built this whole thing wrong, because both JFrames are built in main methods (I though this was how you did it, every tutorial begins with a main method).
to the actionPerform I've created on the JButton or textField_Password, but that does not work at all.Any idea how to open another class from actionPerform?
I would like to open the main window once user credentials are verified. Any ideas on how to proceed. This is all new to me and any help would be greaty appreciated.
Thanks in advance to anyone who helps me with this one, because I'm kind of stuck!
I was trying to add the following:
Main window = new Main();
window.frame.setVisible();
to my Jbutton actionPerform
here is the main code, any help would be greatly appreciated as I am a little loss
import javax.swing.JFrame;
import java.awt.SystemColor;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
//import com.mysql.jdbc.Connection;
//import com.mysql.jdbc.PreparedStatement;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JSeparator;
import javax.swing.JPasswordField;
import javax.swing.JCheckBox;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.sql.SQLException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Login {
private JFrame frame;
private JTextField txtUsername;
private JPasswordField txtPassword;
final String signUp = ("https://www.google.com");
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setBounds(100, 100, 547, 382);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setLocationRelativeTo(null);
// frame.setUndecorated(true);
txtUsername = new JTextField();
txtUsername.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
txtUsername.setText(null);
}
});
JLabel labelResponse = new JLabel("");
labelResponse.setHorizontalAlignment(SwingConstants.CENTER);
labelResponse.setFont(new Font("Dialog", Font.BOLD, 12));
labelResponse.setForeground(Color.ORANGE);
labelResponse.setBounds(122, 280, 277, 30);
frame.getContentPane().add(labelResponse);
txtUsername.setBorder(null);
txtUsername.setHorizontalAlignment(SwingConstants.CENTER);
txtUsername.setFont(new Font("Meiryo", Font.BOLD, 18));
txtUsername.setForeground(new Color(0, 128, 0));
txtUsername.setOpaque(false);
txtUsername.setText("Username");
txtUsername.setBackground(SystemColor.inactiveCaption);
txtUsername.setBounds(82, 62, 353, 53);
frame.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
/*
* JLabel labelClose = new JLabel("X");
*
labelClose.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
* labelClose.addMouseListener(new MouseAdapter() {
*
* #Override public void mouseClicked(MouseEvent e) {
System.exit(0); } });
* labelClose.setFont(new Font("Tahoma", Font.BOLD, 20));
* labelClose.setForeground(new Color(102, 205, 170));
labelClose.setBounds(493,
* 11, 22, 22); frame.getContentPane().add(labelClose);
*
* JLabel labelMin = new JLabel("-");
*
labelMin.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
* labelMin.addMouseListener(new MouseAdapter() {
*
* #Override public void mouseClicked(MouseEvent arg0) {
* frame.setState(Frame.ICONIFIED); } });
labelMin.setForeground(new Color(102,
* 205, 170)); labelMin.setFont(new Font("Tahoma", Font.BOLD,
20));
* labelMin.setBounds(470, 11, 22, 22);
frame.getContentPane().add(labelMin);
*/
JLabel lblGt = new JLabel("Log In");
lblGt.setForeground(new Color(0, 128, 0));
lblGt.setFont(new Font("Meiryo", Font.BOLD, 20));
lblGt.setBounds(10, 5, 88, 38);
frame.getContentPane().add(lblGt);
JSeparator separator = new JSeparator();
separator.setBounds(82, 113, 353, 2);
frame.getContentPane().add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(82, 190, 353, 2);
frame.getContentPane().add(separator_1);
JCheckBox chckbxShowPass = new JCheckBox("Show Pass");
chckbxShowPass.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
chckbxShowPass.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (chckbxShowPass.isSelected()) {
txtPassword.setEchoChar((char) 0);
} else {
txtPassword.setEchoChar('*');
}
}
});
chckbxShowPass.setBorder(null);
chckbxShowPass.setOpaque(false);
chckbxShowPass.setForeground(new Color(0, 128, 0));
chckbxShowPass.setFont(new Font("Meiryo", Font.BOLD, 14));
chckbxShowPass.setBackground(new Color(0, 128, 0));
chckbxShowPass.setBounds(409, 281, 106, 23);
frame.getContentPane().add(chckbxShowPass);
JLabel labelRegister = new JLabel("Register");
labelRegister.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
labelRegister.setForeground(new Color(0, 128, 0));
labelRegister.setFont(new Font("Meiryo", Font.BOLD, 14));
labelRegister.setBounds(10, 285, 76, 16);
frame.getContentPane().add(labelRegister);
JButton buttonLogin = new JButton("Login");
buttonLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "password"); // not the actual
String query = "select EmailAddress,
Password from users where EmailAddress LIKE '%"
+
txtUsername.getText() + "%'";
PreparedStatement statement =
con.prepareStatement(query);
ResultSet result =
statement.executeQuery();
if (result.next()) {
String dbasePassword =
result.getString("Password").toString().trim();
String enteredPassword = new
String(txtPassword.getText().trim());
if
(dbasePassword.equals(enteredPassword))
labelResponse.setText("User recognized");
else
labelResponse.setText("Verify credentials");
} else {
labelResponse.setText("You
must be registered to use this software.");
}
statement.close();
con.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception evt) {
evt.printStackTrace();
labelResponse.setText("Exception
occurred while searching in the users table");
}
}
});
txtPassword = new JPasswordField();
txtPassword.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER)
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root",
"password");
String query = "select
EmailAddress, Password from users where EmailAddress LIKE '%"
+
txtUsername.getText() + "%'";
PreparedStatement statement =
con.prepareStatement(query);
ResultSet result =
statement.executeQuery();
if (result.next()) {
String dbasePassword =
result.getString("Password").toString().trim();
String enteredPassword
= new String(txtPassword.getText().trim());
if
(dbasePassword.equals(enteredPassword))
labelResponse.setText("User recognized");
else
labelResponse.setText("Verify credentials");
} else {
labelResponse.setText("You must be registered to use this software.");
}
statement.close();
con.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception evte) {
evte.printStackTrace();
labelResponse.setText("Exception occurred while searching in the users
table");
}
}
});
txtPassword.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
txtPassword.setText(null);
}
});
txtPassword.setText("Password");
txtPassword.setBorder(null);
txtPassword.setHorizontalAlignment(SwingConstants.CENTER);
txtPassword.setForeground(new Color(0, 128, 0));
txtPassword.setFont(new Font("Meiryo", Font.BOLD, 18));
txtPassword.setOpaque(false);
txtPassword.setBackground(SystemColor.inactiveCaption);
txtPassword.setBounds(82, 139, 353, 53);
frame.getContentPane().add(txtPassword);
buttonLogin.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonLogin.setBorderPainted(false);
buttonLogin.setBackground(new Color(0, 128, 0));
buttonLogin.setFont(new Font("Tahoma", Font.PLAIN, 18));
buttonLogin.setBounds(82, 216, 353, 53);
frame.getContentPane().add(buttonLogin);
labelRegister.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
try {
Desktop.getDesktop().browse(new
URI("insertURL"));
} catch (Exception ex) {
// System.out.println(ex);
}
}
});
}
}
I found a solution and I will post it here. Hopefully it helps other new coders out there.
My main problem was that I was trying to link two application windows. Instead of selecting New/Other/Jframe, I used New/Other/Application Window which makes it tough to call the second window.

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.

Write my ComboBox value to file

I've got a problem with this, I've got text from comboBox saved into text variable but now I can't make it to be saved to the file like 'num1' and 'num2' after I click a buttom. I know I am missing something simple - or everything is wrong anyways please help! Thank!
package windowbuilded.views;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class WiewWindow {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WiewWindow window = new WiewWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public WiewWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1, num2, ans2, combo;
num1=Integer.parseInt(textField.getText());
num2=Integer.parseInt(textField_1.getText());
ans2 = num1 + num2;
textField_2.setText(Integer.toString(ans2));
try{
File dir = new File("C:\\test");
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
FileWriter writer = new FileWriter(child, true);
PrintWriter out = new PrintWriter(writer);
out.println(num1);
out.println(num2);
out.close();
}
}
} catch (IOException e) {
// do something
}
}
});
btnNewButton.setBounds(124, 206, 89, 23);
frame.getContentPane().add(btnNewButton);
textField = new JTextField();
textField.setBounds(10, 34, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(124, 34, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(124, 101, 86, 20);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Yes", "No", "Blah!"}));
String text = (String)comboBox.getSelectedItem();
System.out.println(text);
comboBox.setBounds(265, 101, 121, 20);
frame.getContentPane().add(comboBox);
}
}

How can I delete/edit row in JTable and MySQL using hibernate?

I have a JTable displaying the content of a table in MYSQL database. I am able also to add a record in my JTable and my database.. The edit and delete operations are only possible in my JTable (the changes are not diplayed to my database). I want to add hibernate code in my buttons events so the changes can be displayed to MySQL database.
Any help will be appreciated.
Here's the class concerned:
package com.hibernate.stock;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JButton;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Gestion extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTable table;
List biens;
int i;
PersistantBien bien = new PersistantBien();
final String columnNames[] = {"ID", "Nom", "Catégorie", "Quantité"};
final DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gestion frame = new Gestion();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Gestion() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblId = new JLabel("ID:");
lblId.setBounds(12, 12, 70, 15);
contentPane.add(lblId);
JLabel lblNom = new JLabel("nom:");
lblNom.setBounds(12, 39, 70, 15);
contentPane.add(lblNom);
JLabel lblCatgorie = new JLabel("catégorie:");
lblCatgorie.setBounds(12, 69, 70, 15);
contentPane.add(lblCatgorie);
JLabel lblQuantit = new JLabel("quantité:");
lblQuantit.setBounds(12, 108, 70, 15);
contentPane.add(lblQuantit);
textField = new JTextField();
textField.setBounds(106, 10, 114, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(106, 37, 114, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(106, 67, 114, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(106, 106, 114, 19);
contentPane.add(textField_3);
textField_3.setColumns(10);
table = new JTable();
table.setBounds(361, 50, 1, 1);
contentPane.add(table);
final JScrollPane tableScrollPane = new JScrollPane(table);
tableScrollPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
textField.setText(tableModel.getValueAt(table.getSelectedRow(), 0).toString());
textField_1.setText(tableModel.getValueAt(table.getSelectedRow(), 1).toString());
textField_2.setText(tableModel.getValueAt(table.getSelectedRow(), 2).toString());
textField_3.setText(tableModel.getValueAt(table.getSelectedRow(), 3).toString());
}
});
tableScrollPane.setBounds(240, 11, 198, 135);
contentPane.add(tableScrollPane);
JButton btnAjouter = new JButton("Ajouter");
btnAjouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
bien.setId_article(textField.getText());
bien.setNom_article(textField_1.getText());
bien.setCategorie(textField_2.getText());
bien.setQuantite(textField_3.getText());
s.save(bien);
s.flush();
tx.commit();
s.close();
}
});
btnAjouter.setBounds(12, 158, 117, 25);
contentPane.add(btnAjouter);
JButton btnEditer = new JButton("Editer");
btnEditer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
tableModel.setValueAt(textField.getText(), table.getSelectedRow(), 0);
tableModel.setValueAt(textField_1.getText(), table.getSelectedRow(), 1);
tableModel.setValueAt(textField_2.getText(), table.getSelectedRow(), 2);
tableModel.setValueAt(textField_3.getText(), table.getSelectedRow(), 3);
s.save(bien);
s.flush();
tx.commit();
s.close();
}
});
btnEditer.setBounds(150, 158, 117, 25);
contentPane.add(btnEditer);
JButton btnSupprimer = new JButton("supprimer");
btnSupprimer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
tableModel.removeRow(table.getSelectedRow());
SQLQuery query=s.createSQLQuery("DELETE * FROM TBiens WHERE id-article='"+textField.getText()+"'");
s.flush();
tx.commit();
s.close();
}
});
btnSupprimer.setBounds(303, 158, 117, 25);
contentPane.add(btnSupprimer);
JButton btnAfficher = new JButton("Afficher");
btnAfficher.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
SQLQuery query=s.createSQLQuery("select * from TBiens");
biens = query.list();
ArrayList<Object[]> res = new ArrayList<Object[]>(biens);
final DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
table.setModel(tableModel);
for (final Object[] bien : res) {
// Assuming each row in the biens list is a list of strings...
final Object[] row = bien;
tableModel.addRow(row);
}
biens.size();
System.out.print(i);
s.flush();
tx.commit();
s.close();
}
catch (ClassCastException e) {
e.printStackTrace();
}
}
});
btnAfficher.setBounds(166, 235, 117, 25);
contentPane.add(btnAfficher);
}
}
Output:
Editing
By default, DefaultTableModel will make all the cells editable, just double click the cell you want to change and it will enter "edit" model.
To save the values back to the database will depend on what approach you want to take, you could override the setValueAt of the TableModel method and push the changes when this method is called, personally, I'd add a Save button and push the changes as a batch
Deleting
This is a little more difficult. The problem is, once you remove one row, all the indices for all the other selected items will change...
A better solution would be devise a hibernate bean/data class and load this via Hibernate. You could then use a custom implementation of the TableModel, extending from something like AbstractTableModel, which would give you management control of the content.
You would then, get all the objects that are selected (this would be a method in your custom TableModel, something like getValueAt(int row) which returned the hibernate object at the specified row) and then pass this to some kind of delete method (ie removeValue(TBiens bean)), firing the appropriate event notifications...
I finally succeeded in deleting and editing rows from my JTable and database.
Here's the code :
package com.hibernate.stock;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JButton;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Gestion extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTable table;
List biens;
int i;
PersistantBien bien = new PersistantBien();
final String columnNames[] = {"ID", "Nom", "Catégorie", "Quantité"};
final DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gestion frame = new Gestion();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Gestion() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblId = new JLabel("ID:");
lblId.setBounds(12, 12, 70, 15);
contentPane.add(lblId);
JLabel lblNom = new JLabel("nom:");
lblNom.setBounds(12, 39, 70, 15);
contentPane.add(lblNom);
JLabel lblCatgorie = new JLabel("catégorie:");
lblCatgorie.setBounds(12, 69, 70, 15);
contentPane.add(lblCatgorie);
JLabel lblQuantit = new JLabel("quantité:");
lblQuantit.setBounds(12, 108, 70, 15);
contentPane.add(lblQuantit);
textField = new JTextField();
textField.setBounds(106, 10, 114, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(106, 37, 114, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(106, 67, 114, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(106, 106, 114, 19);
contentPane.add(textField_3);
textField_3.setColumns(10);
table = new JTable();
table.setBounds(361, 50, 1, 1);
contentPane.add(table);
final JScrollPane tableScrollPane = new JScrollPane(table);
tableScrollPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
textField.setText(tableModel.getValueAt(table.getSelectedRow(), 0).toString());
textField_1.setText(tableModel.getValueAt(table.getSelectedRow(), 1).toString());
textField_2.setText(tableModel.getValueAt(table.getSelectedRow(), 2).toString());
textField_3.setText(tableModel.getValueAt(table.getSelectedRow(), 3).toString());
}
});
tableScrollPane.setBounds(240, 11, 198, 135);
contentPane.add(tableScrollPane);
JButton btnAjouter = new JButton("Ajouter");
btnAjouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
bien.setId_article(textField.getText());
bien.setNom_article(textField_1.getText());
bien.setCategorie(textField_2.getText());
bien.setQuantite(textField_3.getText());
s.save(bien);
s.flush();
tx.commit();
s.close();
}
});
btnAjouter.setBounds(12, 158, 117, 25);
contentPane.add(btnAjouter);
JButton btnEditer = new JButton("Editer");
btnEditer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
tableModel.setValueAt(textField.getText(), table.getSelectedRow(), 0);
tableModel.setValueAt(textField_1.getText(), table.getSelectedRow(), 1);
tableModel.setValueAt(textField_2.getText(), table.getSelectedRow(), 2);
tableModel.setValueAt(textField_3.getText(), table.getSelectedRow(), 3);
SQLQuery query=s.createSQLQuery("update TBiens "
+ "set id_article='"+ table.getValueAt(table.getSelectedRow(),0) +"', "
+ "nom_article= '"+ table.getValueAt(table.getSelectedRow(),1) +"', "
+ "categorie= '"+ table.getValueAt(table.getSelectedRow(),2) +"' , "
+ "quantite= '"+ table.getValueAt(table.getSelectedRow(),0) +"' "
+ "where id_article = '"+ table.getValueAt(table.getSelectedRow(),0) +"'");
query.executeUpdate();
s.flush();
tx.commit();
s.close();
}
});
btnEditer.setBounds(150, 158, 117, 25);
contentPane.add(btnEditer);
JButton btnSupprimer = new JButton("supprimer");
btnSupprimer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
tableModel = (DefaultTableModel) table.getModel();
SQLQuery query=s.createSQLQuery("delete from TBiens where id_article = '"+ table.getValueAt(table.getSelectedRow(),0) +"'");
query.executeUpdate();
tableModel.removeRow(table.getSelectedRow());
s.flush();
tx.commit();
s.close();
}
});
btnSupprimer.setBounds(303, 158, 117, 25);
contentPane.add(btnSupprimer);
JButton btnAfficher = new JButton("Afficher");
btnAfficher.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
SQLQuery query=s.createSQLQuery("select * from TBiens");
biens = query.list();
ArrayList<Object[]> res = new ArrayList<Object[]>(biens);
final DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
table.setModel(tableModel);
for (final Object[] bien : res) {
// Assuming each row in the biens list is a list of strings...
final Object[] row = bien;
tableModel.addRow(row);
}
biens.size();
System.out.print(i);
s.flush();
tx.commit();
s.close();
}
catch (ClassCastException e) {
e.printStackTrace();
}
}
});
btnAfficher.setBounds(166, 235, 117, 25);
contentPane.add(btnAfficher);
}
}

Categories