I have made an applet with a search engine functionality. The problem here is, when I am trying to search using a keyword first, it is displayed properly by opening a new JFrame in JTable format. But when I close that frame and enter something else in the search form to search something else, it not only shows the latest thing I have searched for but also those things I searched for before. And horizontally, it keeps repeating the table columns too. Here are screenshots:
First I search for Dosa:
And then I close that Frame and search for Idli, look how it comes:
Can anyone help me and tell me where I am going wrong? Here is my code for the Database activity and retrieval thing.
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
try {
s=field.getText();
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/delikat",
"root", "");
Statement st = (Statement) con.createStatement();
ResultSet rs= (ResultSet) st.executeQuery( "SELECT * FROM delicious where name = '"+s+ "'" );
ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
st.close();
}
catch(Exception e) {
e.printStackTrace();
}
Vector<Vector<Object>> NULL = null;
if(data==NULL) {
JOptionPane.showMessageDialog(frame, "No Data Found");
}
else {
//Declare a new Frame for the Query Result Display
JFrame tab=new JFrame();
//Add the Data and the Column Names to the Table
JTable table = new JTable(data, columnNames);
//Add Scroll Pane for instances when more data is to be displayed
JScrollPane scrollPane = new JScrollPane( table );
/* Open the Result of the Query in a new Frame, in a Tabular Format with Scroll Pane.
Add all the elements to the Frame and set the specifications of the Frame like
Size, Visibility, etc.
*/
tab.add( scrollPane );
tab.setVisible(true);
tab.setSize(810,100);
}
}
});
Please help me overcome this problem. Thank You.
required to reinitialize data = new Vector<Vector<Object>> if Vector<Vector<Object>> data = new Vector<Vector<Object>> (pseudo code) is reused then old 2D array is a new without old elements
use XxxTableModel for underlaying data instead of recreate a whole array, could be as standard of possible ways
Try:
data.clear();
before
while (rs.next()) {...
Related
I simply want to fill a table with data from my SQL database that I created with phpMyAdmin. I'll share an image of my database.
I'm completely perplex as to what my problem is, I have a try catch to return me an error message if anything goes wrong but i'm not getting anything back. I know the problem isn't my conection because I have another table that I was able to fill with data.
I simplied copy and pasted and changed the values, but my new table isn't getting any data.
My table name is jTable_Inv. This is the first time I have a problem like this.
Heres an image of my database.
And heres my code:
public class GestionInventario extends javax.swing.JFrame {
DefaultTableModel model = new DefaultTableModel();
/**
* Creates new form GestionInventario
*/
public GestionInventario() {
initComponents();
initComponents();
setSize(600, 450);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
try {
Connection cn = Conexion.conectar();
PreparedStatement pst = cn.prepareStatement(
"select Id_inventario, Disponible, Pelicula from inventario");
ResultSet rs = pst.executeQuery();
jTable_Inv = new JTable(model);
jScrollPane1.setViewportView(jTable_Inv);
model.addColumn(" ");
model.addColumn("Disponibles");
model.addColumn("Pelicula");
while(rs.next()) {
Object [] fila = new Object[3];
for (int i = 0; i<3; i++){
fila[i] = rs.getObject(i + 1);
}
model.addRow(fila);
}
cn.close();
} catch (SQLException e) {
System.err.println("Error en el llenado de la tabla");
}
}
Error being cause by initializing my components twice
I am having trouble showing my database filled JTable within my GUI application.
My code below runs through and creates a GUI with a panel, I then create my JTable and add it onto my application. I then run through a method that supposedly populates the table. After the populating has finished, nothing shows.
Dissecting my code, I'm led to believe somewhere is causing the data not to parse into my table, for some unknown reason, which is why I have come here.
At the click of a button, this code entails:
JTable tigerTable = new JTable();
JPanel centerPanel = new JPanel();
centerPanel.add(tigerTable, new GridBagConstraints());
FillTable(tigerTable, "SELECT * FROM TIGER_INFO");
The FillTable method as follows:
//Add buildTableModel method
public void FillTable(JTable table, String Query)
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:derby:STOCK_CONTROL");
Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stat.executeQuery(Query);
System.out.println("Connected");
//Remove previously added rows
while (table.getRowCount() > 0)
{
((DefaultTableModel) table.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
conn.close();
}
catch (InstantiationException |
IllegalAccessException |
ClassNotFoundException |
SQLException e)
{
System.out.println(e);
e.printStackTrace();
}
}
Doing so creates the application, but does not show any table with data. My database contains 3 columns and 3 rows, but I do not see my data displayed inside a JTable.
My question is, how can I populate my JTable with my database and display it correctly on my GUI application?
If you need anything else, please let me know and I will provide as much as I can.
Thank you in advance.
I think you mix the operation, i suggest to use this instruction :
Create a Bean, or Entity to store the information of your Object
Get the List of your data,
Display your data in your JTable,
So you can use this to display your data in your JTable :
....
List<TIGER_INFO> list = new ArrayList<>();//create a List of data
while (rs.next()){
//fill data in your List
list.add(new TIGER_INFO(rs.getTYPExxx("att1"), rs.getTYPExxx("att2"), rs.getTYPExxx("att3"));
}
//when you finish call your function which display your data :
fillData(list);
....
Fill date method can look like this :
private void fillData(List<TIGER_INFO> list) {
DefaultTableModel model = (DefaultTableModel) jTableName.getModel();
while (model.getRowCount() > 0) {
for (int i = 0; i < model.getRowCount(); i++) {
model.removeRow(i);
}
}
for (TIGER_INFO obj : list) {
model.addRow(new Object[]{
obj.getAttribute1(),
obj.getAttribute2,
obj.getAttribute3
});
}
}
I recommend to write a class extending AbstractTableModel. Add a function to this class filling the content based on a SQL-Statement. Then it will look something like:
TigerTableModel tigerModel = new TigerTableModel(dbConnection);
tigerModel.executeQuery("select * FROM TIGER_INFO");
JTable tigerTable = new JTable(tigerModel);
or you create a generic TableModel that is able to run every SQL-statement, so you are very flexible in your project.
I have found the solution - I've been trying to wrap my head around the problem for way too long, and I finally fixed it.
Try setting the table model manually first.
JTable tigerTable = new JTable();
tigerTable.setModel(new DefaultTableModel(0, numberOfColumns));
When you don't specify a model, the JTable creates an anonymous inner class and generally doesn't behave how you want it to.
I am trying to pull data from a table in a mysql database and populate the results in a JTable. There are currently 3 tabs in the UI, the first two being input screens, which work fine. The 3rd tab, I am trying to run a query (after button is pushed) and display the results in a JTable. I am getting no error messages, but the screen does not display the table. Below is my code. Any assistance would be greatly appreciated. Note, user name and password have been replaced with generic. The query has also been simplified until I can get it to work. The system.out.print was just to check and see if it was pulling any data.
private void salePropertyActionPerformed(java.awt.event.ActionEvent evt) {
String sSelectQuery = "";
Statement statement=null;
Connection conn = null;
//PreparedStatement pStatement =null;
JPanel panel= spPanel;
TableColumn column;
JTable spTable = jTable1;
Vector columnNames = new Vector();
Vector data = new Vector();
spTable = new JTable(data,columnNames);
JScrollPane scrollPane = new JScrollPane(spTable);
panel.add(scrollPane);
try {
String myDriver = "com.mysql.jdbc.Driver";
String myURL = "jdbc:mysql://localhost:3306/realestate?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
conn=DriverManager.getConnection(myURL,"root","jul1664bd");
/*Storing SQL statement*/
sSelectQuery ="SELECT propertyID, propertyPrice FROM property";
statement = conn.createStatement();
try (ResultSet rs = statement.executeQuery(sSelectQuery) //executes the query
) {
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
for(int i = 1; i<=columns; i++){
columnNames.addElement(metaData.getColumnName(i));
}
while (rs.next()){
Vector row = new Vector(columns);
for (int i=1; i<=columns; i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
System.out.println(data);
}
rs.close();
for (int i=0; i<spTable.getColumnCount(); i++){
column=spTable.getColumnModel().getColumn(i);
//column.setMaxWidth(250);
}
}
statement.close();
} catch (SQLException e) {
System.err.println("An exception ocurred");
System.err.println(e.getMessage());
} catch (ClassNotFoundException ex) {
Logger.getLogger(realEstateUI.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(this,"Query Complete");
}
/**
You are attempting to add the JTable after the UI is visible. For the addition to take affect you must call revalidate followed by repaint. As an alternative, add your JTable upon UI construction (before it is visible) and populate the model of the JTable in salePropertyActionPerformed
I am doing a Practical Assessment Task for my Grade 12 IT class. I am struggling with the code to populate my jTable (From the swing controls) in my GUI. I am using Netbeans as an IDE. The database connects using a jdbc:odbc bridge. This code is in a java class in my project.
**please note that i am relatively inexperienced when it comes to coding
Here is the code i have currently (but it gives no output in my jtable)
if you can fix it, please explain what you did or if you can please give me code that will work :)
db.setConnection();
Statement stmt = null;
try {
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}"
+ ";DBQ=src/TheChangeProjectDB.accdb");
stmt = con.createStatement();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex);
}
String sql = "SELECT * FROM KanyisaLearners";
try {
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i));
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 0; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
stmt.close();
} catch (Exception e) {
System.out.println(e);
}
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
KanyisaHoofskerm frame = new KanyisaHoofskerm();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setTitle("Learners");
frame.setVisible(true);
Given this lines:
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane); // your class extends from JFrame?
JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
And then this ones:
KanyisaHoofskerm frame = new KanyisaHoofskerm(); // new frame local variable
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
...
frame.setVisible(true);
I strongly suspect your class extends from JFrame which you are adding your table to. If so then you don't make it visible but a new frame local variable instead. Consequently there's not table displayed at all, at least as far as I can see.
If this is the case please take a look to this question with the same problem and Extends JFrame vs. creating it inside the the program topic.
Regarding your code to do database call:
Beware JDBC-ODBC bridge will no longer be included since JDK 8.
Database calls are time consuming tasks and may block the Event Dispatch Thread, causing your GUI become unresponsive. You should consider use SwingWorker to avoid this issue. Take a look to Concurrency in Swing lesson for further details.
Since JDK 7 you can use Try-with-resources statement to easily deal with Exceptions and make your code simpler and cleaner.
Your code gives an Exception when adding row.
change your code by using a descriptor instead of using index.
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 0; i < columns; i++) {
row.addElement(rs.getObject(columnNames.get(i)));
}
data.addElement(row);
}
I'm trying one sample program for practice and i want to display results of database in JTable. The problem is i have no idea how to do that. I know how to get data from database and display it on text field or console but never tried with JTable. How to do that ?
Consider that i've table which is holding information like person name, age, city and date. i want it to be displayed via JTable. Also is it possible to update the JTable display if i add the option of adding more details in program(i mean adding entries to db then that will show immediately in JTable )?
Any suggestions, pointers on how to proceed is appreciated. Thanks in advance.
JDBC + JTable # google:
Hacking Swing: A JDBC Table Model
Mastering the JTable
Making SQL Queries with JDBC and Displaying Results with Swing
here is the code
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1).toUpperCase());
}
// Get all rows.
Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> newRow = new Vector<Object>();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
you can call this method such that way
void update_Table() throws ParseException
{
// we used this try catch so that values in table automatically show(without clicking on any button) when the dialog box open
try
{
Connection con=MSUTIL.getMSConnection();
PreparedStatement pst=con.prepareStatement("select payment_mode from PaymentMode");
ResultSet rs=pst.executeQuery();
//here i call that method
table.setModel(resultSetToTableModel(rs));
table.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 14));
while(rs.next())
{
mp.paymentmode_ComboBox.addItem(rs.getString("payment_mode"));
}
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
//this method is for closing the connection
MSUTIL.cleanUp(con, pst, rs);
}
}