除非手动拉伸框架,否则文本框不会显示在框架上 [英] TextBox not displaying on frame until the frame is stretched manually

查看:126
本文介绍了除非手动拉伸框架,否则文本框不会显示在框架上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个登录页面.我为两个文本框和一个按钮编写了代码.用户名旁边的一个文本框,密码旁边的另一个文本框.下面的一个登录"按钮.但是我不确定为什么在输出中没有显示文本框和按钮.我只在输出屏幕上看到用户名和密码标签.

I am trying to create a login page. I wrote code for two textboxes and one button. One textbox next to Username and other one next to Password. One "Sign In" button below. But I am not sure why the textbox's and button are not shown on my output. I only get the Username and password label's on my ouput screen.

奇怪的是,每当我拉伸输出帧时(我的意思是水平或垂直拉动屏幕),两个文本框都会出现按钮.

Strange thing is whenever I stretch my output frame, (I mean either pulling the screen horizontally or vertically) the two textboxes and the button shows up.

请检查我的代码,让我知道出了什么问题.我试图放置图片以使其更易于理解,但我的声誉不高.请帮忙.

Please check my code and let me know what's wrong. I was trying to put pictures to make easier to understand but I do not have enough reputation. Please help.

import javax.swing.*;
import java.awt.*;

public class HomeScreen{

public static void main(String args[]){

JFrame frame = new JFrame("Medical Store");
frame.setVisible(true);
frame.setSize(600,400);
JPanel panel = new JPanel(new GridBagLayout());
frame.getContentPane().add(panel, BorderLayout.NORTH);

GridBagConstraints c = new GridBagConstraints();

JLabel label1 = new JLabel("Username");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,10,10);
panel.add(label1,c);

JLabel label2 = new JLabel("Password");
c.gridx = 0;
c.gridy = 1;    
panel.add(label2,c);

JTextField textbox1 = new JTextField(10);
c.gridx = 1;
c.gridy = 1;
panel.add(textbox1,c);

JTextField textbox2 = new JTextField(10);
c.gridx = 2;
c.gridy = 1;
panel.add(textbox2,c);

JButton button1 = new JButton("Sign In");
c.gridx = 1;
c.gridy = 2;
panel.add(button1,c);

}   
}

推荐答案

在添加所有组件之前,您正在调用setVisible(true) ,因此您的GUI正在这样做 >,然后在添加组件之前进行绘制.

You're calling setVisible(true) before adding all components, and so your GUI is doing just that, drawing itself before components are added.

JFrame frame = new JFrame("Medical Store");
frame.setVisible(true);

// all components added here

解决方案:在添加所有组件后的结束后进行setVisible(true)调用.

Solution: make the setVisible(true) call at the end after adding all components.

JFrame frame = new JFrame("Medical Store");

// all components added here

frame.setVisible(true);

现在所有组件都应该可视化.

Now all components should be visualized.

其他问题:

  • 避免在任何情况下调用setSize(...).取而代之的是让布局管理器和组件首选大小为您做到这一点.
  • 在将JFrame设置为可见之前,先在JFrame上调用pack(),以便进行上述操作.
  • Avoid calling setSize(...) on anything. Instead let the layout managers and component preferred sizes do that for you.
  • Call pack() on the JFrame just prior to setting it visible so that the above will happen.

这篇关于除非手动拉伸框架,否则文本框不会显示在框架上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆