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:
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);
This works for me.
menuBar.add(Box.createHorizontalGlue());
JTextField textField = new JTextField(10);
textField.setMaximumSize( textField.getPreferredSize() );
menuBar.add(textField);
Post an SSCCE if you need more help.
Edit:
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.