java中空格键vk__Java Swing - 如何register键板用于JDialog的VK_SPACE操作

import java.awt.BorderLayout;

import java.awt.FlowLayout;

import java.awt.Frame;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;

import javax.swing.JButton;

import javax.swing.JComponent;

import javax.swing.JDialog;

import javax.swing.JList;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.KeyStroke;

import javax.swing.ListSelectionModel;

public class Main {

public static void main(String[] args) {

JDialog dialog;

JList jlist;

ActionListener otherListener = new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

System.out.println("current");

}

};

JButton okButton = new JButton("OK");

okButton.addActionListener(e -> close(true));

JButton cancelButton = new JButton("Cancel");

cancelButton.addActionListener(e -> close(false));

jlist = new JList(new String[] { "A", "B", "C", "D", "E", "F", "G" });

jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

jlist.setVisibleRowCount(5);

JScrollPane scroll = new JScrollPane(jlist);

JPanel buttonsPanel = new JPanel(new FlowLayout());

buttonsPanel.add(okButton);

buttonsPanel.add(cancelButton);

JPanel content = new JPanel(new BorderLayout());

content.add(scroll, BorderLayout.CENTER);

content.add(buttonsPanel, BorderLayout.SOUTH);

dialog = new JDialog((Frame) null, true);

dialog.setContentPane(content);

dialog.pack();

dialog.getRootPane().registerKeyboardAction(otherListener,

KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),

JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

dialog.getRootPane().registerKeyboardAction(otherListener,

KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),

JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

dialog.getRootPane().getInputMap()

.put(KeyStroke.getKeyStroke("SPACE"), "doSomething");

dialog.getRootPane().getActionMap()

.put("doSomething", new AbstractAction() {

@Override

public void actionPerformed(ActionEvent e) {

System.exit(0);

}

});

dialog.setVisible(true);

}

static void close(boolean commit) {

if (commit) {

System.out.println("Now saving...");

} else {

System.out.println("Now closing...");

System.exit(0);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值