My code is working when I directly use jtable, but when I bound it with scroll panel, it runs one time. After another click on button it hides the data. Here is the code:
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import com.mysql.jdbc.Statement;
class Scrl extends JFrame implements ActionListener
{
JScrollPane sp;
Icon back,front;
JLabel l,l1;
JTable tb=new JTable();
DefaultTableModel model;
String column[]={"JobcardNo","Customer Name","Brand","Date","PhoneNo"};
JTextField jobt=new JTextField("");
JButton b=new JButton("click");
public Scrl()
{
b.setBounds(200,140,100,20);
jobt.setBounds(114,50,100,20);
model = new DefaultTableModel();
tb.setModel(model);
model.setColumnIdentifiers(column);
add(jobt);
add(b);
b.addActionListener(this);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
setLayout(null);
setSize(700,600);
setVisible(true);
setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
String job_no=jobt.getText();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ac_data","root","root");
java.sql.Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from main");
while(rs.next())
{
String hey=rs.getString(1);
if(hey.equals(job_no))
{
System.out.println(rs.getString(2));
String jobno=rs.getString(1);
String names=rs.getString(2);
String brand=rs.getString(21);
String date=rs.getString(6);
String phoneno=rs.getString(4);
model.addRow(new Object[]{jobno,names,brand,date,phoneno});
}
}
}
catch(Exception ee)
{
}
}
JScrollPane sp=new JScrollPane(tb);
sp.setBounds(1,165,687,440);
add(sp);
}
public static void main(String[] args)
{
new Scrl();
}
}
Scroll panel is not refreshing data itslef.
You don't close the Connection when you're finished.
You should read the information from your database once, before you construct the GUI, and put the information into a TableModel.
You're trying to place all of the Swing components by hand when you should be using a layout manager.
You're not putting your Swing components on the Event Dispatch thread.
That should be enough reading and studying to keep you busy for a while.