gpt4 book ai didi

java - 使用绝对布局定位 GUI 组件

转载 作者:行者123 更新时间:2023-12-02 05:33:05 25 4
gpt4 key购买 nike

我知道这里已经有很多关于使用绝对布局定位组件的问题,但它们似乎没有回答我的问题。

我正在用 Java 创建一个纸牌游戏,以更好地学习 GUI 组件。我似乎了解我正在使用的各种 ActionListener 类,但我无法将组件定位在窗口中我想要的位置。

我正在尝试以类似于基本纸牌布局的格式设置窗口(甲板、弃牌堆、顶部有 4 个花色堆,下面有 7 个纸牌堆)。我的思考过程是,我需要在 JFrame 组件中使用绝对布局来手动将不同的堆栈元素放置在它们应该去的地方(也许这不是最好的方法?)。为此,我尝试使用 setLocation(x, y)setLocation(Point)setBounds(x, y, width, height) code> 等,似乎没有任何作用。我只是得到一个空白窗口。

这是我的代码尝试在窗口中手动放置组件的示例:

public class SolitaireTable extends JFrame {
public static final int SUIT_STACK_CNT = 4;
public static final int SOL_STACK_CNT = 7;
public static final Point DECK_POS = new Point(5,5);
public static final Point DISCARD_POS = new Point(73+10, 5); //73 is width of card images and 10 gives it a 5 px border to left and right
public static final Point SUIT_STACK_POS = new Point(DISCARD_POS.x + 73 + 92, 5);
public static final Point SOL_STACK_POS = new Point(DECK_POS.x, DECK_POS.y + 97 + 5); //97 is heigh of card image. 5 gives it a border of 5

public SolitaireTable()
{
setLayout(null);

ImageIcon cardImg = new ImageIcon("images/2c.gif");
Card card1 = new Card(cardImg);
add(card1);
card1.setBounds(50, 50, card1.getWidth(), card1.getHeight());

}

public static void main(String[] args)
{
SolitaireTable table = new SolitaireTable();
table.setTitle("Solitaire");
table.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table.setVisible(true);
table.setSize(800, 600);
}
}


public class Card extends JComponent {
private ImageIcon img;//current image displayed (either front or back of card)
private Point coords;
private String suit;
private int face; //use ints instead of strings to make descending face pattern calculations easier. 0 = ace, 1= 2, 10 = j, 12 = k, etc
private String color;
private boolean revealed; //whether see face or back of card
private ImageIcon frontImage; //image of card's face side (set in constructor)

public Card(ImageIcon img){
this.img = img;

}

public void moveTo(Point p) {
coords = p;
}

//================================================================= getWidth
public int getWidth() {
return img.getIconWidth();
}

//================================================================ getHeight
public int getHeight() {
return img.getIconHeight();
}
}

我已经在互联网上搜索了好几天,试图找出如何在绝对布局中定位组件,但没有找到太多。任何帮助将不胜感激。谢谢。

最佳答案

您使用 ImageIcon 创建 Card 类,但您从未在任何地方绘制该图标,因此没有任何内容可绘制并且您会得到一个空屏幕。

您需要将绘画代码添加到您的类中。请参阅 Swing 教程中关于 Custom Painting 的部分了解更多信息和工作示例。

或者您可以创建一个 JLabel 并将图标添加到标签,然后将标签添加到组件。 (如果使用此方法,请不要忘记设置卡片组件的布局管理器)。

或者您可以使用图标创建一个 JLabel。然后,您可以扩展 JLabel(而不是 JComponent)来添加自定义方法。

关于java - 使用绝对布局定位 GUI 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25331226/

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