我的JPanel为什么不显示? [英] Why won't my JPanel show?

查看:269
本文介绍了我的JPanel为什么不显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我只是检查,当我点击我的按钮时,它不会显示我的JPanel,任何想法为什么?

So I'm just checking and when I click my button it won't show my JPanel, any idea why?

谢谢。

我想要第三堂课,非常感谢帮助 - 谢谢分配。

I want the third class to show, really do appreciate the help - Thanks allot.

第一堂课 - JFrame课程。

import javax.swing.JFrame;

public class Frame {
    public static void main(String[] args ) {
        JFrame frame = new JFrame("JFrame Demo");
        Panel panel1 = new Panel();

        frame.add(panel1);


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 500);
        frame.setVisible(true);

    }
}

第二类 - 面板1

import javax.swing.JPanel;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Panel extends JPanel{
    public Panel() {
        setLayout(null);
        final Panel2 panel2 = new Panel2();


        JButton btnNewButton = new JButton("New button");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                setVisible(false);
                panel2.setVisible(true);


            }
        });
        btnNewButton.setBounds(62, 197, 224, 122);
        add(btnNewButton);
    }
}

第三类 - 第2小组(我想要这显示)

import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.CardLayout;
import javax.swing.JTextField;


public class Panel2 extends JPanel {
    private JTextField textField;
    public Panel2() {

        setLayout(null);
        setVisible(true);
        textField = new JTextField();
        textField.setBounds(84, 84, 290, 77);
        add(textField);
        textField.setColumns(10);

    }
}


推荐答案

您永远不会将 panel2 添加到任何内容中。 JPanel 不像 JFrame 其中 setVisible 使它神奇地出现了。您需要将其添加到容器中。只需将其添加到面板

You never add panel2 to anything. A JPanel isn't like a JFrame where setVisible makes it magically appear. You need to add it to a container. Just add it to your Panel.

  • Also avoid using null layouts. Learn to use Layout Managers

另见 初始主题 。你想从像这样的事件发送线程运行你的swing应用程序

Also see Initial Threads. You want to run your swing apps from the Event Dispatch Thread like this

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable(){
        public void run() {
            new Frame();
        }
    });
}


  • 这看起来像你可能一直试图做的情况类似于 CardLayout 实现的东西。有关基本用途,请参阅此 示例 。另请参阅 如何使用卡片布局

  • This looks like a case where you may have been trying to do something along the lines of what a CardLayout achieves. See this example for a basic use. Also see How to Use Card Layout

    这篇关于我的JPanel为什么不显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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