【问题标题】:JTextField, set caret position to end of input without highlighting whole stringJTextField,将插入符号位置设置为输入末尾而不突出显示整个字符串
【发布时间】:2012-02-16 08:29:34
【问题描述】:

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

    }
}

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE
  • 同意,如果你在玩 JDialog,那么看到 SSCCE 真的很重要,其他的一切都应该是黑暗的
  • 为什么要调用requestFocus()?让按钮无法聚焦会更好吗?
  • 我调用了 requestFocus() 这样您就可以继续输入,而无需再次单击文本字段。如果使按钮不可聚焦具有相同的效果,我可以尝试这样做,但我不确定这就是它发生的原因
  • 贱与否,直到现在它是正确的(一次太频繁了:)

标签: java swing jtextfield netbeans-7 caret


【解决方案1】:

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

textField.replaceSelection( symbol );

另外,下次发布SSCCE 来说明问题。一个简单的焦点问题不需要贴 300 行代码。此外,使用非 JDK 类发布代码也无助于我们运行代码。

【讨论】:

    猜你喜欢
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多