0

我的问题与此类似:JTable Cell Update doesn't work

但是,我使用的是 JDialog 而不是上面链接中指定的 JTable。我有一个扩展 JDialog 的自定义类。我在该对话框中使用 JEditorPane 作为文本组件并创建简单的确定、取消按钮。现在的问题是,当我在 JEdiorPane 中输入内容并按下 OK 按钮时,该值不会应用于文本组件,直到我将焦点移出 JDialog 或点击 tab/ENTER。

我希望在按下 OK 按钮后立即通知容器我已完成编辑。简而言之,我想明确地拥有一个类似于 stopCellEditing() 的功能。我怎样才能做到这一点?

4

1 回答 1

1

请参阅此示例,该示例似乎可以正常工作并且与您描述的相同:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class TestEditorPaneDialog {

    public void init() {
        final JFrame frame = new JFrame();
        JButton clickMe = new JButton("Click me");
        clickMe.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                showDialog(frame);
            }
        });
        frame.add(clickMe);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        showDialog(frame);
    }

    private void showDialog(final JFrame frame) {
        final JDialog dialog = new JDialog(frame, true);
        final JEditorPane pane = new JEditorPane();
        pane.setText("Type something here");
        JPanel south = new JPanel();
        JPanel buttons = new JPanel(new GridLayout(1, 0, 10, 10));
        JButton ok = new JButton("OK");
        ok.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
                JOptionPane.showMessageDialog(frame, "You have typed in: " + pane.getText());
            }
        });
        JButton cancel = new JButton("Cancel");
        cancel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        buttons.add(ok);
        buttons.add(cancel);
        south.add(buttons);
        dialog.add(new JScrollPane(pane));
        dialog.add(south, BorderLayout.SOUTH);
        dialog.setSize(250, 150);
        dialog.setLocationRelativeTo(frame);
        dialog.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestEditorPaneDialog().init();
            }
        });
    }
}
于 2013-09-12T09:28:08.703 回答