用绝对布局定位GUI组件



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

我正在用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();
    }
}

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

你用一个ImageIcon创建了你的Card类,但是你从来没有在任何地方绘制图标,所以没有什么可以绘制的,你得到一个空的屏幕。

你需要在你的类中添加绘画代码。有关更多信息和工作示例,请参阅Swing教程中关于自定义绘画的部分。

或者创建JLabel并将Icon添加到标签中,然后将标签添加到组件中。(如果使用这种方法,不要忘记设置卡片组件的布局管理器)。

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

您是否使用绝对布局?


  • Absolute Layout is DEPRECATED .....看一下here

  • From docs:绝对布局比其他没有绝对定位的布局更不灵活,更难以维护。

  • 然而 ,如果它适合你的特殊目的,就使用它。

  • 您可以使用RelativeLayouts如下所示:设置视图的绝对位置

最新更新