Use a Java Class to display data to jTable from a jFrame - java

I would like to know how can I reference a java class in my jFrame form to display data on the jTable. This is a code from my jFrame and I want to know how can I put it in a java class and just reference the class here in the JFrame so I could save space in this JFrame form
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}

Something like this?
public class CustomActionHandler {
private JComboBox jComboBox1;
// all the necessary stuff you need for the code to work
CustomActionHandler(JComboBox jComboBox1, etc...) {
this.jComboBox1 = jComboBox1;
// finish passing all the data here
}
public static void JComboActionFollowup() {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
and in your JFrame:
private CustomActionHandler actionhandler = new CustomActionHandler(jComboBox1, etc...)
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
actionhandler.JComboActionFollowup();
}

Related

Cannot login using Swing

I created a login GUI login form and tried to login if the username and password matches with that entered in the database. But, I am unable to login
I could not find any error in the code.
public class Login {
private JTextField nameTextField;
private JButton submitButton;
private JTextField passwordTextField;
private JLabel Message;
private JPanel LoginPanel;
public static void main(String[] args) {
JFrame frame=new JFrame("Login");
frame.setContentPane(new Login().LoginPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(650,500);
frame.setVisible(true);
}
public Login() {
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
while (rs.next()) {
if (rs.getString("name").equals(nameTextField.getText()) && rs.getString("password").equals(passwordTextField.getText())) {
Message.setText("Login Success");
}
else {
Message.setText("Failed");
}
}
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
});
}}
If the password and username matches, I want the application to show the message "Login Success"
Currently you're scanning the whole table and in fact check the username/password of the last element in the DB.
I would simply get the (unique) element corresponding to the username entered and verify the password.
Something like this:
PreparedStatement st = con.prepareStatement("SELECT password FROM employee WHERE name = ?");
st.setString(1, nameTextField.getText().trim());
ResultSet rs = st.executeQuery();
if (rs.next() && rs.getString(1).equals(passwordTextField.getText()))
Message.setText("Login Success");
else
Message.setText("Failed");
rs.close();
con.close();

Adding row in jtable and database using Java

I have a problem with my code and it has no error log so I can't see the problem . . .
Current Problem:
Mainclass() is where the main frame is. . . Clicking ADD will open
AddBroker() and clicking ADD in AddBroker() will update databse and jtable
in MainClass(). Database can now be updated but the jtable in MainClass() won't
change until you open it again
This is my main class (other codes were redacted to focus on problem)
public class MainClass extends JFrame {
JButton button_17 = new JButton("ADD");
button_17.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//to call class AddBroker()
AddBroker ab = new AddBroker();
ab.setVisible(true);
}
});}
Then this is the class for AddBroker(). . .
public class AddBroker extends JFrame {
JButton btnAdd = new JButton("ADD");
final Object[] addBrokerrow = new Object[3];
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ButtonCon bcd = new ButtonCon();
DriverTableCon dtcd = new DriverTableCon(); //this is just jtable
MainClass mcd = new MainClass();
String a = brokerBroker.getText();
String b = addBroker.getText();
String c = tinBroker.getText();
addBrokerrow[0] = a;
addBrokerrow[1] = b;
addBrokerrow[2] = c;
dtcd.modelBroker.addRow(addBrokerrow);
bcd.addBrokerCon(a,b,c);
}
});}
And ButtonCon() is where the adding of data is
public class ButtonCon {
Connection con;
Statement st;
ResultSet rs;
StringBuffer results;
String url = "jdbc:ucanaccess://C://DATABASE//NTD.accdb";
public void addBrokerCon(String broker, String add, String tin) {
try {
con = DriverManager.getConnection(url);
String sql = "INSERT INTO brokerT (Broker, Address, Tin_No) VALUES (?,?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, broker);
ps.setString(2, add);
ps.setString(3, tin);
ps.executeUpdate();
ps.close();
con.close();
}
catch (Exception e) {
System.out.print(e.toString());
}
} }
There is no error so I have no idea what is wrong here. Any input would be appreciated :)
So it's been a week and what I did try to solve the problem and what I did is add a "Refresh" button that loads the table again.
You fogot about ps.executeUpdate(); between ps.setString(3, tin); and ps.close();.
And remove all with st it is not necessary.

Load data from MySQL into JComboBox

I have two MySQL tables as image below
movie
movie_title
JComboBox combo = new JComboBox();
combo.setBounds(125, 15, 190, 20);
try {
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select title FROM movie_title";
PreparedStatement ps=connect.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("title");
combo.addItem(name);
}
} catch (Exception e) {
System.out.println("null");
}
combo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JComboBox comboBox=(JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
displayDay(selected);
}
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
combo1.addItem(day);
}
} catch (Exception e) {
System.out.println("null");
}
}
});
I have implemented ActionListener in comboBox. When user select movie Marvel's Captain America, it will get the movie_day item from movie and load into combo1. Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?
Edit
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
DefaultComboBoxModel model = (DefaultComboBoxModel)combo1.getModel();
if (model.getIndexOf(day) == -1)
{
combo1.addItem(day);
}
}
} catch (Exception e) {
System.out.println("null");
}
Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?
Before adding the date to the combo box you need to check if the date already exists.
DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel();
if (model.getIndexOf(theDate) == -1)
{
comboBox.addItem( theDate );
}
You could also change the SQL statement to only get "unique" dates, but I don't know SQL well enough to give you the actual syntax. Maybe this SQL Tutorial will help, otherwise you need to find a better tutorial.

Populating jTable from database based on a column value entered in same table column

I have a jTable. It has 6 column. I need to enter name in column 1 and once I press enter key the other 5 columns must be populated from database. Can anyone help please?
private void jTable2KeyPressed(java.awt.event.KeyEvent evt) {
{
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
{
// Object s=jTable2.getModel().getValueAt(1, 1);
//System.out.println("Value" +s);
Object Name= jTable2.getModel().getValueAt(1, 1);;
try {
openconn();
PreparedStatement ps;
System.out.println("Val" +Name);
ps = conn.prepareStatement("select * from inventory.addproducts where name='"+Name+"'");
rs= ps.executeQuery();
if(rs.next())
{
String rate=rs.getString(2);
jTable2.getModel().setValueAt(rate, 2, 3);
}
else
{
JOptionPane.showInputDialog("Wrong input");
}
conn.close();
}
catch(Exception ex)
{
}
}}
}
Hope this will make sense how to do it, use DefaultTableModel to populate your JTabel, a simple example, have not tried it out:
private DefaultTableModel model=new DefaultTableModel();
private JTable table=new JTable(model);
private JButton submit =new JButton("Submit");
public void populate(){
submit.addActionListener(e->{model.addRow(new Object[]{textField.getText(),database.getSurname(),database.getAge()});})
}

Refresh JTable after insert

Am programming of the application that manage football's players and clubs
I'm real stopped in small part and I couldn't find for it any solution after the try of many ideas.
Simply: I have a JTable and I want to refresh it after any task (Insert, Update or Delete).
That's the code
//for fill the JTable
// class controllApp
class controllApp(){
public DefaultTableModel getCleubData() {
Vector<Vector<String>> data = new Vector<Vector<String>>();
Vector<String> colum = new Vector<String>();
colum.add("id_c");
colum.add("coach");
colum.add("nom_cleub");
colum.add("DATE_CREATION");
colum.add("COULEUR_MAILLOT");
colum.add("COUNTRY");
String query = "select id_c,coach,nom_cleub,date_creation,couleur_maillot,country from CLEUB ORDER BY ID_C";
try {
Connection conn = ReportDriver.connectDB(DB_CONNECTION, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Vector<String> vstring = new Vector<String>();
vstring.add(rs.getString("id_c"));
vstring.add(rs.getString("coach"));
vstring.add(rs.getString("nom_cleub"));
java.sql.Date date = rs.getDate("date_creation");
java.text.DateFormat df = java.text.DateFormat.getDateInstance();
vstring.add(df.format(date));
vstring.add(rs.getString("couleur_maillot"));
vstring.add(rs.getString("country"));
vstring.add("\n\n\n\n\n\n\n");
data.add(vstring);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
}
}
}
DefaultTableModel d = new DefaultTableModel(data, colum);
return d;
}
}
//fill frame in other class (frame classe)
// class frame() to call controllAPP.getJoueurdata()
class frame(){
private static JTable table1;
AbstractTableModel model;
model = new controllApp().getJoueurData();
table1 = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table1);
scrollPane.setBounds(6, 29, 807, 297);
panel.add(scrollPane);
}
the solution is to get the Jtable's Model then add Vector data to it, then you have to set the model to the existing JTable.

Categories