我有一个JTable
里面JScrollPane
。JPanel
我MouseListener
在最后一个JPanel
. 问题是,当鼠标按下外部可用空间时,我无法收听鼠标事件JTable
。我有另一个JPanel
with JTextField
,它将事件分派给它的 parent JPanel
。可能有一些属性可以设置JScrollPane
?
SSCCE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleTableDemo extends JPanel {
public SimpleTableDemo() {
super(new BorderLayout(0, 0));
String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };
Object[][] data = { { "Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false) }, { "John", "Doe", "Rowing", new Integer(3), new Boolean(true) }, { "Sue", "Black", "Knitting", new Integer(2), new Boolean(false) }, { "Jane", "White", "Speed reading", new Integer(20), new Boolean(true) }, { "Joe", "Brown", "Pool", new Integer(10), new Boolean(false) } };
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setBackground(Color.GREEN);
table.setFillsViewportHeight(false);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
JPanel textPanel = new JPanel();
JTextField textField = new JTextField(50);
textPanel.add(textField);
add(textPanel, BorderLayout.NORTH);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
System.out.println("PRESSED!!!");
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 400);
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}