6

我有一个在小程序中显示表格的代码,由两列组成:-

  1. 图像图标
  2. 描述

这是我的代码:

    import javax.swing.table.*;

    public class TableIcon extends JFrame
     {
    public TableIcon()
    {
    ImageIcon aboutIcon = new ImageIcon("about16.gif");
    ImageIcon addIcon = new ImageIcon("add16.gif");
    ImageIcon copyIcon = new ImageIcon("copy16.gif");

    String[] columnNames = {"Picture", "Description"};
    Object[][] data =
    {
        {aboutIcon, "About"},
        {addIcon, "Add"},
        {copyIcon, "Copy"},
    };

    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    JTable table = new JTable( model )
    {
        //  Returning the Class of each column will allow different
        //  renderers to be used based on Class
        public Class getColumnClass(int column)
        {
            return getValueAt(0, column).getClass();
        }
    };
    table.setPreferredScrollableViewportSize(table.getPreferredSize());

    JScrollPane scrollPane = new JScrollPane( table );
    getContentPane().add( scrollPane );
}

public static void main(String[] args)
{
    TableIcon frame = new TableIcon();
    frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    frame.pack();
    frame.setVisible(true);
  }

} 

现在我想知道的是如何在我的表格上实现选择侦听器或鼠标侦听器事件,以便它应该从我的表格中选择一个特定的图像并显示在文本区域或文本字段上(我的表格包含图像文件的路径)?

我可以在表格和框架上的表格上添加文本字段吗?如果需要,请随时询问。

4

3 回答 3

7

在我的代码中,我有一个设置单选模式的表格;就我而言,如何编写列表选择侦听器(使用从 getMinSelectionIndex 到 getMaxSelectionIndex 的 for 循环)中描述的侦听器没有用,因为释放鼠标按钮我确定我只选择了一行。

所以我解决了如下:

....

int iSelectedIndex =-1;

....

JTable jtable = new JTable(tableModel); // tableModel defined elsewhere
jtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

ListSelectionModel selectionModel = jtable.getSelectionModel();

selectionModel.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
        handleSelectionEvent(e);
    }
});

....

protected void handleSelectionEvent(ListSelectionEvent e) {
    if (e.getValueIsAdjusting())
        return;

    // e.getSource() returns an object like this
    // javax.swing.DefaultListSelectionModel 1052752867 ={11}
    // where 11 is the index of selected element when mouse button is released

    String strSource= e.getSource().toString();
    int start = strSource.indexOf("{")+1,
        stop  = strSource.length()-1;
    iSelectedIndex = Integer.parseInt(strSource.substring(start, stop));
}

我认为这个解决方案不需要在开始和停止之间进行 for 循环来检查选择了哪个元素,当表格处于单选模式时更合适

于 2013-11-29T11:21:32.110 回答
5

这个怎么样?

        protected void handleSelectionEvent(ListSelectionEvent e) {
            if (e.getValueIsAdjusting())
                return;

            final DefaultListSelectionModel target = (DefaultListSelectionModel)e.getSource();
            iSelectedIndex = target.getAnchorSelectionIndex();
        }
于 2016-09-25T08:48:53.263 回答
3

阅读 Swing 教程中有关如何编写列表选择侦听器的部分。

您不能将文本字段添加到表格,但可以将文本字段和表格添加到同一框架。

于 2013-04-09T16:06:27.090 回答