我的表有4列,我只想让第1列被点击。此外,此代码还允许使用LEFT鼠标按钮,我只想要右键。
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
int iCol = jTable1.getSelectedColumn();
if(iCol == 1 && evt.getModifiers() == InputEvent.BUTTON3_MASK)
{
if(evt.getClickCount() == 2)
{
int iRow = jTable1.getSelectedRow();
File iFile = new File(jTable1.getValueAt(iRow, iCol).toString());
String iPath = iFile.getAbsolutePath();
File iDir = new File(iPath.substring(0, iPath.lastIndexOf(File.separator)));
if(Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().open(iDir);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
如果这个问题变成2,我很抱歉。
答案 0 :(得分:1)
让我们开始,左键通常由MouseEvent.BUTTON1
表示,然后移到MouseEvent#getModifiers
通常用于提供有关当前按下的键的信息,我们开始看到主要问题。
您真正想要的方法是MouseEvent#getButton
尝试运行以下示例以获取一些想法;)
public class TestMouseClicked {
public static void main(String[] args) {
new TestMouseClicked();
}
public TestMouseClicked() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MousePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MousePane extends JPanel {
private JToggleButton leftButton;
private JToggleButton middleButton;
private JToggleButton rightButton;
public MousePane() {
setLayout(new GridBagLayout());
leftButton = new JToggleButton("Left");
middleButton = new JToggleButton("Middle");
rightButton = new JToggleButton("Right");
add(leftButton);
add(middleButton);
add(rightButton);
ButtonGroup bg = new ButtonGroup();
bg.add(leftButton);
bg.add(middleButton);
bg.add(rightButton);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getButton());
if (e.getButton() == MouseEvent.BUTTON1) {
leftButton.setSelected(true);
} else if (e.getButton() == MouseEvent.BUTTON2) {
middleButton.setSelected(true);
} else if (e.getButton() == MouseEvent.BUTTON3) {
rightButton.setSelected(true);
}
}
});
}
}
}
答案 1 :(得分:1)
关于仅点击特定列:
1.使用自己的模型创建表格。
final JTable table = new JTable( new MyTableModel(data, columnNames));
2。创建覆盖所需功能的新模型(即isCellEditable)
public class MyTableModel extends DefaultTableModel {
private static final long serialVersionUID = -8422360723278074044L;
MyTableModel(Object[][] data, Object[] columnNames )
{
super(data,columnNames);
}
public boolean isCellEditable(int row,int cols)
{
if(cols==1 ){return true;}
return false;
}
}