我刚接触Java,找不到简单的解决方案。在下图中,您可以看到我的问题所在。我想写一个程序,在那里我可以创建播放列表并保护它们,但我已经被困在一开始,因为JTextfield太小了。
import javax.swing.JFrame;
public class Main {
public static void main(String args[]) {
JFrame w = new Layout();
w.setVisible(true);
w.setSize(600, 600);
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setLocationRelativeTo(null);
w.setResizable(true);
}
}import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class Layout extends JFrame{
JTextField input;
Layout(){
//title and layout type
super("ThePlay");
setLayout(new FlowLayout());
JButton s; //search button
JButton h; //home button
JButton mp; //my playlist button
JButton cp; //create playlist button
JButton fs; //favorite songs button
//frame constructor
Container mainContainer = this.getContentPane();
mainContainer.setLayout(new BorderLayout(8,6));
mainContainer.setBackground(Color.GRAY);
this.getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.GRAY));
//input constructor
input = new JTextField();
input.setBounds(300, 50, 150, 25);
//up frame
JPanel topPanel = new JPanel();
topPanel.setBorder(new LineBorder(Color.BLACK, 3));
topPanel.setBackground(Color.GRAY);
topPanel.setLayout(new FlowLayout(6));
//bot frame
JPanel downPanel = new JPanel();
downPanel.setBorder(new LineBorder(Color.BLACK, 3));
downPanel.setBackground(Color.GRAY);
downPanel.setLayout(new FlowLayout(5));
//create buttons
s = new JButton("Search");
h = new JButton("Home");
mp = new JButton("My Playlists");
cp = new JButton("Create Playlist");
fs = new JButton("Favorite Songs");
//add buttons to the frame
mainContainer.add(topPanel,BorderLayout.NORTH); //top frame location
mainContainer.add(downPanel,BorderLayout.CENTER); //bottom frame location
topPanel.add(input);
topPanel.add(s);
topPanel.add(h);
topPanel.add(mp);
topPanel.add(cp);
topPanel.add(fs);
}
}

发布于 2021-07-30 16:48:11
您可以通过以下方式为JTextField指定一个大小:
input = new JTextField(20);来自 的
传递给JTextField构造函数的整数参数,在本例中为20,表示字段中的列数。此数字与字段当前字体提供的度量一起用于计算字段的首选宽度。它不限制用户可以输入的字符数。
发布于 2022-02-04 17:29:19
当构造函数中的int过大时,JTextField将出现错误
我想这取决于容器的大小。
这里,如果我写10而不是5,它是不起作用的:
Dimension dim = getPreferredSize();
dim.width = 150;
setPreferredSize(dim);
nameLabel = new JLabel("Name: ");
nameField = new JTextField(5);https://stackoverflow.com/questions/68594431
复制相似问题