简体   繁体   中英

JComboBox and JTable in java applet

Here is the code for a java applet in which, the combobox will retrieve content from access database and while we select an item it must display the rows of the table which have the 'composition' field as the selected combobox item. My problem is, this works fine for the first time I select it. While the result of my first selection is being shown(which is a table), if I make a second selection on the combo box, the panel becomes blank. I want it to repeatedly show corresponding outputs for successive selections also. Kindly help me diagnose the error. Thanks in advance!

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.Date;
import java.sql.*;
import java.text.*;

public class gc implements ActionListener
{
JComboBox cc=new JComboBox();
JFrame frame=new JFrame();
JTable table;
DefaultTableModel model;
String query;
int i;
JPanel panel=new JPanel();

public gc()
{
frame.setTitle("Composition Check");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new FlowLayout());

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select DISTINCT composition from try");

while(rs.next())
{
 cc.addItem(rs.getString("composition"));
}

conn.close();
}
catch(Exception e)
{
}

p1.add(cc);
cc.addActionListener(this);
frame.add(p1,BorderLayout.NORTH);

frame.setVisible(true);
}
public void addTable(String query)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
Statement st=conn.createStatement();
System.out.println(query);
ResultSet rs=st.executeQuery(query);
ResultSetMetaData md=rs.getMetaData();
int cols=md.getColumnCount();
model=new DefaultTableModel();

model.addColumn("Purpose");
model.addColumn("Name");
model.addColumn("Manu");
model.addColumn("Expiry");
model.addColumn("Stock");
model.addColumn("Cost");
model.addColumn("Supplier");
model.addColumn("Supplier Number");
model.addColumn("Rack");

table=new JTable(model);

String[] tabledata=new String[cols];
int i=0;

while(rs.next())
{
for(i=0;i<cols;i++)
{
 tabledata[i]=rs.getObject(i+1).toString();

}
model.addRow(tabledata);

}
JScrollPane scroll = new JScrollPane(table); 
panel.setLayout(new BorderLayout());

panel.add(scroll,BorderLayout.CENTER);
frame.add(panel,BorderLayout.CENTER);
conn.close();
}
catch(Exception e)
{
}
}

public void actionPerformed(ActionEvent evt)
{
String ac=(String)cc.getSelectedItem();
System.out.println(ac);

addTable("select * from try where composition='"+ac+"'");
frame.setVisible(true);
}

public static void main(String[] args)
{
new gc();
}

}

Add

panel.removeAll();

Before you add the scroll pane. This will clear the pane and make room for the next set of results...

Update It occues to me that a better approach would be to simple replace the table's model. This lessens the risk for memory leaks, by replacing the scroll pane & table on each run.

Add a class level reference to the JTable & in your ui unit code add

table = new JTable();
JScrollPane scroll = new JScrollPane(table); 
panel.setLayout(new BorderLayout());

panel.add(scroll,BorderLayout.CENTER);
frame.add(panel,BorderLayout.CENTER);

Now, in your data update code, create the new model as your are and then call

table.setModel(model);

This should be faster to update, but more importantly, takes less memory to accomplish.

As for the date format. You have two choices. You can either format the value as it comes out if the database OR you can supply you own cell renderer.

public class SQLDateTableCellRenderer extends DefauktTableCellRenderer {

    public Component getTableCellRendererComponent(JTable table,
                                           Object value,
                                           boolean isSelected,
                                           boolean hasFocus,
                                           int row,
                                           int column) {
        if (value instanceof java.sql.Date) {
            value = new SimpleDateFormat("dd/MM/yyyy").format(value);
        }

        retrun super.getTableCellRenderer(...);
    }

}

Forgive the short hand, I'm on my iPad. It would be better to use a static or class reference to the date format, but that would require meto type more ;)

You could then set this as the default renderer on the JTable. This saves you the need to know which columns need a SQL date formatted.

table.setDefaultRenderer(java.sql.Date, new SQLDateTableCellRenderer());

This, of course, means tat rather then converting the objects to strings when you extract them from the database, you will simply want to extract the objects directly

tabledata[i]=rs.getObject(i+1); 

Make sure you convert the tabledata to a Object[] array instead of Strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM