1

我有一个有 2 列的 JTable,这个 JTable 有 N 行(其中 N 取决于其他任务)并在每个单元格中显示之前设置一个默认值。对于每一行,都有一个 String 和一个 int 值。

我需要这个表,当我点击OK按钮时,发送所有单元格数据(在这些由用户编辑之后)作为对象与链接列表中的 2 个数据(行 x 列 x)耦合。(对象构造函数JOB接收一个String和一个int尚未完成。)

我该如何编码???

这是使用我的 JTable 和 2 个按钮(确定和取消)生成窗口的代码:

    /**
     * Create the frame.
     */
    public InsertJobWindows() {
        setTitle("Welcome");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 551, 293);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JPanel panel_1 = new JPanel();

        JButton btnNewButton = new JButton("    OK   ");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        panel_1.add(btnNewButton);

        JButton btnNewButton_1 = new JButton("Cancel");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                InsertJobWindows.this.dispose();
            }
        });

        JPanel panel = new JPanel();

        final JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
        table.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent event) {
                        int viewRow = table.getSelectedRow();
                        JLabel statusText=new JLabel();
                        if (viewRow < 0) {
                            //Selection got filtered away.
                            statusText.setText("");
                        } else {
                            int modelRow = 
                                table.convertRowIndexToModel(viewRow);
                            statusText.setText(
                                String.format("Selected Row in view: %d. " +
                                    "Selected Row in model: %d.", 
                                    viewRow, modelRow));
                        }
                    }
                }
        );


                //Create the scroll pane and add the table to it.
                JScrollPane scrollPane = new JScrollPane(table);

                        //Set up column sizes.
                        initColumnSizes(table);

        panel_1.add(btnNewButton_1);
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING, false)
                        .addComponent(panel_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(panel, GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE))
                    .addContainerGap())
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(panel, GroupLayout.PREFERRED_SIZE, 213, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED, 61, Short.MAX_VALUE)
                    .addComponent(panel_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );
        GroupLayout gl_panel = new GroupLayout(panel);
        gl_panel.setHorizontalGroup(
            gl_panel.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel.createSequentialGroup()
                    .addGap(11)
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(12, Short.MAX_VALUE))
        );
        gl_panel.setVerticalGroup(
            gl_panel.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel.createSequentialGroup()
                    .addGap(5)
                    .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE)
                    .addContainerGap())
        );
        panel.setLayout(gl_panel);
        contentPane.setLayout(gl_contentPane);



    }

    private void initColumnSizes(JTable table) {
        MyTableModel model = (MyTableModel)table.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        Object[] longValues = model.longValues;
        TableCellRenderer headerRenderer =
            table.getTableHeader().getDefaultRenderer();

        for (int i = 0; i < 2; i++) {
            column = table.getColumnModel().getColumn(i);

            comp = headerRenderer.getTableCellRendererComponent(
                                 null, column.getHeaderValue(),
                                 false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;

            comp = table.getDefaultRenderer(model.getColumnClass(i)).
                             getTableCellRendererComponent(
                                 table, longValues[i],
                                 false, false, 0, i);
            cellWidth = comp.getPreferredSize().width;

            if (DEBUG) {
                System.out.println("Initializing width of column "
                                   + i + ". "
                                   + "headerWidth = " + headerWidth
                                   + "; cellWidth = " + cellWidth);
            }

            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }


    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"JobName", "time"};
        int numJobs=JobManager.loadNumJob();
        private Object[][] data = getDefaultTableData();

        public Object[][] getDefaultTableData(){
            Object[][] tabella=new Object[numJobs][2];
            for(int i=0; i<numJobs; i++){
                for(int j=0; j<2; j++){
                    tabella[i][j]="insert the correct data";
                }
            }

            return tabella;
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return numJobs;
        }

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

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        public boolean isCellEditable(int row, int col) {
            return true;
        }

        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                                   + " to " + value
                                   + " (an instance of "
                                   + value.getClass() + ")");
            }

            data[row][col] = value;
            fireTableCellUpdated(row, col);

            if (DEBUG) {
                System.out.println("New value of data:");
                printDebugData();
            }
        }


        public void run() {
            try {
                InsertJobWindows frame = new InsertJobWindows();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
}
4

1 回答 1

1

更改您的表格模型以保存一个LinkedList(或更简单地说,一个List)您的工作。

有点像这样:

public class Job {
    public int time; // Should n't this be a long?
    public String jobName;
}

class MyTableModel extends AbstractTableModel {
    private String[] columnNames = {"JobName", "time"};
    int numJobs=JobManager.loadNumJob();
    private List<Job> data = getDefaultTableData();

    public List<Job> getDefaultTableData(){
        List<Job> jobs = new LinkedList<Job>();
        for(int i=0; i<numJobs; i++) {
            Job job = new Job();
            job.time = /* Some int value */ 0;
            job.jobName= /* Some string value */ "";
            jobs.add(job);
        }

        return jobs;
    }

    public int getColumnCount() {
        return columnNames.length;
    }

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

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

    public Object getValueAt(int row, int col) {
        if (col==0) {
            return data.get(row).jobName;
        } else if (col==1) {
            return data.get(row).time;
        }
        return null;
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

    public boolean isCellEditable(int row, int col) {
        return true;
    }

    public void setValueAt(Object value, int row, int col) {
        if (DEBUG) {
            System.out.println("Setting value at " + row + "," + col
                               + " to " + value
                               + " (an instance of "
                               + value.getClass() + ")");
        }

        if (col==0) {
            data.get(row).jobName = value; // Here do the casts and necessary checks.
        } else if (col==1) {
            data.get(row).time= value; // Here do the casts and necessary checks.
        }
        fireTableCellUpdated(row, col);

        if (DEBUG) {
            System.out.println("New value of data:");
            printDebugData();
        }
    }
于 2012-04-08T14:51:13.003 回答