如何将一个唯一的按钮添加到JTable中

时间:2014-09-13 02:21:47

标签: java swing jtable defaulttablemodel

我想知道如何将JTable

添加到JButton的唯一(更改后的所有内容)
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();
 }):

1 个答案:

答案 0 :(得分: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();
         }
      });
   }
}