Java JTextField,将插入符号位置设置为输入的结尾,而不突出显示整个字符串

Java JTextField,将插入符号位置设置为输入的结尾,而不突出显示整个字符串,java,swing,jtextfield,netbeans-7,caret,Java,Swing,Jtextfield,Netbeans 7,Caret,我真的很困惑,因为我以为我解决了这个问题。我有一个自定义的JDialog,用户在其中输入一个等式,还有一些按钮可以在光标位置向输入中添加特殊字符。以下是我必须添加特殊字符的函数: private void addSymbol(String symbol) { int pos = input.getCaretPosition(); String currInput = input.getText(); input.setText(currInput.subSequence

我真的很困惑,因为我以为我解决了这个问题。我有一个自定义的JDialog,用户在其中输入一个等式,还有一些按钮可以在光标位置向输入中添加特殊字符。以下是我必须添加特殊字符的函数:

private void addSymbol(String symbol) {

    int pos = input.getCaretPosition();
    String currInput = input.getText();
    input.setText(currInput.subSequence(0, pos) + symbol
            + currInput.subSequence(pos, currInput.length()));
    input.requestFocus();
    input.setCaretPosition(pos+1);

}
我在Netbeans中工作,昨天这个函数按预期工作。按一个按钮,将在光标位置添加字符,并将光标移到新字符后面的右侧,这样即使添加的字符位于字符串末尾,也可以继续键入而不中断。今天,我试图将代码复制到一个不同类型的项目中,所以在放弃并重新命名之前,我对正在工作的项目重新命名了几次

现在,当我尝试在输入的末尾添加一个特殊字符时,整个输入字符串都会高亮显示,因此很容易键入内容,添加一个字符,然后继续键入,并意外地覆盖刚刚输入的所有内容。在字符串中间添加字符时效果良好。我尝试了一个干净的构建,重新启动Netbeans,我删除了这个函数的各个部分,以确保我看到的版本实际上是被调用的版本(我遇到了一个事件,以前不是这样,所以现在我有点偏执)。有人知道会发生什么,或者如何在不高亮显示的情况下将光标设置在字符串的末尾吗

编辑:下面是测试代码

GetExpressionDialog.java

package bepe;

public class GetExpressionDialog extends javax.swing.JDialog {

    /** Creates new form GetExpressionDialog */
    public GetExpressionDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        input = new javax.swing.JTextField();
        andButton = new javax.swing.JButton();
        orButton = new javax.swing.JButton();
        stileButton = new javax.swing.JButton();
        messageLabel = new javax.swing.JLabel();
        submitButton = new javax.swing.JButton();
        notButton = new javax.swing.JButton();
        impliesButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        andButton.setText("∧");
        andButton.setToolTipText("You can also type \"&\"");
        andButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                andButtonActionPerformed(evt);
            }
        });

        orButton.setText("∨");
        orButton.setToolTipText("You can also type \"|\"");
        orButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                orButtonActionPerformed(evt);
            }
        });

        stileButton.setText("⊢");
        stileButton.setToolTipText("You can also type \"|-\"");
        stileButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
        stileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stileButtonActionPerformed(evt);
            }
        });

        messageLabel.setText("Enter the sequent you would like to prove:");

        submitButton.setText("Submit");
        submitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitButtonActionPerformed(evt);
            }
        });

        notButton.setText("¬");
        notButton.setToolTipText("You can also type \"!\"");
        notButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                notButtonActionPerformed(evt);
            }
        });

        impliesButton.setText("→");
        impliesButton.setToolTipText("You can also type \"->\"");
        impliesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                impliesButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(20, 20, 20)
                        .add(messageLabel))
                    .add(layout.createSequentialGroup()
                        .add(20, 20, 20)
                        .add(input, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 482, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(stileButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(notButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(andButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(orButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(impliesButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 200, Short.MAX_VALUE)
                        .add(submitButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(messageLabel)
                .add(8, 8, 8)
                .add(input, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(stileButton)
                    .add(notButton)
                    .add(andButton)
                    .add(orButton)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(impliesButton)
                        .add(submitButton)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void stileButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            

        addSymbol("⊢");

    }                                           

    private void andButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          

        addSymbol("∧");

    }                                         

    private void orButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         

        addSymbol("∨");

    }                                        

    private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             

        dispose();

    }                                            

    private void notButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          

        addSymbol("¬");

    }                                         

    private void impliesButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              

        addSymbol("→");

    }                                             

    private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   

        input.setText("");

    }                                  

    private void addSymbol(String symbol) {

        int pos = input.getCaretPosition();
        String currInput = input.getText();
        input.setText(currInput.subSequence(0, pos) + symbol
                + currInput.subSequence(pos, currInput.length()));
        input.requestFocus();
        input.setCaretPosition(pos+1);

    }

    public String getText() {
        return input.getText();
    }

    public javax.swing.JLabel getMessage() {
        return messageLabel;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GetExpressionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GetExpressionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GetExpressionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GetExpressionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                GetExpressionDialog dialog = new GetExpressionDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton andButton;
    private javax.swing.JButton impliesButton;
    private javax.swing.JTextField input;
    private javax.swing.JLabel messageLabel;
    private javax.swing.JButton notButton;
    private javax.swing.JButton orButton;
    private javax.swing.JButton stileButton;
    private javax.swing.JButton submitButton;
    // End of variables declaration

插入特殊字符的代码不是最有效的。您不需要替换整个文本。只需使用:

textField.replaceSelection( symbol );

另外,下次发布一个演示问题的帖子。对于一个简单的焦点问题,不需要发布300行代码。此外,发布带有非JDK类的代码也无助于我们运行代码。

为了更快地获得更好的帮助,请发布一个。同意,非常重要的一点是查看SSCE如果您使用JDialog,其他所有内容都应该是黑色的。您为什么调用requestFocus()?是否最好使按钮不可聚焦?我调用了requestFocus(),这样您就可以继续键入而无需再次单击文本字段。如果使按钮不可聚焦也有同样的效果,我可以尝试一下,但我不确定这是不是发生瘙痒的原因,直到现在它是正确的(一次太频繁了:)
textField.replaceSelection( symbol );