0

我需要为我的 JFrame 组件使用自定义位置,我尝试查看 Java 文档中关于使用 insets 对象制作自定义位置的信息,但我不太了解...

如果您有任何方法可以在自定义位置或一个好的教程/网络/其他中添加组件,我可以轻松学习如何使用自定义位置。

4

1 回答 1

0

如果您还没有尝试过 null 布局,请查看此代码,可能会有所帮助

public static void main(String[] args) {
    SwingUtilities.invokeLater(NullLayout::new);
}

NullLayout() {
    JFrame frame = new JFrame("Basket Game");
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    for (int i = 0; i < 4; i++) {
        JPanel strip = new JPanel();
        strip.setMaximumSize(new Dimension(Integer.MAX_VALUE, 50));
        strip.setBorder(BorderFactory.createTitledBorder("Strip " + i));
        strip.add(new JLabel("Strip " + i));
        mainPanel.add(strip);
    }

    JPanel gamearea = new JPanel();
    gamearea.setLayout(null);
    mainPanel.add(gamearea);

    for (int i = 0; i < 5; i++) {
        int x = i * 100, y = i * 100;
        JPanel basket = new JPanel();
        basket.setSize(200, 50);
        basket.setLocation(x, y);
        basket.setBackground(Color.YELLOW);
        basket.add(new JLabel("x = " + x + ", y = " + y));
        gamearea.add(basket);
    }

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(mainPanel);
    frame.pack();
    frame.setResizable(false);
    frame.setSize(600, 600);

    frame.setVisible(true);
}

}

于 2017-09-26T10:11:09.960 回答