I know there are many questions on here already about positioning components using absolute layout, but they don't seem to answer my questions.
I'm working on creating a Solitaire game in java to better learn GUI components. I seem to understand the various ActionListener
classes I'm using, but I'm having trouble positioning components where I want them in the window.
I'm trying to set up the window in a format that resembles the basic solitaire layout (deck, discard pile, 4 suit stacks at the top and 7 solitaire stacks below them). My thought process was that I'd need to use an absolute layout in my JFrame component to manually place the different stack elements where they should go (maybe this isn't the best approach?). In doing so, I've tried using setLocation(x, y)
, setLocation(Point)
, setBounds(x, y, width, height)
, etc and nothing seems to work. I just get a blank window.
Here's an example of my code trying to manually place components in the window:
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();
}
}
I've been scouring the internet for days trying to figure out how to position components in an absolute layout but haven't found much. Any help would be greatly appreciated. Thanks.