gpt4 book ai didi

java - 如何通过单击鼠标右键获取 JTable 单元格的值

转载 作者:行者123 更新时间:2023-12-02 04:45:29 25 4
gpt4 key购买 nike

我的 Java Swing 应用程序中有一个 JTable,总体来说一切工作正常。我在 JTable 上添加了一个 MouseListener,因此每当我尝试右键单击表中的一行时,我都可以捕获该事件并运行一个方法。然而,我想做的是

  • 选择单元格
  • 获取其值(value)
  • 然后调用该方法。

为此,我当前必须左键单击该行,然后右键单击它。是否可以通过单击鼠标右键立即选择行/单元格?

这是迄今为止我的代码:

public class MyMouseAdapterTableArticoli extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
JTable t = (JTable)me.getSource();
JMenuItem menuItem;
rowPopUp = t.rowAtPoint(me.getPoint());
if ((me.getClickCount() == 2) && (me.getButton() == MouseEvent.BUTTON1)) {
pulisciTableArtRappre();
if((listaMagazzino != null) && (listaMagazzino.size() > 0)) {
pulisciTableArtMagazzino();
}
popolaCampi(rowPopUp);
} else if (me.getButton() == MouseEvent.BUTTON3) {
JPopupMenu popup = new JPopupMenu();
menuItem = new JMenuItem("Mostra Prezzi di Acquisto");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mostraPrezziAcquisto(rowPopUp);
}//fine metodoVoid
});//fine actionlistener
popup.add(menuItem);

MouseListener popupListener = new PopupListener(popup);
table.addMouseListener(popupListener);

}//fine else e if
}

public void mousePressed(MouseEvent e) {
JTable source = (JTable)e.getSource();
int row = source.rowAtPoint(e.getPoint());
int column = source.columnAtPoint(e.getPoint());

if (!source.isRowSelected(row)) {
source.changeSelection(row, column, false, false);
}
}

最佳答案

table.addMouseListener( new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
JTable source = (JTable)e.getSource();
int row = source.rowAtPoint( e.getPoint() );
int column = source.columnAtPoint( e.getPoint() );

if (! source.isRowSelected(row))
source.changeSelection(row, column, false, false);
}
});

编辑:

学习新概念时创建一个简单的示例。例如:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SSCCE extends JPanel
{
public SSCCE()
{
JTable table = new JTable(15, 5);
add( new JScrollPane(table) );

table.addMouseListener( new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
JTable source = (JTable)e.getSource();
int row = source.rowAtPoint( e.getPoint() );
int column = source.columnAtPoint( e.getPoint() );

if (! source.isRowSelected(row))
source.changeSelection(row, column, false, false);
}
});
}

private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE(), BorderLayout.NORTH);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}

public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

关于java - 如何通过单击鼠标右键获取 JTable 单元格的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com