簡體   English   中英

Java AbstractTableModel中“添加”按鈕的用法

[英]Usage of “Add” button in Java AbstractTableModel

我試圖在我的AbstractTableModel中添加一個“添加”按鈕。 然后,它將彈出一個表單,供用戶輸入計算機的IP地址並單擊“添加”。 我只是停留在如何動態地向表中添加新行(單元格)的部分。 我在這里找到了一些示例,但在我的情況下,所有這些示例都沒有幫助我。

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException;


public class CampaignConfiguration extends JFrame {

    //private static final long serialVersionUID1 = 1L;
    private JPanel contentPane1;
    private JLabel lblTestsuiteName;
    public static  JTextField testSuiteTexField;
    public static JTextArea computerTextArea;
    public static String[] computerListArray;
    public static String testSuiteName;
    private JTextField txtHours;
    private JTextField txtMin;
    private JLabel label;
    private static JTable table;
    private static JButton btnUnmap, btnSave, btnClose, btnAdd;
    public static ArrayList<String> computerTextArray = new ArrayList<String>();
    final MyTableModel tableData;

    private JPanel contentPane;
    private boolean debug = true,  // Prints out debug messages
                     booleanValue;   // Used to convert String[] execute to a boolean value
    XMLparser xml = new XMLparser(Constants.TMP_DIR + Constants.COMPUTER_LIST_TEMP_FILE, Constants.XML_ROOT_TAG, Constants.XML_PARENT_TAG);
    public ArrayList<String> parameters_1 = new ArrayList<String>(),    
                             parameters_2 = new ArrayList<String>(), 
                             parameters_3 = new ArrayList<String>(), 
                             parameters_4 = new ArrayList<String>(), 
                             parameters_5 = new ArrayList<String>();

    private SaveToXml save = new SaveToXml();
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args){
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    final CampaignConfiguration frame = new CampaignConfiguration();
                    frame.setVisible(true);
                    frame.validate();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void ActionOnClose(){
        addWindowListener(
                  new java.awt.event.WindowAdapter()
                  {
                    public void windowClosing( java.awt.event.WindowEvent e )
                    {
                      try {
                        Main.Refresh();
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    }
                  }
                );
    }

    /**
     * Create the frame.
     */
    public CampaignConfiguration() throws FileNotFoundException, ParserConfigurationException, SAXException, IOException{
        ActionOnClose();
        setTitle("Campaign Configuration");
        ArrayList<MyObject> list = new ArrayList<MyObject>();
        int listSize = NetworkMapping.usedDrives.size();
          for(int i = 0; i < listSize;i++){
            if(debug){
                System.out.println("---------------------------------------------");
                System.out.println("pc_ip_address [" + i + "] = '" + NetworkMapping.usedDrives.get(i) + "'");
                System.out.println("---------------------------------------------");
                System.out.println("\n");
            }
            list.add(new MyObject(NetworkMapping.pc_ip_addresses.get(i)));
         }   

        // Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 87, 493, 263);
        TableColumn column = null;

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 529, 517);
        contentPane1 = new JPanel();
        contentPane1.setBorder(new EmptyBorder(50, 10, 10, 10));
        contentPane1.setLayout(null);
        contentPane1.add(scrollPane);
        setContentPane(contentPane1);

        // Add the scroll pane to this panel.
        getContentPane().add(scrollPane);
        tableData = new MyTableModel(list);
        table = new JTable(tableData);

        scrollPane.setViewportView(table);
        //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setRowHeight(25);
        table.setFillsViewportHeight(true);

        JLabel lblCampaignName = new JLabel("Campaign Name (Case Sensitive)");
        lblCampaignName.setBounds(10, 11, 218, 14);
        contentPane1.add(lblCampaignName);

        textField = new JTextField();
        textField.setBounds(10, 36, 86, 20);
        contentPane1.add(textField);
        textField.setColumns(10);

        btnSave = new JButton("Save");
        btnSave.setBounds(209, 361, 89, 23);
        contentPane1.add(btnSave);

        btnUnmap = new JButton("Disconnect Drives");
        btnUnmap.setBounds(177, 395, 154, 23);
        contentPane1.add(btnUnmap);

        btnClose = new JButton("Close");
        btnClose.setBounds(308, 361, 89, 23);
        contentPane1.add(btnClose);

        btnAdd = new JButton("Add");
        btnAdd.setBounds(108, 361, 89, 23);
        contentPane1.add(btnAdd);

        // Add actionlistener
        ButtonAction ba = new ButtonAction();
        btnClose.addActionListener(ba);
        btnSave.addActionListener(ba);
        btnUnmap.addActionListener(ba);
        btnAdd.addActionListener(ba);
    }
    class MyObject {
        String ip_address;
        int iterations;
        boolean isExecute;
        String parameter_1, 
               parameter_2,
               parameter_3,
               parameter_4;

        MyObject(String ip_address) {
             this.ip_address = ip_address;
        }
   }

class MyTableModel extends AbstractTableModel {
    Vector<String> textData = new Vector<String>();

    private static final long serialVersionUID = 1L;
    /**
     * 
     */
    //private static final long serialVersionUID = 1L;
    private String[] columnNames = { "Test Machine IP Address"};

    ArrayList<MyObject> list = null;

    MyTableModel(ArrayList<MyObject> list) {
         this.list = list;
    }

    public void addText(String text) {
        textData.addElement(text);
        fireTableDataChanged();
      }
    public int getColumnCount() {
         return columnNames.length;
    }

    public int getRowCount() {
         return list.size();
    }

    public String getColumnName(int col) {
         return columnNames[col];
    }

    public Object getValueAt(int row, int col) {

         MyObject object = list.get(row);

         switch (col) {
         case 0:
              return object.ip_address;
        /* case 1:
              return object.iterations;
         case 2:
              return object.isExecute;
         case 3:
             return object.parameter_1;
         case 4:
             return object.parameter_2;
         case 5:
             return object.parameter_3;
         case 6:
             return object.parameter_4;*/
         default:
              return "unknown";
         }
    }
    @Override
    public boolean isCellEditable(int row, int col) {
        return true;
    }

    @SuppressWarnings("unchecked")
      public Class getColumnClass(int c) {
         return getValueAt(0, c).getClass();
    }
    @Override
    public void setValueAt(Object value, int row, int col) {
        MyObject obj = list.get(row);
        if(col == 0){
            obj.ip_address = (String)value;
        } /*else if(col == 1){
            obj.iterations = (int)value;
        } else if (col == 2) {
            obj.isExecute = (Boolean)value;
        } else if (col == 3) {
            obj.parameter_1 = (String)value;
        }else if (col == 4) {
            obj.parameter_2 = (String)value;
        }else if (col == 5) {
            obj.parameter_3 = (String)value;
        }else if (col == 6) {
            obj.parameter_4 = (String)value;
        }*/
        fireTableCellUpdated(row, col);              
        try {
            SaveDataEntered(value, row, col);
        } catch (ParserConfigurationException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    // col = 0 / IP Address
    // col = 1 / 
    // col = 2 / 
    // col = 3 / 
    private void SaveDataEntered(Object value, int row, int col) throws ParserConfigurationException, IOException {
      MyObject obj = list.get(row);
      if(col == 0){
          System.out.println("ip address column");
          NetworkMapping.pc_ip_addresses.set(row, (String)value);
      } /*else if(col == 1){
          System.out.println("iterations column");
         // iterations[row] = Integer.toString((int)value);
      } else if(col == 2){
          System.out.println("execute column");
         // execute[row] = Boolean.toString((Boolean)value);
      } else if(col == 3){
          obj.parameter_1 = (String)value;                
          System.out.println("(String)value = " + (String)value);                 
         // parameters_1.set(row, (String)value);
      } else if(col == 4){
          obj.parameter_2 = (String)value;                
          System.out.println("(String)value = " + (String)value);                 
         // parameters_2.set(row, (String)value);
      }else if(col == 5){
          obj.parameter_3 = (String)value;                
          System.out.println("(String)value = " + (String)value);                 
         // parameters_3.set(row, (String)value);
      }else if(col == 6){
          obj.parameter_4 = (String)value;        
          System.out.println("(String)value = " + (String)value);                 
         // parameters_4.set(row, (String)value);
      }*/

          //save.WriteClaConfigFile(pc_ip_address, pc_ip_address, iterations, execute, parameters_1, parameters_2, parameters_3, parameters_4); 

      if(debug){
              System.out.println("    row " + row + ":");


    System.out.println("--------------------------");
                  System.out.println("pc_ip_address selection\t= '" + NetworkMapping.pc_ip_addresses.get(row)+ "'");
                  System.out.println("value\t\t\t= '" + value + "'");
                  System.out.println("row\t\t\t= '" + row + "'");
                  System.out.println("col\t\t\t= '" + col + "'");
                  System.out.println("--------------------------");
          }

        }
   }

}

忘記了我的按鈕操作:

class ButtonAction
        implements ActionListener{
        ButtonAction() {}

        public void actionPerformed(ActionEvent e){

          Object obj = e.getSource();
          if (obj == btnAdd){               // Add machine
              System.out.println("Should be adding");
              //tableData.addText("Test");  
              tableData.addRow("Test");
          } 
          } // Close if/else block
        } // Close actionPerformed

您正在將表模型中的getValueAt指向list ,但您的addText方法正在設置textData值。

在動作偵聽器和addText取消注釋tableData.addText("Test") ,將textData.addElement(text)更改為list.add(new MyObject(text))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM