gpt4 book ai didi

Java Swing : JTextField doesn't lose focus as expected

转载 作者:行者123 更新时间:2023-11-30 07:25:41 26 4
gpt4 key购买 nike

我有一个包含 2 列的 JTable。其中一列由 JTextField 表示,另一列由单选按钮表示。

模型以这种方式填充:

   model.addRow(new Object[]{radioButton, ""});

与 JTextField 关联的是这样的单元格编辑器:

class MyCellEditor extends DefaultCellEditor {

MyCellEditor(JTextField textField) {
super(textField);
textField.addFocusListener(new FocusListener() {

public void focusLost(FocusEvent e) {
// do something if focus is lost
}

@Override
public void focusGained(FocusEvent e) {
}
});
}

当我单击 JTextField 单元格时,我得到了预期的“闪烁”光标,因此我可以输入我的文本。无论如何,如果我单击主窗口中的其他任何地方,我会期望“focusLost(...)”方法已被调用,但只有当我在窗口中“玩”一下时才会发生这种情况(比如点击进出 jtextfield 几次)。

为什么组件在第一次点击另一个外部组件后不会失去焦点?

最佳答案

您可以在 TableCellEditor 中覆盖 stopEditing()

或者直接写

table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

更复杂的(JFormattedTextField)例子

import java.awt.Component;
import java.awt.EventQueue;
import java.text.DecimalFormat;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class EditorAsRendererTableTest {

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
JTable table = new JTable(3, 2);
TableColumnModel colModel = table.getColumnModel();
MyCellEditor both = new MyCellEditor();
colModel.getColumn(0).setCellEditor(both);
colModel.getColumn(0).setCellRenderer(both);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

private static class MyCellEditor extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {

private static final long serialVersionUID = 1L;
private JFormattedTextField renderer = new JFormattedTextField(DecimalFormat.getInstance());
private JFormattedTextField editor;

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
renderer.setValue(value);
return renderer;
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
editor = new JFormattedTextField(DecimalFormat.getInstance());
editor.setValue(value);
return editor;
}

@Override
public boolean stopCellEditing() {
try {
editor.commitEdit();
} catch (ParseException e) {
return false;
}
return super.stopCellEditing();
}

@Override
public Object getCellEditorValue() {
return editor.getValue();
}
}

private EditorAsRendererTableTest() {
}
}

关于Java Swing : JTextField doesn't lose focus as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10784875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com