2012-10-15 117 views
0

我想在用戶提供輸入後顯示錶。我無法弄清楚爲什麼表格不顯示。Java Applet表在運行時不顯示

我創造了我的表作爲以創建一個表,我可以添加到描述here (Stack Overflow)here (Rose India)

,但我的代碼不會將表添加到小程序,特別是在這裏:

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

休息的代碼,充分貼合here (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.. 
} 

回答

1

您需要在添加後驗證容器組件:

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

而且它不是一個好主意,有你的paint方法內部數據庫調用。例如,當小程序重新獲得焦點或調整大小時,將會多次調用paint。一個建議是將數據庫調用提取出來放入一個單獨的方法並添加一個「重新加載」按鈕。