摆动组件不可见 [英] swing component not visible

查看:159
本文介绍了摆动组件不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,并且处于起步阶段. 我在JFrameJPanel中有一个JTextField. JTextField不存在. 如果我使用

I am working on an application and I am stuck in the incipient phase. I have a JTextField in a JPanel in a JFrame. JTextField isn't there. If I use

JPanel p0 = (JPanel) f.getContentPane();

有效.但不是

JPanel p0 = new JPanel();
f.add(p0);

所以问题是:

  1. 为什么该字段不可见? (最重要的q)
  2. 上述两种方法有什么区别?

代码:

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;

public class Main
{

    static Font fontDefault = new Font("arial", Font.PLAIN, 15);

    public static void main ( String [ ] args )
    {
        JFrame f = new JFrame("Liquid");
        f.setSize(new Dimension(840, 400));
        //f.setIconImage(image);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //JPanel p0 = (JPanel) f.getContentPane();// is it necessary?
        JPanel p0 = new JPanel();
        p0.setLayout(null);
        JPanel p1 = new JPanel();
        p1.setLayout(null);

        JTextField tfHostName = new JTextField("default text", 20);
        tfHostName.setBounds(50, 50, 200, 25);
        tfHostName.setFont(fontDefault);

        JButton bRequest = new JButton("request");
        JButton bReset = new JButton("reset");

        JTextArea taTest = new JTextArea("default text", 1, 20);
        p0.add(tfHostName);
        f.add(p0);

        f.add(p1);

        p0.add(taTest);
        //f.pack();
        f.setResizable(false);
        f.setVisible(true);

    }
}

提醒一下:

它与JPanel p0 = (JPanel) f.getContentPane();一起使用 但是为什么id不支持我更喜欢的第二种方法?另外,以这种方式,我如何添加第二个面板,以及如何使每个面板中的组件自动排列?

It works with JPanel p0 = (JPanel) f.getContentPane(); but why id doesn't with 2nd approach, which I'm more comfortable with? Plus, that way how do I add a second panel and how do I make components in each panel auto-arranged?

更新:

我意识到代码一开始就无法正常工作,可能是因为我没有指定任何坐标/位置吗?...

I realized that the code didn't work in the first place probably because I didn't specified any coordinates/position?...

推荐答案

首先,您必须将面板添加到layoutmangager.

first you have to add your panel to your layoutmangager.

喜欢

add(p0);

然后您需要调用JFrame的包装

and then you need a call to pack of the JFrame

pack();


如果需要2个面板,则可以在框架/布局管理器中为其指定位置.


if you want 2 panels, you have give them a position in your frame / layout manager.

f.add(pane1, BorderLayout.WEST);
f.add(pane2, BorderLayout.EAST);


您有3种可能性来设置组件的尺寸:


you have 3 possibilites to set the size on your components:

setPreferredSize(Dimension D);
setMinimumSize(Dimension D);
setMaximumSize(Dimension D);

这篇关于摆动组件不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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