我有一个示例代码:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class AWT extends JFrame {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(600, 450));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.green.darker());
Button btn_1 = new Button("Button 1");
btn_1.setBackground(Color.green.darker());
btn_1.setSize(40, 100);
Button btn_2 = new Button("Button 2");
btn_2.setBackground(Color.green.darker());
btn_2.setSize(40, 100);
Button btn_3 = new Button("Button 3");
btn_3.setBackground(Color.green.darker());
btn_3.setSize(40, 100);
JPanel players = new JPanel(new GridLayout(1, 3));
players.add(btn_1);
players.add(btn_2);
players.add(btn_3);
players.setBackground(Color.green.darker());
players.setPreferredSize(new Dimension(450, 80));
JPanel game = new JPanel();
game.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
game.setBackground(Color.green);
game.setPreferredSize(new Dimension(600, 370));
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
frame.setContentPane(content);
content.add(players, BorderLayout.NORTH);
content.add(game, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
结果是给了我这样一个窗口:
alt text http://img710.imageshack.us/img710/1573/21672037.gif
,虽然它会导致更像这样的事情:
alt text http://img686.imageshack.us/img686/8948/44650673.gif
为什么它不以这种方式渲染?
最佳答案
GridLayout
忽略按钮的首选大小。代替
JPanel players = new JPanel(new GridLayout(1, 3));
和
JPanel players = new JPanel(); // default FlowLayout
附录:这是一个相关的示例,可以让布局和默认的首选尺寸完成工作。通过指定尽可能少的约束,当调用
pack()
时,外观将适应每个平台的外观。import java.awt.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class AWT extends JFrame {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel players = new JPanel();
players.add(new GameButton("Button 1"));
players.add(new GameButton("Button 2"));
players.add(new GameButton("Button 3"));
players.setBackground(GameButton.color);
JPanel game = new JPanel();
game.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
game.setBackground(Color.green);
game.setPreferredSize(new Dimension(600, 450));
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
frame.setContentPane(content);
content.add(players, BorderLayout.NORTH);
content.add(game, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private static class GameButton extends JButton {
private static final Color color = Color.green.darker();
private static final Font font = new Font("SanSerif", Font.BOLD, 20);
private String name;
public GameButton(String name) {
super(name);
this.setBackground(color);
this.setFont(font);
}
}
}