日期:2014-05-20 浏览次数:20783 次
import java.awt.FlowLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTable; public class ComboBoxText { private static String[] data1 = {"北京","天津","上海"}; private static String[] data2 = {"东北","华北","华南"}; public static void main(String[] args) { final ComboBoxText ct = new ComboBoxText(); final JTable t = new JTable(2,2); final JComboBox cb = new JComboBox(); t.setValueAt("1", 0, 0); t.setValueAt("2", 0, 1); t.setValueAt("3", 1, 0); t.setValueAt("4", 1, 1); t.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { int rowIndex = t.getSelectedRow(); int colIndex = t.getSelectedColumn(); if(rowIndex==0){ cb.removeAllItems(); for (int i = 0; i < data1.length; i++) { cb.addItem(data1[i]); } } if(rowIndex==1){ cb.removeAllItems(); for (int i = 0; i < data2.length; i++) { cb.addItem(data2[i]); } } } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT)); f.add(t); f.add(cb); f.setVisible(true); f.setSize(200, 100); } }
------解决方案--------------------
import java.awt.FlowLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTable; public class ComboBoxText { public static void main(String[] args) { final int numRows = 4; final int numColumns = 2; final ComboBoxText ct = new ComboBoxText(); final JTable t = new JTable(numRows,numColumns); final JComboBox cb = new JComboBox(); t.setValueAt("北京", 0, 0); t.setValueAt("天津", 1, 0); t.setValueAt("上海", 2, 0); t.setValueAt("重庆", 3, 0); t.setValueAt("1", 0, 1); t.setValueAt("2", 1, 1); t.setValueAt("3", 2, 1); t.setValueAt("4", 3, 1); t.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { // int rowIndex = t.getSelectedRow(); int colIndex = t.getSelectedColumn(); cb.removeAllItems(); for (int i = 0; i < numRows; i++) { Object o = t.getValueAt(i, colIndex); cb.addItem(o); } } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT)); f.add(t); f.add(cb); f.setVisible(true); f.setSize(400, 400); } }