2

选中时如何显示JTable一行的信息?

我将简要解释我正在尝试做什么,然后发布我创建的 SSCCE,以防我的任何解释令人困惑。

我希望能够单击表格中的任何行并在面板上显示该信息。我不确定我需要利用什么来完成工作。

我想我需要使用:

  • table.getSelectedRow()
  • MouseListener()
  • ListSelectionListener()

我以前没有使用过 Listeners,所以我只知道那些来自阅读文章/文档,同时研究我需要做什么才能完成工作。

对于如何在我的 JPanel 上显示信息,我也有些困惑。面板是在主类中创建的,而表是在其自己的类中创建的。

我感谢任何帮助和建议。

示例来源:

import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class SwingTesting {

    private final JFrame frame;
    private final TablePane tablePane;
    private final JSplitPane splitPane;
    private final JPanel infoPanel;

    public SwingTesting() {
        tablePane = new TablePane();
        infoPanel = new JPanel();
        frame = new JFrame();

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tablePane, infoPanel);

        frame.add(splitPane);
        frame.pack();
        frame.setVisible(true);
    }


    class TablePane extends JPanel {

        private final JTable table;
        private final TableModel tableModel;
        private final ListSelectionModel listSelectionModel;

    public TablePane() {
        table = new JTable();
        tableModel = createTableModel();
        table.setModel(tableModel);
        table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        table.add(table.getTableHeader(), BorderLayout.PAGE_START);
        table.setFillsViewportHeight(true); 

        listSelectionModel = table.getSelectionModel();
        table.setSelectionModel(listSelectionModel);
        listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
        table.setSelectionModel(listSelectionModel);

        this.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridheight = 1;
    gbc.gridwidth = 3;
    gbc.insets = new Insets(5, 5, 5, 5);
    gbc.ipadx = 2;
    gbc.ipady = 2;
    gbc.weightx = 1;
    gbc.weighty = 1;
        this.add(new JScrollPane(table), gbc);
    }

    private TableModel createTableModel() {
        DefaultTableModel model = new DefaultTableModel(
            new Object[] {"Car", "Color", "Year"}, 0 
        ){
            @Override 
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        addTableData(model);
        return model;
    }

    private void addTableData(DefaultTableModel model) {
        model.addRow(new Object[] {"Nissan", "Black", "2007"});
        model.addRow(new Object[] {"Toyota", "Blue", "2012"});
        model.addRow(new Object[] {"Chevrolet", "Red", "2009"});
        model.addRow(new Object[] {"Scion", "Silver", "2005"});
        model.addRow(new Object[] {"Cadilac", "Grey", "2001"});
    }


    class SharedListSelectionHandler implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            String contents = "";

            if(lsm.isSelectionEmpty()) {
                System.out.println("<none>");
            } else {
                int minIndex = lsm.getMinSelectionIndex();
                int maxIndex = lsm.getMaxSelectionIndex();
                for(int i = minIndex; i <= maxIndex; i++) {
                    if(lsm.isSelectedIndex(i)) {
                        for(int j = 0; j < table.getColumnCount(); j++) {
                            contents += table.getValueAt(i, j) + " ";
                        }
                    }
                }
                System.out.println(contents);
            }
        }

    }
}

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new SwingTesting();
            }
        });
    }
}

这并不像我想要的那样表现。它打印出双倍的信息。

所以不是Chevrolet Red 2009打印出来Chevrolet Red 2009 Chevrolet Red 2009。最终,我想将文本放在 JLabel 中并将其放在面板上。请记住,包含 JLabel 的面板与表格属于不同的类。

4

3 回答 3

3
table.getModel().addTableModelListener(tableModelListener);

详情请参阅TableModel.addTableModelListener(TableModelListener)


基于SSCCE。

带有选择详细信息的 GUI

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class SwingTesting {

    private final JFrame frame;
    private final TablePane tablePane;
    private final JSplitPane splitPane;
    private final JPanel infoPanel;

    JTextField make = new JTextField(9);;
    JTextField color = new JTextField(7);;
    JTextField year = new JTextField(4);

    public SwingTesting() {
        tablePane = new TablePane();
        infoPanel = new JPanel(new FlowLayout(5));

        infoPanel.add(new JLabel("Make"));
        infoPanel.add(make);
        infoPanel.add(new JLabel("Color"));
        infoPanel.add(color);
        infoPanel.add(new JLabel("Year"));
        infoPanel.add(year);

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tablePane, infoPanel);

        frame.add(splitPane);
        frame.pack();
        frame.setVisible(true);
    }

    class TablePane extends JPanel {

        private final JTable table;
        private final TableModel tableModel;
        private final ListSelectionModel listSelectionModel;

    private void setFields(int index) {
        make.setText(table.getValueAt(index, 0).toString());
        color.setText(table.getValueAt(index, 1).toString());
        year.setText(table.getValueAt(index, 2).toString());
    }

    private void clearFields() {
        make.setText("");
        color.setText("");
        year.setText("");
    }

    public TablePane() {
        table = new JTable();
        tableModel = createTableModel();
        table.setModel(tableModel);
        table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        table.add(table.getTableHeader(), BorderLayout.PAGE_START);
        table.setFillsViewportHeight(true);

        listSelectionModel = table.getSelectionModel();
        table.setSelectionModel(listSelectionModel);
        listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
        table.setSelectionModel(listSelectionModel);

        this.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridheight = 1;
    gbc.gridwidth = 3;
    gbc.insets = new Insets(5, 5, 5, 5);
    gbc.ipadx = 2;
    gbc.ipady = 2;
    gbc.weightx = 1;
    gbc.weighty = 1;
        this.add(new JScrollPane(table), gbc);
    }

    private TableModel createTableModel() {
        DefaultTableModel model = new DefaultTableModel(
            new Object[] {"Car", "Color", "Year"}, 0
        ){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        addTableData(model);
        return model;
    }

    private void addTableData(DefaultTableModel model) {
        model.addRow(new Object[] {"Nissan", "Black", "2007"});
        model.addRow(new Object[] {"Toyota", "Blue", "2012"});
        model.addRow(new Object[] {"Chevrolet", "Red", "2009"});
        model.addRow(new Object[] {"Scion", "Silver", "2005"});
        model.addRow(new Object[] {"Cadilac", "Grey", "2001"});
    }


    class SharedListSelectionHandler implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            String contents = "";

            if(lsm.isSelectionEmpty()) {
                System.out.println("<none>");
            } else {
                int minIndex = lsm.getMinSelectionIndex();
                int maxIndex = lsm.getMaxSelectionIndex();
                if (minIndex==maxIndex) {
                    setFields(minIndex);
                } else {
                    clearFields();
                    for(int i = minIndex; i <= maxIndex; i++) {
                        if(lsm.isSelectedIndex(i)) {
                            for(int j = 0; j < table.getColumnCount(); j++) {
                                contents += table.getValueAt(i, j) + " ";
                            }
                        }
                    }
                    System.out.println(contents);
                }
            }
        }

    }
}

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new SwingTesting();
            }
        });
    }
}
于 2012-05-15T18:37:43.207 回答
2

我会用

  • table.getSelectedRow()可能是安全的,直到/没有实施RowSorteror RowFilter,否则你必须convertViewToModel

  • MouseListener为了JToolTip

  • ListSelectionListener()是直接的方法,但是

一个)setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

b) 测试 if row > -1,否则没有选择任何行

c) 那么就没有理由思考或减少I would prefer to have double/multi click disabled.

  • frame.getContentPane().add(splitPane);不需要ContentPane从 Java5使用

  • SwingTesting();请阅读初始线程

编辑:

如何在此处此处顶部示例中使用ListSelectionListener

于 2012-05-15T18:33:51.100 回答
1

好吧,我认为使用自定义MouseListener不像使用可以在每一行的单独列上ButtonColumn呈现的特殊那样可行JButton,您只需ActionListenerJButton.

更多信息可以在这里找到: 表格按钮列

于 2012-05-15T18:23:40.857 回答