0

我想在用户提供输入后显示一个表格。我无法弄清楚为什么表格不会显示。

我按照此处(Stack Overflow)此处(Rose India)的描述创建了我的表,以便创建一个可以添加到的表,

但我的代码没有将表添加到小程序中,特别是在这里:

aTable = new MDTable(mdList);
add( aTable );

其余代码,在这里完整粘贴(Pastebin)

public class FMCSAApplet extends Applet implements ActionListener {

String zipcode;

Label lab1;
TextField t1;
Button submitButton;
MDTable aTable;

public void init()
{
    setLayout(new FlowLayout()); 
    submitButton = new Button("Submit"); 
    lab1 = new Label("Enter a zipcode:");
    t1 = new TextField(15);

    add(lab1);
    add(t1);
    add(submitButton);
    submitButton.addActionListener(this); 
}

public void paint(Graphics g)
{
    g.drawString("Zip code: "+zipcode,30,100);
    if(zipcode!=null) {
        g.drawString("dotNum\t inputZip\t name\t\t city\t state\t mileage\t unsafe\t fatigued\t fitness\t substance\t maintenance\t inspections",30,120);
        try {
            ..Code Stripped..
                            // get info from database, add to ArayList<MData> mdList
                                    ..Code Stripped..
                                    mdList.add(motorcoach);
                }
            } // end while
            rs.close();

            aTable = new MDTable(mdList);
            add( aTable );

        }catch (Exception f) {
            System.out.println(f);
        }
    }
}

public void actionPerformed(ActionEvent evt) 
{
    // Here we will ask what component called this method
     if (evt.getSource() == submitButton) {
         zipcode = t1.getText();
         repaint();
     }
}

public boolean action(Event e,Object o)
{
    zipcode = t1.getText();
    repaint();
    return true;
}

} //end FMCSAApplet Class

class MDTable extends JPanel {
    public MDTable(ArrayList<MData> md) {
        Object[][] cellData = {
            {1,2,"3","4","5",6,7,8,9,10,11,12}     
        };

        String[] columnNames = {"dotNum","inputZip", "name","city","state","mileage","unsafe","fatigued","fitness","substance","maintenance","inspections"};
        add(  new JTable(cellData, columnNames) ) ;
        DefaultTableModel model = new DefaultTableModel(cellData,columnNames);
        JTable table = new JTable(model);
        for (MData md1 : md) {
            model.insertRow(table.getRowCount(),new Object[]{md1.getDotNum(), md1.getInputZip(), md1.getName(), md1.getCity(), md1.getState(), md1.getMileage(), md1.getUnsafe(), md1.getFatigued(), md1.getFitness(), md1.getSubstance(), md1.getMaintenance(), md1.getInspections()});
        }
    } //end MDTable Constructor
} //end MDTable Class

class MData {
        ..Code Stripped..
        public MData(int d, int i, String n, String c, String s, int m, int u, int f, int fi, int su, int ma, int in)
        ..Code Stripped..
}
4

1 回答 1

1

添加组件后,您需要验证容器MDTable

add( aTable );
validate();
...

在您的paint方法中进行数据库调用也不是一个好主意。paint例如,当小程序重新获得焦点或调整大小时,将被多次调用。一个建议是将数据库调用提取到一个单独的方法中并添加一个“重新加载”按钮。

于 2012-10-15T18:38:02.243 回答