目录:
- java源码:
- 效果图
java源码
package textfield;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class JtextField extends JFrame {
private JTextField textField;
public JtextField() {
initUi();
}
private void initUi() {
setTitle("example");
setLayout(new GridLayout(0, 1));
textField = new JTextField("Left");
textField.setHorizontalAlignment(JTextField.LEFT);
add(textField);
textField = new JTextField("Center");
textField.setHorizontalAlignment(JTextField.CENTER);
add(textField);
textField = new JTextField("Right");
textField.setHorizontalAlignment(JTextField.RIGHT);
add(textField);
textField = new JTextField("Leading");
textField.setHorizontalAlignment(JTextField.LEADING);
add(textField);
textField = new JTextField("Trailing");
textField.setHorizontalAlignment(JTextField.TRAILING);
add(textField);
add(new JButton("--------------------------------------------"));
textField = new JTextField(15);
JButton jbtnCut = new JButton("Cut");
JButton jbtnPaste = new JButton("Paste");
JButton jbtnCopy = new JButton("Copy");
jbtnCut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
textField.cut();
update();
}
});
jbtnPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
textField.paste();
update();
}
});
jbtnCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
textField.copy();
update();
}
});
textField.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent ce) {
update();
}
});
add(textField);
add(jbtnCut);
add(jbtnPaste);
add(jbtnCopy);
}
private void update() {
System.out.println("All text: " + textField.getText());
if (textField.getSelectedText() != null)
System.out.println("Selected text: " + textField.getSelectedText());
else
System.out.println("Selected text: ");
}
private void display() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setSize(250, (int) this.getSize().getHeight());
this.setVisible(true);
}
public static void main(final String args[]) {
new JtextField().display();
}
}
效果图: