gpt4 book ai didi

java - 为什么我在添加 setLayout(null) 时失去视觉效果?

转载 作者:行者123 更新时间:2023-11-30 06:14:56 27 4
gpt4 key购买 nike

我正在尝试构建一个小型垄断游戏。在这里您可以看到我遇到问题的代码部分。

public class Board extends JPanel {
private ImageIcon image;
private JLabel label;
static Player p1;
static Player p2;

public Board() {
p1 = new Player("Jack", 1);
p2 = new Player("Matt", 2);
setLayout(null);
image = new ImageIcon("board.jpg");
label = new JLabel(new ImageIcon("/Users/Onurcan/Documents/"
+ "workspace/Monopoly/src/board.jpg"));

add(p1.getToken());
add(label);
}

public class Monopoly {


public Monopoly() {
JFrame frame = new JFrame("Monopoly");
frame.setSize(1378, 900);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Board(), BorderLayout.WEST);
frame.setVisible(true);
}
}

正如您所猜到的,我在我的测试类中创建了一个新的 Monopoly 对象来运行这个程序。当我删除 setLayout(null) 时,我可以在程序中看到 token 和板。但是如果不输入 setLayout(null) 我就无法将 token 移动到起点。在创建玩家时,如果第二个参数为 1,则表示 token 是帽子,如果第二个参数为 2,则表示它是鞋子。所以我问我怎样才能不丢失 setLayout(null) 的视觉效果?或者如果不将布局设置为 null,我该如何更改我的 token 位置?

最佳答案

实际上有两个是在容器上定位组件。

  1. 糟糕的方式。使用空布局并手动设置边界或大小或位置。这是一种非常糟糕的方法,因为现代 UI 并没有足够好地反射(reflect)像素完美的东西。

  2. 定义适当的 LayoutManager(或具有自己的 LayoutManager 的多个嵌套面板)。因此所有组件的大小/位置都是根据 LayoutManager 的规则计算的。

关于java - 为什么我在添加 setLayout(null) 时失去视觉效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29530759/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com