取消选择JTextfield上的默认选择

时间:2012-02-09 15:26:58

标签: java swing jtextfield caret getcaretpos

使用JTextField时,我喜欢设置默认文本。

然后我运行该程序,将自动选择此默认文本(至少当您只有一个字段时)。换句话说,如果我立即键入一个字母,默认文本将被删除并替换为新文本。

我的问题是如何以允许我键入字母而不删除默认文本的方式更改默认设置?我希望这封信只能添加到默认文本的末尾。

这是我的代码:

    public class ButtonsNText extends JPanel implements ActionListener, KeyListener {

private JTextField TextLine;
private JToggleButton UpperCaseButton;
private JToggleButton LowerCaseButton;
private JCheckBox ContinuousButton;
private ButtonGroup myButtonGroup;

public ButtonsNText(){
    TextLine = new JTextField(10);
    add(TextLine); TextLine.setName("TextLine");
    TextLine.setText("default text"); 
    TextLine.setCaretPosition(TextLine.getText().length());
    TextLine.addKeyListener(this);
    myButtonGroup = new ButtonGroup();
    UpperCaseButton = new JToggleButton("Upper case");
    add(UpperCaseButton);UpperCaseButton.setName("UpperCaseButton");
    LowerCaseButton = new JToggleButton("Lower case");
    add(LowerCaseButton); LowerCaseButton.setName("LowerCaseButton");
    ContinuousButton = new JCheckBox("Continuous?");
    add(ContinuousButton); ContinuousButton.setName("ContinuousButton");
    myButtonGroup.add(UpperCaseButton); myButtonGroup.add(LowerCaseButton);
    UpperCaseButton.addActionListener(this);
    LowerCaseButton.addActionListener(this);
    ContinuousButton.addActionListener(this);

}
public static void main(String[] args) {
    JFrame frame = new JFrame("Hello world example");
    frame.add(new ButtonsNText());
    frame.pack();
    frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == UpperCaseButton){
        TextLine.setText(TextLine.getText().toUpperCase());
    }
    else if(e.getSource() == LowerCaseButton){
        TextLine.setText(TextLine.getText().toLowerCase());
    }
}
@Override
public void keyReleased(KeyEvent k) {
    if(ContinuousButton.isSelected()){
        if(UpperCaseButton.isSelected()){
            int pos = TextLine.getCaretPosition();
            TextLine.setText(TextLine.getText().toUpperCase());
            TextLine.setCaretPosition(pos);
        }
        else if(LowerCaseButton.isSelected()){
            int pos = TextLine.getCaretPosition();
            TextLine.setText(TextLine.getText().toLowerCase());
            TextLine.setCaretPosition(pos);

        }
    }
    int key = k.getKeyCode();
    if(key == KeyEvent.VK_ENTER){
        if(UpperCaseButton.isSelected()){
            TextLine.setText(TextLine.getText().toUpperCase());
        }
        else if(LowerCaseButton.isSelected()){
            TextLine.setText(TextLine.getText().toLowerCase());
        }
    }
}

}

我尝试过像isFocusable(),setFocusable(),setCaterPosition()和其他类似的方法,但在这里我认为我需要一种不同的方法。

3 个答案:

答案 0 :(得分:6)

只需为焦​​点Gained添加一个FocusListener,它将与tfield2.setCaretPosition(tfield2.getDocument()。getLength()); 在这里,请参阅您的帮助代码:

import java.awt.event.*;

import javax.swing.*;

public class TextFieldExample extends JFrame
{
    public TextFieldExample()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel contentPane = new JPanel();
        JTextField tfield = new JTextField(10);
        final JTextField tfield2 = new JTextField(10);
        tfield2.setText("default text");
        tfield2.addFocusListener(new FocusListener()
        {
            public void focusGained(FocusEvent fe)
            {
                tfield2.setCaretPosition(tfield2.getDocument().getLength());
            }

            public void focusLost(FocusEvent fe)
            {
            }
        });

        contentPane.add(tfield);
        contentPane.add(tfield2);

        setContentPane(contentPane);

        pack();
        setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new TextFieldExample();
            }
        });
    }
}

答案 1 :(得分:3)

如果你把插入符号移到最后怎么样?

txt.setCaretPosition(txt.getText().length());

答案 2 :(得分:3)

表示@Pete将被删除

import java.awt.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;

public class TestTextComponents extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTextField jTextField1;
    private JTextField jTextField2;

    public TestTextComponents() {
        initComponents();
    }

    private void initComponents() {
        jTextField1 = new JTextField();
        jTextField2 = new JTextField();
        getContentPane().setLayout(new FlowLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("Text component persistent selection");
        setResizable(false);
        getContentPane().add(new JLabel(
                "Please skip between text fields and watch persistent selection: "));
        jTextField1.setText("jTextField1");
        getContentPane().add(jTextField1);
        jTextField2.setText("jTextField2");
        getContentPane().add(jTextField2);
        jTextField1.setCaret(new HighlightCaret());
        jTextField2.setCaret(new HighlightCaret());
        //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
       // setBounds((screenSize.width - 600) / 2, (screenSize.height - 70) / 2, 600, 70);
    }

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

            @Override
            public void run() {
                new TestTextComponents().setVisible(true);
            }
        });
    }
}

class HighlightCaret extends DefaultCaret {

    private static final Highlighter.HighlightPainter unfocusedPainter =
            new DefaultHighlighter.DefaultHighlightPainter(new Color(230, 230, 210));
    private static final long serialVersionUID = 1L;
    private boolean isFocused;

    @Override
    protected Highlighter.HighlightPainter getSelectionPainter() {
        return isFocused ? super.getSelectionPainter() : unfocusedPainter;
    }

    @Override
    public void setSelectionVisible(boolean hasFocus) {
        if (hasFocus != isFocused) {
            isFocused = hasFocus;
            super.setSelectionVisible(false);
            super.setSelectionVisible(true);
        }
    }
}