final JTextField x1 = new JTextField("0.0", 4); // Button1 x alignment
final JTextField y1 = new JTextField("0.0", 4); // Button1 y alignment
final JTextField x2 = new JTextField("0.0", 4);
final JTextField y2 = new JTextField("0.0", 4);
final JTextField x3 = new JTextField("0.0", 4);
final JTextField y3 = new JTextField("0.0", 4);
p2.add(x1);
p2.add(y1);
p2.add(x2);
p2.add(y2);
p2.add(x3);
p2.add(y3);
GridBagConstraints constraints = new GridBagConstraints();
c.add(p1, constraints);
constraints.gridx = 1;
JButton updateButton = new JButton("Update");
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jb1.setAlignmentX(
Float.valueOf(x1.getText().trim()).floatValue());
jb1.setAlignmentY(
Float.valueOf(y1.getText().trim()).floatValue());
jb2.setAlignmentX(
Float.valueOf(x2.getText().trim()).floatValue());
jb2.setAlignmentY(
Float.valueOf(y2.getText().trim()).floatValue());
jb3.setAlignmentX(
Float.valueOf(x3.getText().trim()).floatValue());
jb3.setAlignmentY(
Float.valueOf(y3.getText().trim()).floatValue());
p1.revalidate();
}
});
c.add(updateButton, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
c.add(p2, constraints);
}
public static void main(String args[]) {
OverlayTest ot = new OverlayTest();
ot.setVisible(true);
}
public class SimpleReporter implements ActionListener {
public void actionPerformed(ActionEvent ae) {
System.out.println(ae.getActionCommand());
}
}
public class GridPanel extends JPanel {
public void paint(Graphics g) {
super.paint(g);
int w = getSize().width;
int h = getSize().height;
g.setColor(Color.red);
g.drawRect(0,0,w-1,h-1);
g.drawLine(w/2,0,w/2,h);
g.drawLine(0,h/2,w,h/2);
}
}
}
最后提醒,使用OverlayLayout布局管理器关键要记住X,Y轴对应组件位置,和容器没有关系。只要明白这一点,使用还是很简单方便的,我用OverlayLayout布局管理器clone了一个PhotoShop的工具面板。