private
static
void
createAndShowGUI() {
// Create and set up the window.
JFrame frame =
new
JFrame(
"FlowLayoutDemo"
);
frame.setDefaultCloseOperation(JFrame.
EXIT_ON_CLOSE
);
// Set up the content pane.
addComponentsToPane(frame.getContentPane());
// Display the window.
frame.pack();
frame.setVisible(
true
);
}
|
public
static
void
addComponentsToPane(Container pane) {
pane.setLayout(
new
FlowLayout());
pane.add(
new
JButton(
"Button 1"
));
pane.add(
new
JButton(
"Button 2"
));
pane.add(
new
JButton(
"Button 3"
));
pane.add(
new
JButton(
"Long-Named Button 4"
));
pane.add(
new
JButton(
"5"
));
}
|
public
static
void
addComponentsToPane(Container pane) {
JPanel xPanel =
new
JPanel();
xPanel.setLayout(
new
BoxLayout(xPanel, BoxLayout.
X_AXIS
));
addButtons(xPanel);
JPanel yPanel =
new
JPanel();
yPanel.setLayout(
new
BoxLayout(yPanel, BoxLayout.
Y_AXIS
));
addButtons(yPanel);
pane.add(yPanel, BorderLayout.
PAGE_START
);
pane.add(xPanel, BorderLayout.
PAGE_END
);
}
private
static
void
addAButton(String text, Container container) {
JButton button =
new
JButton(text);
button.setAlignmentX(Component.
CENTER_ALIGNMENT
);
container.add(button);
}
private
static
void
addButtons(Container container) {
addAButton(
"Button 1"
, container);
addAButton(
"Button 2"
, container);
addAButton(
"Button 3"
, container);
addAButton(
"Long-Named Button 4"
, container);
addAButton(
"5"
, container);
}
|
public
static
void
addComponentsToPane(Container pane) {
JButton[] buttons =
new
JButton[9];
pane.setLayout(
new
GridLayout(3, 3));
for
(
int
i = 0; i < buttons.
length
; i++) {
buttons[i] =
new
JButton(i +
""
);
pane.add(buttons[i]);
}
}
|
本文出自 “子 孑” 博客,请务必保留此出处http://zhangjunhd.blog.51cto.com/113473/128174