在JMenuBar中调整JTextField的大小 [英] Resizing JTextField in JMenuBar

查看:153
本文介绍了在JMenuBar中调整JTextField的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将JTextField作为搜索栏添加到JFrame顶部的JMenuBar中.我的问题是JTextField的大小不断调整,以占用JMenuBar中的所有可用空间,而我不希望这样做.我尝试了setPreferredSize()setMaximum Size(),但是它们没有用,大概是因为JMenuBar中使用的LayoutManager不遵守这些大小.我还尝试将JTextField添加到带有FlowLayoutJPanel并将面板添加到JMenuBar,但是我得到的内容如下所示:

I'm trying to add a JTextField as a search bar to a JMenuBar at the top of my JFrame. My problem is that the JTextField keeps getting resized to take up all available space in the JMenuBar, and I don't want it to. I've tried setPreferredSize() and setMaximum Size(), but these didnt work, presumably because the LayoutManager used in the JMenuBar doesn't respect these sizes. I also tried adding the JTextField to a JPanel with a FlowLayout and adding the panel to the JMenuBar, but I get something that looks like this:

面板位于JMenuBar的右侧,大小似乎正确,但是除了这个奇怪的蓝色条形图之外,我看不到其他任何内容.

The panel is on the right side of the JMenuBar, and the size seems to be correct, but I can't see anything in it other than this weird blue bar.

以下是(我认为)相关的代码.让我知道是否需要更多:

Here's the code that (I think) is relevant. Let me know if more is needed:

       JPanel searchPanel = new JPanel();
    searchPanel.setPreferredSize(new Dimension(100, 25));


    JTextField searchBar = new JTextField(50);

    String[] fields = {"title", "author", "subject", "publisher", "year", "circulating", "catalog" };


    JComboBox searchFields = new JComboBox(fields);

    JButton searchBtn = new JButton("search");

    searchPanel.add(searchBar);
    searchPanel.add(searchFields);
    searchPanel.add(searchBtn);
    searchPanel.setVisible(true);

    fileMenu.add(open);
    fileMenu.add(save);
    fileMenu.add(exit);

    libMenu.add(viewLib);
    libMenu.addSeparator();
    libMenu.add(newBook);
    libMenu.add(search);

    this.setJMenuBar(topBar);
       topBar.add(fileMenu);
    topBar.add(libMenu);
    topBar.add(Box.createHorizontalGlue());
   topBar.add(searchPanel);

推荐答案

这对我有用.

menuBar.add(Box.createHorizontalGlue());
JTextField textField = new JTextField(10);
textField.setMaximumSize( textField.getPreferredSize() );
menuBar.add(textField);

如果需要更多帮助,请发布SSCCE.

Post an SSCCE if you need more help.

再次,发布该代码仅仅是为了表明问题出在包含文本字段的最大大小.您如何选择执行此操作取决于您.

Again, the code is posted was just to show that the problem is in containing the maximum size of the text field. How you choose to do this is up to you.

这篇关于在JMenuBar中调整JTextField的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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