Ms.*_*. B 8 java swing jtextfield jcreator
我试图让我的JTextField填充宽度并为其设置高度但仍然失败.我尝试添加代码setPreferredSize(new Dimension(320,200));但仍然失败.有什么方法可以让我的JTextField填充宽度并将高度设置为200或其他什么?
cam*_*ckr 21
你不应该玩高度.让文本字段根据使用的字体确定高度.
如果要控制文本字段的宽度,则可以使用
textField.setColumns(...);
Run Code Online (Sandbox Code Playgroud)
让文本字段确定首选宽度.
或者,如果您希望宽度为父面板的整个宽度,则需要使用适当的布局.也许是BorderLayout的北方.
有关更多信息,请参阅布局管理器上的Swing教程.
将高度设置为200
设置Font为大型变体(150 + px).如前所述,使用列控制宽度,并使用将遵循首选宽度和高度的布局管理器(或约束).

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class BigTextField {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new FlowLayout(5));
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
// Create big text fields & add them to the GUI
String s = "Hello!";
JTextField tf1 = new JTextField(s, 1);
Font bigFont = tf1.getFont().deriveFont(Font.PLAIN, 150f);
tf1.setFont(bigFont);
gui.add(tf1);
JTextField tf2 = new JTextField(s, 2);
tf2.setFont(bigFont);
gui.add(tf2);
JTextField tf3 = new JTextField(s, 3);
tf3.setFont(bigFont);
gui.add(tf3);
gui.setBackground(Color.WHITE);
JFrame f = new JFrame("Big Text Fields");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Run Code Online (Sandbox Code Playgroud)
您要向其中添加 JTextField 的面板使用什么类型的 LayoutManager?
不同的布局管理器以不同的方式调整元素的大小,有些遵循 SetPreferredSize(),而另一些则缩放组件以适合其容器。
请参阅:http ://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
附:这与eclipse无关,它是java的。