我需要构建二十一点游戏作为学习项目。
我想用 SWING GUI 构建它。我需要它只是将屏幕分成两部分,然后能够使用相对于指定部分的绝对 (x, y) 位置插入元素(在我的情况下,它是带有签名 ImageIcon 的扩展 JButton)。
像这样的东西:
我是在 Android 下开发的,在那里你可以以非常简单的方式处理元素,我对 SWING 感到迷茫。没有 AbsoluteLayout 或类似的东西吗?
这是我的几次尝试的一个例子:
public void run() {
// TODO Auto-generated method stub
JFrame jFrame = new JFrame("Blackjack");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = jFrame.getContentPane();
Insets insets = pane.getInsets();
URL url = ClassLoader.getSystemClassLoader().getResource("10_of_clubs.png");
BufferedImage bi = null;
try {
bi = ImageIO.read(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Image resizedImage = bi.getScaledInstance(128, 186, 0);
ImageIcon icon = new ImageIcon(resizedImage);
ImageButton imgButton = new ImageButton(icon);
imgButton.setPreferredSize(new Dimension(128, 186));
ImageButton imgButton2 = new ImageButton(icon);
imgButton.setPreferredSize(new Dimension(128, 186));
pane.setLayout(new GridBagLayout());
JPanel headPanel = new JPanel();
JPanel headPanel2 = new JPanel();
GridBagConstraints cns = new GridBagConstraints();
cns.gridx = 0;
cns.gridy = 0;
cns.weightx = 0.5;
cns.weighty = 0.2;
cns.anchor = GridBagConstraints.FIRST_LINE_START;
cns.fill = GridBagConstraints.BOTH;
headPanel.setBackground(Color.RED);
headPanel.add(imgButton, cns);
GridBagConstraints cns2 = new GridBagConstraints();
cns2.gridx = 0;
cns2.gridy = 0;
cns2.weightx = 0.5;
cns2.weighty = 0.2;
cns2.anchor = GridBagConstraints.FIRST_LINE_START;
cns2.fill = GridBagConstraints.CENTER;
headPanel2.setBackground(Color.BLUE);
headPanel2.add(imgButton2, cns2);
pane.add(headPanel);
pane.add(headPanel2);
jFrame.setSize(800, 600);
jFrame.setVisible(true);
jFrame.setLocationRelativeTo(null);
}
我得到的就是:
肿瘤坏死因子。