【发布时间】:2014-08-15 17:30:55
【问题描述】:
我知道这里已经有很多关于使用绝对布局定位组件的问题,但它们似乎没有回答我的问题。
我正在使用 Java 创建一个纸牌游戏,以更好地学习 GUI 组件。我似乎了解我正在使用的各种ActionListener 类,但我无法将组件定位在我希望它们在窗口中的位置。
我正在尝试以类似于基本单人纸牌布局的格式设置窗口(套牌、弃牌堆、顶部 4 个套装堆叠和下方 7 个单人纸牌堆叠)。我的想法是,我需要在我的 JFrame 组件中使用绝对布局来手动将不同的堆栈元素放置在它们应该去的地方(也许这不是最好的方法?)。在这样做时,我尝试使用setLocation(x, y)、setLocation(Point)、setBounds(x, y, width, height) 等,但似乎没有任何效果。我只是得到一个空白窗口。
这是我尝试在窗口中手动放置组件的代码示例:
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();
}
}
我已经在互联网上搜索了几天,试图弄清楚如何在绝对布局中定位组件,但没有找到太多。任何帮助将不胜感激。谢谢。
【问题讨论】:
-
为什么选择
null布局?相同的设计可以通过适当的布局管理器来实现。 -
" 需要在我的 JFrame 组件中使用绝对布局来手动将不同的堆栈元素放置在它们应该去的地方(也许这不是最好的方法?)。"如果您知道定位游戏元素的逻辑,请将其合并到自定义
SolitaireLayoutManager..
标签: java swing layout-manager null-layout-manager