2013-07-21 37 views
0

我想将我在JTable中选择的项目的名称放入JLabel中,每当我单击表格中的新项目时JLabel中的文本也发生变化 有人可以告诉我,我应该在java中学习什么?在JLabel中显示表格中的项目名称

+0

您应该首先介绍java的swing框架。然后看看JTable文档:http://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html – Addict

回答

2

你应该知道非常基本的Swing编程和TableModel的更深一点的了解, SelectionModelListSelectionListener(这是你的目标的关键)。

工作的示例:

import java.awt.BorderLayout; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JTable; 
import javax.swing.event.ListSelectionEvent; 
import javax.swing.event.ListSelectionListener; 

public class TableSelectionToLabel { 
    private static JTable t = new JTable(new String[][]{{"1,1", "1,2"}, {"2,1", "2,2"}}, 
          new String[]{"1", "2"}); 
    private static JLabel l = new JLabel("Your selction will appear here"); 
    private static JFrame f = new JFrame("Table selection listener Ex."); 
    private static ListSelectionListener myListener = new ListSelectionListener() { 
     @Override 
     public void valueChanged(ListSelectionEvent e) { 
      int col = t.getColumnModel().getSelectionModel().getLeadSelectionIndex(); 
      int row = t.getSelectionModel().getLeadSelectionIndex(); 
      try { 
       l.setText(t.getModel().getValueAt(row, col).toString()); 
      } catch (IndexOutOfBoundsException ignore) { 

      } 
     } 
    }; 

    public static void main(String[] args) { 
     t.getSelectionModel().addListSelectionListener(myListener); 
     t.getColumnModel().getSelectionModel().addListSelectionListener(myListener); 
     f.getContentPane().add(t, BorderLayout.NORTH); 
     f.getContentPane().add(l, BorderLayout.CENTER); 
     f.pack(); 
     f.setVisible(true); 
    } 
} 

编辑:

我修改了代码,以听取模型列模型都选择活动,以获得更准确的结果。

1

首先创建JLabel

JLabel label = new JLabel(); 

然后一个监听器添加到表选择:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { 
    public void valueChanged(ListSelectionEvent event) { 
     label.setText(table.getValueAt(table.getSelectedRow(), table.getSelectedColumn())); 
    } 
}); 
相关问题