问题描述
我试图将JTextField
作为搜索栏添加到JFrame
顶部的JMenuBar
中.我的问题是JTextField
的大小不断调整,以占用JMenuBar
中的所有可用空间,而我不希望这样做.我尝试了setPreferredSize()
和setMaximum Size()
,但是它们没有用,大概是因为JMenuBar
中使用的LayoutManager
不遵守这些大小.我还尝试将JTextField
添加到带有FlowLayout
的JPanel
并将面板添加到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的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!