如何将 JTextField 添加到 JFrame 的 MenuBar? [英] How can I add a JTextField to a JFrame's MenuBar?

查看:37
本文介绍了如何将 JTextField 添加到 JFrame 的 MenuBar?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试重载 JMenu 并放入一些自定义代码来支持 JTextField,但这并不顺利.我在这里的主要目的是在菜单项的右侧添加一个搜索字段.所以我在左边有文件、编辑、帮助之类的东西,然后在右边是搜索栏,几乎就像某些浏览器中的谷歌搜索栏一样.有没有人知道我该如何添加此功能?

I've been trying to overload JMenu and put in some custom code to support a JTextField but that isn't going well. My main purpose here is to add a search field to the right of my menu items. So I have something like File, Edit, help on the left and then on the right would be the search bar, almost like how there is a google search bar in some browsers. Does anyone have an idea how I could go about adding this functionality?

推荐答案

我从来没有把它看作 JMenuItem,我认为它总是放在 JMenuBar

I never see that as JMenuItem, I think that alyways placed in JMenuBar

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

public class MenuGlueDemo {

    public MenuGlueDemo() {
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(createMenu("Menu 1"));
        menuBar.add(createMenu("Menu 2"));
        menuBar.add(createMenu("Menu 3"));
        menuBar.add(new JSeparator());
        menuBar.add(new JButton("   Seach ....  "));
        menuBar.add(new JTextField("   Seach ....  "));
        menuBar.add(new JComboBox(new Object[]{"height", "length", "volume"}));
        menuBar.add(Box.createHorizontalGlue());
        menuBar.add(createMenu("About"));
        JFrame frame = new JFrame("MenuGlueDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(menuBar);
        frame.pack();
        frame.setVisible(true);
    }

    public JMenu createMenu(String title) {
        JMenu m = new JMenu(title);
        m.add("Menu item #1 in " + title);
        m.add("Menu item #2 in " + title);
        m.add("Menu item #3 in " + title);
        if (title.equals("About")) {
            m.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }
        return m;
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                MenuGlueDemo menuGlueDemo = new MenuGlueDemo();
            }
        });
    }
}

这篇关于如何将 JTextField 添加到 JFrame 的 MenuBar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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