当前位置: 技术问答>java相关
如何使JTextField中输入的文字居中显示
来源: 互联网 发布时间:2015-10-02
本文导语: 多谢! | 给你一个小例子,刚写的,呵呵:) import javax.swing.*; import java.awt.event.*; import java.awt.*; public class JTextFieldTest extends JFrame { public JTextFieldTest() { super("设置JTextField的文字...
多谢!
|
给你一个小例子,刚写的,呵呵:)
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JTextFieldTest extends JFrame
{
public JTextFieldTest()
{
super("设置JTextField的文字的位置");
JTextField text = new JTextField("这些文字将居中显示",10);
text.setHorizontalAlignment(JTextField.CENTER);
getContentPane().add(text,BorderLayout.NORTH);
setSize(300,400);
show();
}
public static void main(String args[])
{
JTextFieldTest p = new JTextFieldTest();
p.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
}
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JTextFieldTest extends JFrame
{
public JTextFieldTest()
{
super("设置JTextField的文字的位置");
JTextField text = new JTextField("这些文字将居中显示",10);
text.setHorizontalAlignment(JTextField.CENTER);
getContentPane().add(text,BorderLayout.NORTH);
setSize(300,400);
show();
}
public static void main(String args[])
{
JTextFieldTest p = new JTextFieldTest();
p.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
}
|
JTextField
public void setHorizontalAlignment(int alignment)
Sets the horizontal alignment of the text. Valid keys are:
JTextField.LEFT
JTextField.CENTER
JTextField.RIGHT
JTextField.LEADING
JTextField.TRAILING
invalidate and repaint are called when the alignment is set, and a PropertyChange event ("horizontalAlignment") is fired.
Parameters:
alignment - the alignment
Throws:
IllegalArgumentException - if alignment is not a valid key
public void setHorizontalAlignment(int alignment)
Sets the horizontal alignment of the text. Valid keys are:
JTextField.LEFT
JTextField.CENTER
JTextField.RIGHT
JTextField.LEADING
JTextField.TRAILING
invalidate and repaint are called when the alignment is set, and a PropertyChange event ("horizontalAlignment") is fired.
Parameters:
alignment - the alignment
Throws:
IllegalArgumentException - if alignment is not a valid key