I have a JTextField being added to an OverlayLayout, but the JTextField automatically scales to be the dimensions of the entire panel, which I don't want. I also don't want to mess with the dimensions of the JTextField because the default height is just right for the font, and the width is supposed to be defined by the number of columns in the constructor. What would be the right way to fix this?
Here's the relevant code that I have now: frame = new JFrame("frame"); frame.setResizable(false);
panel = new GamePanel();
panel.setPreferredSize(new Dimension(500,300));
panel.setLayout(new OverlayLayout(panel));
JTextField t = new JTextField(50);
panel.add(t);
frame.add(panel);
frame.pack();
frame.setVisible(true);
GamePanel is just a subclass of JPanel; it doesn't do anything that would affect the JTextField.
EDIT: ok, I've heard now that using the default Swing layout managers isn't the best idea. kleopatra linked a page that refers to three third-party layouts that should accomplish pretty much everything you need to do, but I can't find anything that would let me overlay a text field (or other component) onto another custom-rendered panel. What would be the right approach?
Does this work as you want it?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.LayoutManager;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
public class OverlaySampleAlignment0 {
public static void main(String args[]) {
JFrame frame = new JFrame("Overlay Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(500,300));
LayoutManager overlay = new OverlayLayout(panel);
panel.setLayout(overlay);
JTextField field = new JTextField("", 12);
field.setMaximumSize(field.getPreferredSize());
//button.setMaximumSize(new Dimension(25, 25));
field.setBackground(Color.white);
field.setAlignmentX(0.0f);
field.setAlignmentY(0.0f);
panel.add(field);
frame.add(panel);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
The height is exactly the height needed for the font, and the width is (in my example) 12 "columns" (JTextField does not use a monospaced font by default in my Java setup). Additionally I aligned it in the upper left corner.
This might also help trouble-shooting layout issues: Link
Most of the code is copied from here: Link. I just added the setMaximumSize(...)
and used a JTextField instead of buttons etc.