public class SelfLayoutingJPanel {
private JFrame main;
public SelfLayoutingJPanel() {
main = new JFrame("Demo");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel(new GridLayout(2, 2));
for(int i = 0; i < 4; i++){
mainPanel.add(new LayoutPanel());
}
main.getContentPane().add(mainPanel);
main.pack();
System.out.println("Panel size " + mainPanel.getPreferredSize());
main.setVisible(true);
}
public static void main(String[] args) {
SelfLayoutingJPanel demo = new SelfLayoutingJPanel();
}
}
class LayoutPanel extends JPanel implements LayoutManager{
JTextField tf = new JTextField("TextField",10);
JButton b = new JButton("#");
Dimension zero = new Dimension(0, 0);
LayoutPanel(){
super();
setLayout(this);
add(b);
add(tf);
}
public void addLayoutComponent(String key, Component c) {
}
public void removeLayoutComponent(Component c) {
}
public Dimension preferredLayoutSize(Container target) {
System.out.println("In preferredLayoutSize(Container target)");
Dimension dim = new Dimension(0, 0);
dim.width = tf.getPreferredSize().width + tf.getPreferredSize().height;
dim.height = tf.getPreferredSize().height;
System.out.println("Result: " + dim);
return dim;
}
public Dimension minimumLayoutSize(Container target) {
return new Dimension(tf.getPreferredSize().height, 2 * tf.getPreferredSize().height);
}
public void layoutContainer(Container c) {
int maxWidth = c.getWidth();
int maxHeight = c.getHeight();
int availableForTextField = maxWidth - tf.getPreferredSize().height;
Rectangle tfBounds = new Rectangle(0, 0, availableForTextField, tf.getPreferredSize().height);
Rectangle buttonBounds = new Rectangle(availableForTextField, 0, tf.getPreferredSize().height, tf.getPreferredSize().height);
System.out.println("TF Bounds: " + tfBounds);
System.out.println("Button Bounds: " + buttonBounds);
tf.setLocation(tfBounds.x, tfBounds.y);
tf.setSize(tfBounds.width, tfBounds.height);
b.setLocation(buttonBounds.x, buttonBounds.y);
b.setSize(buttonBounds.width, buttonBounds.height);
}
}