Swing中使用JTable右键菜单及可编辑数据状态
时间:2016-10-14 16:52 来源:未知 作者:机器AI 点击:次
Swing中使用JTable右键菜单及可编辑数据状态 在表格上显示右键菜单是使用率非常高的。这些代码非常实用,可以给我们很多启示。 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.DefaultCellEditor; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class TBTest { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(400,300); String[][] data = new String[][]{{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}, {"10", "11", "12"}}; String[] names = new String[]{"数值1", "数值2", "数值3"}; final JTable table = new JTable(data, names); DefaultCellEditor cellEdit = new DefaultCellEditor(new JTextField()); cellEdit.setClickCountToStart(2);//双击后使选择的格子可编辑 table.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { if (SwingUtilities.isRightMouseButton(me)) { final int row = table.rowAtPoint(me.getPoint()); System.out.println("row:"+row); if(row!=-1){ final int column = table.columnAtPoint(me.getPoint()); final JPopupMenu popup = new JPopupMenu(); JMenuItem select = new JMenuItem("选择"); select.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("选择"); table.setRowSelectionInterval(row, row); //高亮选择指定的行 } }); popup.add(select); popup.add(new JSeparator()); JMenuItem edit = new JMenuItem("编辑"); popup.add(edit); edit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("编辑"); table.clearSelection(); //清除高亮选择状态 table.editCellAt(row, column); //设置某列为可编辑 } }); JMenuItem calcel = new JMenuItem("取消"); calcel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("取消"); popup.setVisible(false); } }); popup.add(new JSeparator()); popup.add(calcel); popup.show(me.getComponent(), me.getX(), me.getY()); } } } }); JScrollPane scrollPane = new JScrollPane(table); frame.setTitle("JTable右键测试"); frame.add(scrollPane); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } (责任编辑:机器AI) |