gpt4 book ai didi

java - 如何在java中设置JTextField边框大小

转载 作者:行者123 更新时间:2023-12-02 06:11:45 25 4
gpt4 key购买 nike

我想设置JTextField的边框高度和宽度,并想将其放在java中的JFrame的中心。我尝试了这些想法,但这些想法行不通。setSize(),SetPrefferedSize(),SetMaximumSize();

需要帮助。提前致谢。

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class P{
public static void main(String [] args){
JFrame frame = new JFrame();
JTextField field = new JTextField();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.NORTH,field);
frame.setSize(350,300);
frame.setVisible(true);

}
}

最佳答案

您可以尝试在 JTextField 上使用 LineBorder 并使用 GridBagLayout 将其放置在容器中

例如...

TextField

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class BorderText {

public static void main(String[] args) {
new BorderText();
}

public BorderText() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JTextField field = new JTextField(10);
field.setBorder(new LineBorder(Color.RED, 10));

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

}

看看How to Use BordersA Visual Guide to Layout Managers了解更多详情

关于java - 如何在java中设置JTextField边框大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com