[英]How to add JButtons in a for loop?
So I am making an UI in a minecraft plugin, and it adds a button for every player, and when we click the button, it kicks the player.所以我在我的世界插件中制作了一个 UI,它为每个玩家添加了一个按钮,当我们点击按钮时,它会踢玩家。 This is the for loop:这是for循环:
for (final Player p : Bukkit.getOnlinePlayers())
{
System.out.println("Looping.");
final JButton b = new JButton();
b.setName(p.getName());
b.setText(p.getName());
b.setToolTipText("Kick " + b.getText());
b.setBackground(Color.GREEN);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!b.getBackground().equals(Color.RED))
{
Bukkit.getScheduler().runTask(main, new Runnable() {
public void run() {
Bukkit.getPlayer(b.getText()).kickPlayer(jtf.getText());
b.setBackground(Color.RED);
}
});
}
}
});
System.out.println("Button added.");
f.add(b);
}
And let's say there are 2 players in the server, asd and dsa .假设服务器中有 2 个玩家, asd和dsa 。 When this for loop runs, it just adds button for asd , but prints Button added (and Looping ) two times.当这个 for 循环运行时,它只是为asd添加按钮,但打印Button added (and Looping ) 两次。
( f is a public static JFrame , and jtf is a public static JTextField ) ( f是公共静态 JFrame ,而jtf是公共静态 JTextField )
So... Why is it not working?那么......为什么它不起作用?
It happens because the defult LayoutManager
is BorderLayout
, so the method add(JComponent comp)
puts the JComponent
in the center of the JFrame
, and the JComponent
fills the entire JFrame
.这是因为该defult LayoutManager
是BorderLayout
,所以方法add(JComponent comp)
放JComponent
在中心JFrame
和JComponent
充满整个JFrame
。 Use the method f.setLayout(new GridLayout(number_of_players, 1));
使用方法f.setLayout(new GridLayout(number_of_players, 1));
, it will split the JFrmae
to rows as the number of your players, so a multiply number of JComponents
could be displayed. ,它会将JFrmae
拆分为行作为您的玩家数量,因此可以显示成倍数的JComponents
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.