简体   繁体   English

JPanel和JMenuBar到同一框架

[英]JPanel and JMenuBar to the same frame

I can't seem to add both a JMenuBar and a JPanel to my frame? 我似乎无法在框架中同时添加JMenuBar和JPanel吗?

How come? 怎么会?

Code: 码:

package proj;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class Proj extends JFrame implements ActionListener {

Proj() {
setSize(400,300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setVisible(true);

JMenuBar rodMenu = new JMenuBar();
JMenu menu = new JMenu("Vis");
JMenuItem men_item1 = new JMenuItem("Statestik");

JPanel wrapper = new JPanel();
wrapper.setPreferredSize(new Dimension(380, 240));
wrapper.setBorder(BorderFactory.createLineBorder(Color.black));

setJMenuBar(rodMenu);
rodMenu.add(menu);
menu.add(men_item1);

add(wrapper);
}

public static void main(String[] args) {
new Proj();
}

}

With this code, the panel isn't added, only the menu... If I remove the menu, then the panel appears. 使用此代码,不添加面板,仅添加菜单...如果我删除菜单,则显示面板。

What do you mean panel not appearing? 您是什么意思面板不出现? I could see both menu and panel with this code! 我可以看到带有此代码的菜单和面板!

在此处输入图片说明

If the problem still persist try moving the setSize(), setResizable() etc block down like 如果问题仍然存在,请尝试将setSize(),setResizable()等向下移动,例如

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class Proj extends JFrame implements ActionListener {

    Proj() {
        JMenuBar rodMenu = new JMenuBar();
        JMenu menu = new JMenu("Vis");
        JMenuItem men_item1 = new JMenuItem("Statestik");

        JPanel wrapper = new JPanel();
        wrapper.setPreferredSize(new Dimension(380, 240));
        wrapper.setBorder(BorderFactory.createLineBorder(Color.black));

        setJMenuBar(rodMenu);
        rodMenu.add(menu);
        menu.add(men_item1);

        JButton b = new JButton("Test");
        wrapper.add(b);

        add(wrapper);

        setSize(400, 300);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        setVisible(true);
    }

    public static void main(String[] args) {
        new Proj();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }

}

Try adding with 尝试添加

this.getContentPane.add(wrapper)

instead of 代替

add(wrapper)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM