【问题标题】:Repainting my JFrame重绘我的 JFrame
【发布时间】:2014-06-12 06:01:50
【问题描述】:

我有一个问题。在向我的 JFrame 添加几个对象后,当我执行应用程序时,我需要调整表单的尺寸以查看所有内容。我做了一些研究,我明白我需要在某处插入这行代码(但我不知道在哪里!!)

revalidate(); 

repaint();

我尝试在任何地方添加这些,但出现语法错误....帮助?

package test_area;

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


public class Test_area {

   // private JFrame f;
   // private JPanel p;
    //private JButton b1;
    private JLabel lab;

    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;

    public Test_area()
    {
        gui();

    }


    public void gui()
    {

      JFrame  f = new JFrame("Ma JFrame");
        f.setVisible(true);
        f.setSize(600,400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel p = new JPanel(new GridBagLayout());
        p.setBackground(Color.CYAN);
        //p.setSize(450,250);

       JButton b1 = new JButton("Login");
       JButton b2 = new JButton("Exit_ ");
       JLabel l1 = new JLabel("Username");
       JLabel l2 = new JLabel("Password");
       JLabel validate = new JLabel("Not Validated Yet");
       TextField textField = new TextField(20);
       JPasswordField pwField = new JPasswordField(15);


        GridBagConstraints c = new GridBagConstraints();

        c.insets = new Insets(5,5,5,5);

        c.gridx=0;
        c.gridy=1;

        p.add(l1,c);

        c.gridx = 1;
        c.gridy = 1;
        p.add(textField,c);

        c.gridx = 0;
        c.gridy = 2;
        p.add(l2,c);

        c.gridx= 1;
        c.gridy=2;
        p.add(pwField,c);

        c.gridx=2;
        c.gridy=1;
        p.add(b1,c);


        c.gridx=2;
        c.gridy=2;

        p.add(b2,c);


        c.gridx=3;
        c.gridy=1;
        p.add(validate,c);

        f.add(p,BorderLayout.NORTH);



//        JButton button;
//        JPanel p = new JPanel();
//        p.setLayout(new GridBagLayout());
//        GridBagConstraints c = new GridBagConstraints();
//        
//        if(shouldFill)
//        {
//         c.fill = GridBagConstraints.HORIZONTAL;
//        }
//        
//        button = new JButton("Button1");
//        
//        if(shouldWeightX)
//        {
//            c.weightx = 0.5;
//        }
//        





    }


    public static void main(String[] args) {

       new Test_area();


    }

}

【问题讨论】:

标签: java swing


【解决方案1】:

使用您的代码,我找不到任何语法错误(代码编译)。您应该使用 pack 为您的 JFrame 使用最小尺寸。因此,只需在添加所有组件后添加 f.pack();

【讨论】:

  • 非常感谢。我也有这么大的空间,因为我想登录,所以如果我成功输入用户和密码,那么秘密 JPanel 就会变得可见。 :D 非常感谢,我对此感到非常困扰。此外,我确实设法使用您的 pack() 或 f.repaint() 和 f.revalidate() 使其工作
【解决方案2】:

正如 user3575404 所说,是的,请致电 pack(),但最重要的是,将所有组件添加到您的 GUI 之后,请致电 setVisible(true)。您现在首先调用它,所以会发生这种情况 - 绘制 GUI,然后添加仍然不可见的组件,因此结果应该不会让您感到惊讶。

【讨论】:

    猜你喜欢
    • 2016-04-20
    • 2015-03-25
    • 2023-03-08
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多