gpt4 book ai didi

java - 有没有办法在 jbutton 之上设置 jbutton?

转载 作者:行者123 更新时间:2023-12-02 00:18:36 28 4
gpt4 key购买 nike

我对此感到好奇,因为我们正在 Swing 中制作游戏,并且出于某种原因将 map 图 block 制作为 jButtons 而不是 jPanels。现在我们想将单位放在它们上面,这样当单位位于它们上面时, map 背景仍然显示。有人知道这是否可能吗?

最佳答案

好的,所以我不确定这确实是您正在寻找的东西以及您的应用程序当前是如何设置的,但这是一个将 JButtons 放在彼此之上的示例(如果这不是您正在寻找的东西) ,考虑发布 SSCCE 并提供更多详细信息)。还有其他替代方案和更好的方法来处理此类事情,但既然您通过 JButton 询问 JButton,这里有一个片段显示:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.basic.BasicButtonUI;

public class TestButtonGrid {

protected int x;
protected int y;

protected void initUI() throws MalformedURLException {
final JFrame frame = new JFrame();
frame.setTitle(TestButtonGrid.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridBagLayout());
ImageIcon icon = new ImageIcon(new URL("http://manhack-arcade.net/pivot/isdrawing/tile_bluerock.png"));
ImageIcon unit = new ImageIcon(new URL("http://static.spore.com/static/image/500/642/783/500642783372_lrg.png"));
ButtonUI ui = new BasicButtonUI();
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
gbc.gridx = i;
gbc.gridy = j;
JButton button = new JButton(icon);
button.setBorderPainted(false);
button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
button.setUI(ui);
button.setOpaque(false);
panel.add(button, gbc);
if (i == j) {
// Choose a layout that will center the icon by default
button.setLayout(new BorderLayout());
JButton player = new JButton(unit);
player.setPreferredSize(new Dimension(unit.getIconWidth(), unit.getIconHeight()));
player.setBorderPainted(false);
player.setUI(ui);
player.setOpaque(false);
button.add(player);
}
}
}
frame.add(panel);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
new TestButtonGrid().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}

}

关于java - 有没有办法在 jbutton 之上设置 jbutton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11452753/

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