如何通过JButton将数据从一个类添加到另一个类'JTable?

时间:2015-01-27 04:39:34

标签: java swing arraylist jtable tablemodel

我要做的是使用array / arraylist存储来自用户的输入数据,然后将其显示在JTable上。我有两个不同的Jtable对话框/类和另一个用户输入对话框,所以当他们单击JButtonAdd时,它会自动显示另一个对话框/类上的JTbale上的数据。我对如何做到完全无能为力。这是我到目前为止的代码。

**MAIN Program**



import java.awt.EventQueue;

import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class StartProgram extends JDialog {
	private JTable tableInfo;

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

	/**
	 * Create the dialog.
	 */
	@SuppressWarnings("serial")
	public StartProgram() {
		getContentPane().setBackground(new Color(153, 255, 153));
		setBounds(100, 100, 550, 500);
		getContentPane().setLayout(null);
		
		JButton btnDelete = new JButton("Delete");
		btnDelete.setBounds(379, 11, 145, 23);
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				JOptionPane.showConfirmDialog(null, "Are you sure you want to delete?");
			}
		});

		getContentPane().add(btnDelete);
		
		JButton btnAddQueueNumber = new JButton("Add Queue Number");
		btnAddQueueNumber.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				AddQueueNumber dialog = new AddQueueNumber();
				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
				dialog.setVisible(true);
			}
		});
		btnAddQueueNumber.setBounds(10, 11, 145, 23);
		getContentPane().add(btnAddQueueNumber);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 45, 514, 405);
		getContentPane().add(scrollPane);
		
		tableInfo = new JTable();
		tableInfo.setShowGrid(false);
		scrollPane.setViewportView(tableInfo);
		tableInfo.setModel(new DefaultTableModel(
			new Object[][] {
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
				{null, null, null, null, null},
			},
			new String[] {
				"Queue Number", "Name", "Interviewer", "Time", "Room"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		
		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Search dialog = new Search();
				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
				dialog.setVisible(true);
			}
		});
		btnSearch.setBounds(164, 11, 145, 23);
		getContentPane().add(btnSearch);

	}
}

AddQueueNumber Class

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;

import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class AddQueueNumber extends JDialog {

    private final JPanel contentPanel = new JPanel();
    private JTextField tfQueueNumber;
    private JTextField tfName;
    private JTextField tfInterviewer;
    private JTextField tfTime;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            AddQueueNumber dialog = new AddQueueNumber();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create the dialog.
     */
    public AddQueueNumber() {
        setBounds(100, 100, 270, 235);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setBackground(new Color(255, 255, 255));
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(null);

        JLabel lblQueueNumber = new JLabel("Queue Number");
        lblQueueNumber.setBounds(10, 11, 93, 14);
        contentPanel.add(lblQueueNumber);

        tfQueueNumber = new JTextField();
        tfQueueNumber.setBounds(98, 8, 146, 20);
        contentPanel.add(tfQueueNumber);
        tfQueueNumber.setColumns(10);

        tfName = new JTextField();
        tfName.setBounds(98, 39, 146, 20);
        contentPanel.add(tfName);
        tfName.setColumns(10);

        JLabel lblName = new JLabel("Name");
        lblName.setBounds(10, 42, 78, 14);
        contentPanel.add(lblName);

        tfInterviewer = new JTextField();
        tfInterviewer.setBounds(98, 70, 146, 20);
        contentPanel.add(tfInterviewer);
        tfInterviewer.setColumns(10);

        JLabel lblInterviewer = new JLabel("Interviewer");
        lblInterviewer.setBounds(10, 73, 78, 14);
        contentPanel.add(lblInterviewer);

        tfTime = new JTextField();
        tfTime.setBounds(98, 101, 146, 20);
        contentPanel.add(tfTime);
        tfTime.setColumns(10);

        JLabel lblTime = new JLabel("Time");
        lblTime.setBounds(10, 104, 78, 14);
        contentPanel.add(lblTime);

        JComboBox cbRoom = new JComboBox();
        cbRoom.setModel(new DefaultComboBoxModel(new String[] {" ", "Circle Room", "Square Room", "Triangle Room", "Pentagon Room", "Rectangle Room"}));
        cbRoom.setBounds(98, 132, 146, 20);
        contentPanel.add(cbRoom);

        JLabel lblRoom = new JLabel("Room");
        lblRoom.setBounds(10, 135, 78, 14);
        contentPanel.add(lblRoom);
        {
            JPanel buttonPane = new JPanel();
            buttonPane.setBackground(new Color(255, 255, 255));
            buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            getContentPane().add(buttonPane, BorderLayout.SOUTH);
            {
                JButton okButton = new JButton("OK");
                okButton.addMouseListener(new MouseListener() {

                    @Override
                    public void mouseReleased(MouseEvent e) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void mousePressed(MouseEvent e) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void mouseExited(MouseEvent e) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void mouseEntered(MouseEvent e) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void mouseClicked(MouseEvent e) {
                        //This is where the data will be saved on the JTable
                        JTable tableInfo = new JTable();
                        DefaultTableModel model = (DefaultTableModel) tableInfo.getModel();
                        if (!tfQueueNumber.getText().trim().equals ("")){
                        model.addRow(new Object[]{ tfQueueNumber.getText(), tfName.getText(),tfInterviewer.getText(), cbRoom.getSelectedItem().toString(),tfTime.getText() });
                        } else {
                            JOptionPane.showMessageDialog(null, "Queue number should not be blank!");
                        }
                    }
                });
                okButton.setActionCommand("Add");
                buttonPane.add(okButton);
                getRootPane().setDefaultButton(okButton);

            }
            {
                JButton cancelButton = new JButton("Cancel");
                cancelButton.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent arg0) {
                        dispose();
                    }
                });
                cancelButton.setActionCommand("Cancel");
                buttonPane.add(cancelButton);
            }
        }



    }
}

1 个答案:

答案 0 :(得分:2)

首先定义一个普通的旧Java对象(PO​​JO),它描述了你想要捕获的数据......

public class Interview {

    private int queueNumber;
    private String name;
    private String interviewer;
    private Date time;
    private String room;

    public Interview(int queueNumber, String name, String interviewer, Date time, String room) {
        this.queueNumber = queueNumber;
        this.name = name;
        this.interviewer = interviewer;
        this.time = time;
        this.room = room;
    }

    public String getInterviewer() {
        return interviewer;
    }

    public String getName() {
        return name;
    }

    public int getQueueNumber() {
        return queueNumber;
    }

    public String getRoom() {
        return room;
    }

    public Date getTime() {
        return time;
    }

    public void setQueueNumber(int queueNumber) {
        this.queueNumber = queueNumber;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setInterviewer(String interviewer) {
        this.interviewer = interviewer;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public void setRoom(String room) {
        this.room = room;
    }



}

这将允许您将数据封装到易于管理的容器中。我个人更喜欢使用interface,因为它可以让我更好地控制要公开的内容和提供的功能,但我们会在这里保持简单......

创建一个JPanel,可以充当面试详情的编辑......

public class InterviewPane extends JPanel {

    private JSpinner queueNumber;
    private JTextField name;
    private JTextField interviewer;
    private JSpinner time;
    private JComboBox room;

    private Interview interview;

    public InterviewPane(Interview interview) {
        this();
        this.interview = interview;
        if (interview != null) {
            queueNumber.setValue(interview.getQueueNumber());
            time.setValue(interview.getTime());
            name.setText(interview.getName());
            interviewer.setText(interview.getInterviewer());
            room.setSelectedItem(interview.getRoom());
        }
    }

    public InterviewPane() {
        queueNumber = new JSpinner();
        time = new JSpinner();
        SpinnerDateModel sm = new SpinnerDateModel(new Date(), null, null, Calendar.MINUTE);
        time = new JSpinner(sm);
        JSpinner.DateEditor de = new JSpinner.DateEditor(time, "hh:mm a");
        name = new JTextField(10);
        interviewer = new JTextField(10);
        room = new JComboBox();
        room.setModel(new DefaultComboBoxModel(new String[]{" ", "Circle Room", "Square Room", "Triangle Room", "Pentagon Room", "Rectangle Room"}));

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        add(new JLabel("Queue Number: "), gbc);
        gbc.gridy++;
        add(new JLabel("Name: "), gbc);
        gbc.gridy++;
        add(new JLabel("Interviewer: "), gbc);
        gbc.gridy++;
        add(new JLabel("Time: "), gbc);
        gbc.gridy++;
        add(new JLabel("Room: "), gbc);

        gbc.gridx++;
        gbc.gridy = 0;
        add(queueNumber, gbc);
        gbc.gridy++;
        add(name, gbc);
        gbc.gridy++;
        add(interviewer, gbc);
        gbc.gridy++;
        add(time, gbc);
        gbc.gridy++;
        add(room, gbc);
    }

    public Interview getInterview() {

        Interview result = interview;

        if (result == null) {
            result = new Interview(
                        (Integer)queueNumber.getValue(), 
                        name.getText(), 
                        interviewer.getText(), 
                        (Date)time.getValue(), 
                        (String)room.getSelectedItem());

        } else {

            interview.setInterviewer(interviewer.getText());
            interview.setName(name.getText());
            interview.setTime((Date) time.getValue());
            interview.setRoom((String) room.getSelectedItem());
            interview.setQueueNumber((int) queueNumber.getValue());

        }

        return result;

    }

}

这使您能够决定何时何地使用编辑器窗格,作为一般做法,您应该避免直接从顶级容器(例如JDialog

)扩展

现在,当您想要显示编辑器时,您可以使用类似......

的内容
InterviewPane editor = new InterviewPane();
switch (JOptionPane.showConfirmationDialog(this, editor, "Details", JOptionPane.OK_CANCEL_OPTION)) {
    case JOptionPane.OK_OPTION:
        Interview interview = editor.getInterview();
        break;
}

这将允许您根据用户响应从编辑器中获取详细信息。

注意,您可能希望使用AbstractTableModel代替DefaultTableModel,因为它更容易管理POJO

看看:

了解更多详情。

你应该避免使用null布局,像素完美布局是现代ui设计中的错觉。影响组件个体大小的因素太多,您无法控制。 Swing旨在与布局管理器一起工作,放弃这些将导致问题和问题的终结,您将花费越来越多的时间来纠正

<强>更新

Swing使用Model-View-Controller范例的版本。这意味着UI(视图)和数据(模型)之间存在分离。

这意味着,当您想要更改屏幕上的内容时,您只需要更改模型而不是整个UI。

例如,在这种情况下,我会使用AbstractTableModel基于我的TableModel并提供我需要的功能(例如添加/删除Interview个对象的功能)。这样可以保持Interview完整无缺,并且通常可以更轻松地进行管理

public class InterviewTableModel extends AbstractTableModel {

    protected static final String[] COLUMN_NAMES = {
        "Queue Number", "Name", "Interviewer", "Time", "Room"
    };

    protected static final Class[] COLUMN_TYPES = new Class[]{
        Integer.class, String.class, String.class, Date.class, String.class
    };

    private List<Interview> rows;

    public InterviewTableModel() {
        rows = new ArrayList<>(25);
    }

    public void addInterview(Interview interview) {
        rows.add(interview);
        int rowIndex = rows.size() - 1;
        fireTableRowsInserted(rowIndex, rowIndex);
    }

    public void removeInterview(Interview interview) {
        if (rows.contains(interview)) {
            int rowIndex = rows.indexOf(interview);
            rows.add(interview);
            fireTableRowsInserted(rowIndex, rowIndex);
        }
    }

    @Override
    public String getColumnName(int column) {
        return COLUMN_NAMES[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return COLUMN_TYPES[columnIndex];
    }

    @Override
    public int getRowCount() {
        return rows.size();
    }

    @Override
    public int getColumnCount() {
        return COLUMN_NAMES.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Interview interview = rows.get(rowIndex);
        Object value = null;
        switch (columnIndex) {
            case 0:
                value = interview.getQueueNumber();
                break;
            case 1:
                value = interview.getName();
                break;
            case 2:
                value = interview.getInterviewer();
                break;
            case 3:
                value = interview.getTime();
                break;
            case 4:
                value = interview.getRoom();
                break;
        }
        return value;
    }

}

首先,您需要更改tableInfo初始化的方式,不再需要DefaultTableModel,而是使用更像...... {/ p >

tableInfo.setModel(new InterviewTableModel());

如果要向模型中添加新的Interview,可以使用类似......

的内容
InterviewPane editor = new InterviewPane();
switch (JOptionPane.showConfirmationDialog(this, editor, "Details", JOptionPane.OK_CANCEL_OPTION)) {
    case JOptionPane.OK_OPTION:
        Interview interview = editor.getInterview();
        InterviewTableModel model = (InterviewTableModel)tableInfo.getModel();
        model.addInterview(interview);
        break;
}

例如......