可能使您感到惊讶的建议:
- 惊喜1:不要使用MouseListener
- 惊喜2:不要使用MouseMotionListener。
- 惊喜三:不要使用KeyListeners。
- 而是使用“键绑定”(此处为教程:“ 键绑定教程”)。我建议您在保存JLabel网格的JPanel上绑定Delete键。然后,当按下Delete键时,通过使用MouseInfo类获取PointerInfo实例,找出光标在哪个JLabel上(如果有的话),并使用该JLabel获取光标在屏幕上的位置。有了这些信息和一些简单的数学运算,您应该很容易找出哪个标签具有光标(再次,如果有的话),并采取适当的措施。请注意,“键绑定”教程将告诉您为什么使用这些键而不是使用KeyListeners更好,但是最重要的是,您不必花太多时间关注应用程序的焦点。
编辑 例如:
import java.awt.Component;import java.awt.GridLayout;import java.awt.MouseInfo;import java.awt.Point;import java.awt.PointerInfo;import java.awt.event.ActionEvent;import java.awt.event.KeyEvent;import javax.swing.*;@SuppressWarnings("serial")public class BindingExample extends JPanel { private static final int ROWS = 10; private static final int COLS = 8; JLabel[][] labels = new JLabel[ROWS][COLS]; public BindingExample() { setLayout(new GridLayout(ROWS, COLS)); for (int r = 0; r < labels.length; r++) { for (int c = 0; c < labels[r].length; c++) { String labelText = String.format("[%d, %d]", r, c); labels[r][c] = new JLabel(labelText, SwingConstants.CENTER); int eb = 4; labels[r][c].setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb)); add(labels[r][c]); } } int condition = JComponent.WHEN_IN_FOCUSED_WINDOW; InputMap inputMap = getInputMap(condition); ActionMap actionMap = getActionMap(); KeyStroke delKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0); String delete = "delete"; inputMap.put(delKeyStroke, delete); actionMap.put(delete, new DeleteAction()); } private class DeleteAction extends AbstractAction { @Override public void actionPerformed(ActionEvent evt) { PointerInfo pInfo = MouseInfo.getPointerInfo(); Point ptonScrn = pInfo.getLocation(); int xPanel = getLocationOnScreen().x; int yPanel = getLocationOnScreen().y; int x = ptOnScrn.x - xPanel; int y = ptOnScrn.y - yPanel; Component component = getComponentAt(x, y); if (component != null) { JLabel selectedLabel = (JLabel) component; System.out.println("Selected Label: " + selectedLabel.getText()); } } } private static void createAndShowGui() { BindingExample mainPanel = new BindingExample(); Jframe frame = new Jframe("Key Bindings Example"); frame.setDefaultCloseOperation(Jframe.DISPOSE_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); }}编辑2
Shoot,只是看到您问题的评论,是的,对于您的目的而言,JList可能会更好。



