繁体   English   中英

我如何有一个唯一的按钮向JTable添加一行

[英]How Would I have a button unique add a row to a JTable

我想知道如何将唯一的(更改一个不会改变所有的)行添加到带有JButtonJTable

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();
 }):

您似乎很近,但是您不想将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();
         }
      });
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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