我在将 aJComboBox
用作 aCellEditor
时遇到问题JTable
。我希望在编辑JComboBox
并按下tab
后显示一个OptionsDialog
,如果选择了特定选项,则焦点保持在JComboBox
. 问题是由于选项卡,焦点移动到下一个单元格,我无法将其返回到JComboBox
下面是我的测试用例之一:
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class TestFocus {
public static void main(String[] args) {
TestFocus test = new TestFocus();
test.go();
}
public void go() {
//create the frame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create and add a tabbed pane to the frame
JTabbedPane tabbedPane = new JTabbedPane();
frame.getContentPane().add(tabbedPane);
//create a table and add it to a scroll pane in a new tab
JTable table = new JTable(new DefaultTableModel(new Object[] {"A", "B"}, 5));
JScrollPane scrollPane = new JScrollPane(table);
tabbedPane.addTab("test", scrollPane);
// create a simple JComboBox and set is as table cell editor on column A
Object[] comboElements = {"aaaaa1", "aaaaaa2", "b"};
final JComboBox comboBox = new JComboBox(comboElements);
comboBox.setEditable(true);
table.getColumn("A").setCellEditor(new DefaultCellEditor(comboBox));
// add an action listener for when the combobox is edited to display an options dialog
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxEdited")) {
// display an options pane
Object[] options = {"Yes", "No"};
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
int response = JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor(comboBox),
"Do you want to return the focus to the ComboBox?",
"This is just a test",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
comboBox.requestFocusInWindow();
if (response == 0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.requestFocusInWindow();
}
});
}
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
}
});
// pack and show frame
frame.pack();
frame.setVisible(true);
}
}