使用从另一个类创建的值创建JTable

时间:2015-04-08 08:34:29

标签: java swing jtable

在我解释我的问题之前,我想展示我的代码:

GUInterface.java

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class GUInterface {

    private JFrame frame;
    private JTextField fieldStudentsGroup, fieldStudentsTotal;
    private JButton btnGenerateGroup;
    private JLabel labelStudentsTotal, labelStudentsGroup;
    private int valueStudentsGroup, valueStudentsTotal;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUInterface window = new GUInterface();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public GUInterface() {
        initialize();       
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        /* GUI */
        frame = new JFrame();
        frame.setTitle("Group Randomizer");
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(0, 1, 0, 0));

        /*  Students per Group  */
        labelStudentsGroup = new JLabel("Students in a Group");
        frame.getContentPane().add(labelStudentsGroup);

        fieldStudentsGroup = new JTextField();
        frame.getContentPane().add(fieldStudentsGroup);
        fieldStudentsGroup.setColumns(10);

        /*  Total Number of Students  */
        labelStudentsTotal = new JLabel("Number of Students");
        frame.getContentPane().add(labelStudentsTotal);

        fieldStudentsTotal = new JTextField();
        frame.getContentPane().add(fieldStudentsTotal);
        fieldStudentsTotal.setColumns(10);

        /*  Action Listener  */
        thehandler handler = new thehandler();
        fieldStudentsTotal.addActionListener(handler);
        fieldStudentsGroup.addActionListener(handler);

        btnGenerateGroup = new JButton("Generate Group");
        frame.getContentPane().add(btnGenerateGroup);
        btnGenerateGroup.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //System.out.println(getValueStudentsTotal());
                //System.out.println(getValueStudentsGroup());

                GroupGenerator gg = new GroupGenerator();
                gg.setStudents(getValueStudentsTotal());
                gg.setStudentsGroup(getValueStudentsGroup());
                gg.generateGroup();
            }
        });
    }

    private class thehandler implements ActionListener{
        public void actionPerformed(ActionEvent event) {
            String string = "";

            if(event.getSource() == fieldStudentsTotal) {
                setValueStudentsTotal(Integer.parseInt(fieldStudentsTotal.getText()));
                string = String.format("Students: %s", getValueStudentsTotal());
                labelStudentsTotal.setText(string);
                //System.out.println(getValueStudentsTotal());
            }
            else if(event.getSource() == fieldStudentsGroup) {
                setValueStudentsGroup(Integer.parseInt(fieldStudentsGroup.getText()));
                string = String.format("Students in a Group: %s", getValueStudentsGroup());
                labelStudentsGroup.setText(string);
                //System.out.println(getValueStudentsGroup());
            }
        }
    }

    public int getValueStudentsGroup() {
        return valueStudentsGroup;
    }
    private void setValueStudentsGroup(int valueStudentsGroup) {
        this.valueStudentsGroup = valueStudentsGroup;
    }
    public int getValueStudentsTotal() {
        return valueStudentsTotal;
    }
    private void setValueStudentsTotal(int valueStudentsTotal) {
        this.valueStudentsTotal = valueStudentsTotal;
    }

}

GroupGenerator.java

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;

public class GroupGenerator {
    private int students, studentsGroup, row, col;
    private int[] numbers, solutionArray;
    private Object[][] results, data;

    public void generateGroup() {

        numbers = new int[students];
        for(int i = 0; i < students; i++) {
            numbers[i] = i + 1;
        }

        solutionArray = new int[students+1];
        solutionArray = numbers;//convertIntegers(solutionList);

        results = new Integer[solutionArray.length][studentsGroup];

        shuffleArray(solutionArray);

        // Testing if the array works
        for (int row = 0, x = 0; x < solutionArray.length; row++) {
            for (int col = 0; col < studentsGroup; col++, x++) {
                System.out.print(" " + solutionArray[x] + " ");
                results[row][col] = solutionArray[x];
            }
            System.out.print("\n");
        }
        // EDIT: added code
    /*  MyTableModel tm = new MyTableModel();
        tm.setCol(col);
        tm.setRow(row);
        tm.setData(results);

        GroupResults gr = new GroupResults();
        gr.start();
        gr.setCol(getCol());
        gr.setRow(getRow());
        gr.setData(getResults());*/
    }

    public void setStudents(int students) {
        this.students = students;
    }
    public void setStudentsGroup(int studentsGroup) {
        this.studentsGroup = studentsGroup;
    }

    // Implementing Fisher–Yates shuffle
    private static void shuffleArray(int[] ar) {
        Random rnd = new Random();
        for (int i = ar.length - 1; i > 0; i--) {
            int index = rnd.nextInt(i + 1);
            // Simple swap
            int a = ar[index];
            ar[index] = ar[i];
            ar[i] = a;
        }
    }

    public static int[] convertIntegers(List<Integer> integers) {
        int[] ret = new int[integers.size()];
        for (int i=0; i < ret.length; i++) {
            ret[i] = integers.get(i).intValue();
        }
        return ret;
    }
}

正如您所看到的,我正在尝试创建一个群组随机数发生器。这是给我在学校的老师。问题是,应用程序仅在控制台中工作(如果导出,命令提示符/终端)。

我的计划是制作一个JTable并将其显示在一个单独的窗口中。我已将值数组转换为多维数组(对于我在其他帖子中的混淆感到抱歉)。现在我所要做的就是将值显示为JTable中的GUI。但是,每当我尝试时,表格都会显示为空白。我试图使用AbstractTableModel,但它永远不会起作用(主要是由于混乱)。有人可以帮我吗?提前谢谢!

编辑: 我添加了用于设置上面JTable值的代码。 这是我尝试制作JTable:

GroupResults.java

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

public class GroupResults extends JDialog {

    private final JPanel contentPanel = new JPanel();
    private Object[][] data;
    private int col, row;
    private JTable table;

    public void start() {
        try {

            String[] title = {"hi"};
            //System.out.println(data[0][0]);
            //table = new JTable(data, title);
            //getContentPane().add(table, BorderLayout.CENTER);

            GroupResults dialog = new GroupResults();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);

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

    public GroupResults() {
        MyTableModel tm = new MyTableModel();

        setBounds(100, 100, 450, 300);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setLayout(new FlowLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);

        /*  Bottom Layer  */
        {
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            getContentPane().add(buttonPane, BorderLayout.SOUTH);
            {
                JButton okButton = new JButton("OK");
                okButton.setActionCommand("OK");
                okButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {
                        //showTable();
                        dispose();
                    }
                });
                buttonPane.add(okButton);
                getRootPane().setDefaultButton(okButton);
            }
        }

        table = new JTable(tm);
        getContentPane().add(table, BorderLayout.CENTER);
    }


    // Another attempt
/*  public void showTable() {
        if(data != null) {
            String[] title = {"hi"};

            //MyTableModel tm = new MyTableModel();
            table = new JTable(data, title);
            //table.setTableHeader(null);
            //table.setFillsViewportHeight(true);
            JScrollPane pane = new JScrollPane(table);
            pane.add(table);
            contentPanel.add(panetable, BorderLayout.CENTER);

            contentPanel.revalidate();
            contentPanel.repaint();
        }
    }*/

    /*  Setters  */
    public void setData(Object[][] data) {
        this.data = data;
    }
    public void setCol(int col) {
        this.col = col;
    }
    public void setRow(int row) {
        this.row = row;
    }

}

MyTableModel.java(我尝试过以下教程)

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

public class MyTableModel extends AbstractTableModel implements TableModelListener{
    private int col, row;
    private Object[][] data;

    GroupGenerator gg = new GroupGenerator();

    /*   Number of Columns   */
    @Override
    public int getColumnCount() {
        System.out.println("TM " + getCol());
        System.out.println(data[0][0]);
        return getCol();
    }

    /*   Number of Rows   */
    @Override
    public int getRowCount() {
        System.out.println("TM " + getRow());
        return getRow();
    }

    /*   Getting Values   */
    @Override
    public Object getValueAt(int row, int col) {
        return data[row][col];
    }



    /*   Setting Values  */
/*  public void setValueAt(Object value, int row, int col) {
        if(true) {
            // Set title "Group"
        }
        data[row][col] = value;
        fireTableCellUpdated(row, col);
    }*/

    /*   Editable/Uneditable Table   */
    public boolean isCellEditable(int row, int col) {
        return false;
    }


    public void refreshTable() {
        fireTableDataChanged();
    }

    public void setCol(int col) {
        this.col = col;
        System.out.println("TM Col " + getCol());
    }
    public int getCol() {
        return col;
    }

    public void setData(Object[][] data) {
        this.data = data;
        System.out.println(data[0][0]);
    }
    public Object[][] getData() {
        return data;
    }

    public void setRow(int row) {
        this.row = row;
        System.out.println("TM Row " + getRow());
    }
    public int getRow() {
        return row;
    }

/*  @Override
    public void tableChanged(TableModelEvent e) {
        row = e.getFirstRow();
        col = e.getColumn();
        TableModel model = (TableModel)e.getSource();

        fireTableDataChanged();

    }*/

    @Override
    public void tableChanged(TableModelEvent arg0) {
        fireTableStructureChanged();
    }
    @Override
    public void setValueAt(Object value, int a, int b) {
        data[a][b] = value;
        fireTableCellUpdated(a,b);
    }

}

0 个答案:

没有答案