我有JList
,在某些面板层次结构中,我无法通过键 UP 和 DOWN 事件更改选择,并注意到我不要向我的JList
发送任何关键事件,因此我开始通过添加以下行来调查Swing
层次结构的焦点管理:
mJList.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
System.out.println("focusLost to "+e.getOppositeComponent());
//mJList.requestFocus();
}
@Override
public void focusGained(FocusEvent e) {
System.out.println("focusGained");
}
});
一开始,我注意到我的一些按钮在我JList
获得它后几毫秒获得了焦点,所以我让所有这些按钮都不可聚焦,然后我得到了这个奇怪的结果,我的{{1失去焦点...... null ?!?!
JList
然后我添加了在focusLost方法中注释掉的行,以便在丢失时重新获得焦点,但我认为这是一个非常糟糕的长期解决方案,所以我的问题是:
focusGained
focusLost to null
仅获得时间焦点,如果不是这样,那为什么会被迫放弃JList
?答案 0 :(得分:1)
请您在此SSCCE上解释您的问题,否则发布您自己的
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Testing extends JFrame {
private static final long serialVersionUID = 1L;
private DefaultListModel listModel = new DefaultListModel();
private JList list = new JList(listModel);
private JScrollPane sp = new JScrollPane(list);
private JButton btn1 = new JButton("Reset Model with freeze");
private JButton btn2 = new JButton("Reset Model with change selection");
private int xX = 0;
public Testing() {
for (int x = 0; x < 19; x++) {
listModel.addElement("" + x);
xX++;
}
btn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
listModel.removeAllElements();
// caused locking GUI for long time in the case
// that Item count is more than 999 Items
for (int x = 0; x < 19; x++) {
listModel.addElement("" + (x + xX));
xX++;
}
}
});
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
//list.clearSelection();
if (list.getSelectedIndex() == 0) {
list.setSelectedIndex(1);
}
listModel.removeAllElements();
for (int x = 0; x < 19; x++) {
listModel.addElement("" + (x + xX));
xX++;
}
list.setSelectedIndex(0);
}
});
add(sp, BorderLayout.CENTER);
add(btn1, BorderLayout.NORTH);
add(btn2, BorderLayout.SOUTH);
setLocation(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
list.setSelectedIndex(0);
}
});
list.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
System.out.println("focusLost to " + e.getOppositeComponent());
//mJList.requestFocus();
}
@Override
public void focusGained(FocusEvent e) {
System.out.println("focusGained");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Testing().setVisible(true);
}
});
}
}