我创建了一个显示背景图片的JLabel
,然后我添加了三个按钮和一个JTextField
,JLable
的布局为GridBagLayout
,但主要问题是JTextField
的大小。我的错是什么?我尝试了preferredSize
以及setBounds
。我是GridBagLayout
的新手。
p = new JPanel();
ImageIcon img = new ImageIcon("C:/Users/manpreet/Desktop/G.L.E.W/3.jpg");
l = new JLabel(img);
practice = new JButton("Practice (No Time Limit)");
Challenge = new JButton("Challenge (60 Seconds)");
l.setLayout(g);
practice.setFont(new Font("Garamond", Font.BOLD, 20));
practice.setForeground(Color.yellow);
practice.setBackground(Color.black);
Challenge.setBackground(Color.black);
Challenge.setFont(new Font("Garamond", Font.BOLD, 20));
Challenge.setForeground(Color.yellow);
gbc.gridx = 0;
gbc.gridy = 0;
l.add(practice,gbc);
gbc.gridwidth=1;
Insets insets1 = new Insets(2,2,2,2);
gbc.insets = insets1;
gbc.gridx = 2;
gbc.gridy = 0;
l.add(Challenge,gbc);
gbc.gridx=1;
gbc.gridy = 1;
t = new JTextField("TextField");
//t.setPreferredSize(new Dimension(150,20));
//t.setBounds(5,5,20,20);
start = new JButton("start");
t.setVisible(true);
start.setVisible(true);
l.add(t,gbc);
gbc.gridx=1;
gbc.gridy = 2;
l.add(start,gbc);
p.add(l);
f.add(p);
f.pack();
practice.addActionListener(this);
Challenge.addActionListener(this);
答案 0 :(得分:1)
首先,如果您希望人们花时间查看您的代码,那么您应该:
JTextField没有正确显示,它看起来像一条垂直线
如果框架中没有足够的空间来显示组件的首选大小,则会发生这种情况。然后GridBagLayout将以最小尺寸显示组件,这就是为什么你会得到一个非常小的文本字段。
基本代码看起来合理,因为你执行pack()。但是,也许在其他地方你用setSize(...)或其他东西覆盖pack()。
如果您需要更多帮助,请发布展示您问题的正确SSCCE。
答案 1 :(得分:0)
1)您可以指定JTextField
的列数,例如:t = new JTextField("TextField",20);
2)借助GridBagConstraints
参数:weightx
和fill
。
3)避免使用:
setPreferredSize(new Dimension(150,20));
setBounds(5,5,20,20);
示例:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class TestFrame extends JFrame{
public TestFrame(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
pack();
setVisible(true);
}
private void init() {
setLayout(new GridBagLayout());
JTextField f1 = new JTextField("text",10);
JTextField f2 = new JTextField("text");
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
add(f1,c);
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
add(f2,c);
}
public static void main(String... strings) {
new TestFrame();
}
}