2014-09-13 13 views
0

我不知道我怎麼會添加一個唯一的(改變一個簡化版,改變所有的人),行至JTableJButton我怎麼會擁有獨特的一鍵添加一行到一個JTable

final DefaultTableModel mod = new DefaultTableModel(); 
JTable t = new JTable(mod); 
mod.addColumn{"  "}; 
mod.addColumn{"  "}; 
JButton b = new JButton 
b.addActionListener(new ActionListener() { 
public void actionPerformed(ActionEvent e) { 
//How would I make tf unique by producing a different variable every row if changed 
final JTextField tf = new JTextField(); 
final Object[] ro = {"UNIQUE ROW", tf}; 
mode.addRow(ro); 
}): 
tf.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    //s change to an other variable every row added 
    String s = tf.getText(); 
}): 
+2

如果這是我的問題,我在這裏尋求幫助,我需要一點時間來創建和發佈[小例子程序(http://stackoverflow.com/help/mcve ),因爲我知道這將是讓人們完全理解我的問題然後幫助我的最好和最快捷的方式。 – 2014-09-13 02:25:19

+1

此外,您似乎試圖將JTextField組件添加到表模型的行,並且我不認爲您真的想這樣做,因爲JTable不會顯示組件本身的「副本」,而是顯示組件。雖然每行的同一列可能共享相同的「渲染」組件,但顯示的內容不同,因爲模型的數據不同。更好地爲你更全面地描述你想要達到的目標,是的,創建併發布你的[mcve](http://stackoverflow.com/help/mcve)。 – 2014-09-13 02:30:28

回答

4

您似乎很接近,但您不想將JTextField添加到表格行。而是添加它所保存的數據。例如:

import java.awt.event.ActionEvent; 
import javax.swing.*; 
import javax.swing.table.DefaultTableModel; 

public class UniqueRow extends JPanel { 
    public static final String[] COLS = {"Col 1", "Col 2"}; 
    private DefaultTableModel model = new DefaultTableModel(COLS, 0); 
    private JTable table = new JTable(model); 
    private JTextField textField1 = new JTextField(10); 
    private JTextField textField2 = new JTextField(10); 

    public UniqueRow() { 
     add(new JScrollPane(table)); 
     add(textField1); 
     add(textField2); 
     ButtonAction action = new ButtonAction("Add Data"); 
     textField1.addActionListener(action); 
     textField2.addActionListener(action); 
     add(new JButton(action)); 
    } 

    private class ButtonAction extends AbstractAction { 
     public ButtonAction(String name) { 
     super(name); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 

     // get text from JTextField 
     String text1 = textField1.getText(); 
     String text2 = textField2.getText(); 

     // create a data row with it. Can use Vector if desired 
     Object[] row = {text1, text2}; 

     // and add row to JTable 
     model.addRow(row); 
     } 
    } 

    private static void createAndShowGui() { 
     UniqueRow mainPanel = new UniqueRow(); 

     JFrame frame = new JFrame("UniqueRow"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 
相關問題