Is there a layout manager that gives the same degree of control as Absolute Positioning? But also makes auto resizing possible? Something where you could place elements using relative coordinates?
问题:
回答1:
GridBagLayout
is the most flexible standard layout manager in Swing and it can achieve practically anything you need, although nowhere near as simply as how you imagine by just using relative coordinates (what you mean, I guess, is 0-100% relative to the frame size).
You may find the official documentation for GridBagLayout
here, which also has some figures and examples.
You can also check out the open-source MiG Layout, which is much more convenient that GridBagLayout
and also a bit more powerful. It is the mother of all layout managers.
回答2:
The most powerful layout manager in JDK is GridBagLayout
. However typical UI contains composition of panels each of them is configured to use different layout. For example border layout for whole window, flow layout for panel that contains a set of buttons, GridLayout
or GridBagLayout
for complex parts.
You can also take a look on alternatives like MigLayout - very powerful tool that allows creating almost any view you can imagine.
回答3:
Another option is to use a SpringLayout(personally, I like a GridBagLayout).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import static javax.swing.SpringLayout.*;
public class SpringScaleTest {
public JComponent makeUI() {
SpringLayout layout = new SpringLayout();
JPanel p = new JPanel(layout);
p.setBorder(BorderFactory.createLineBorder(Color.GREEN, 10));
JLabel l1 = new JLabel("label: width=90%", SwingConstants.CENTER);
l1.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
JButton l2 = new JButton("button: width=50%");
Spring panelw = layout.getConstraint(WIDTH, p);
SpringLayout.Constraints c1 = layout.getConstraints(l1);
c1.setX(Spring.constant(0));
c1.setY(Spring.constant(20));
c1.setWidth(Spring.scale(panelw, 0.9f));
p.add(l1);
SpringLayout.Constraints c2 = layout.getConstraints(l2);
c2.setWidth(Spring.scale(panelw, 0.5f));
layout.putConstraint(SOUTH, l2, -20, SOUTH, p);
layout.putConstraint(EAST, l2, -20, EAST, p);
p.add(l2);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() { createAndShowGUI(); }
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new SpringScaleTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}