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

时间:2012-02-16 08:29:34

标签: java swing jtextfield netbeans-7 caret

我真的很困惑,因为我以为我解决了这个问题。我有一个自定义的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

test.java

package bepe;

public class test {

    public test(){}

    public static void main(String[] args) {

        GetExpressionDialog dialog = new GetExpressionDialog(null, true);
        dialog.setVisible(true);

        String input = dialog.getText();
        if (input.isEmpty()) return;

    }
}

1 个答案:

答案 0 :(得分:3)

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

textField.replaceSelection( symbol );

此外,下次发布演示此问题的SSCCE。对于简单的焦点问题,不需要发布300行代码。此外,使用非JDK类发布代码也无法帮助我们运行代码。