Reputation: 43
I am working on a game but have some issues with the location of the JLabels. I have this:
as my board. I am trying to do two things:
Here is my code:
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bp.removeAll();
bp.revalidate();
bp.repaint();
BufferedImage mFrame2= null;
try {
mFrame2 = ImageIO.read(new File("B2.png"));
}
catch (IOException e1) {
e1.printStackTrace();
}
bp = new BackgroundPanel(mFrame2);
bp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel hi1 = new JLabel ("Ledu");
Font fs = hi1.getFont();
hi1.setFont(fs.deriveFont(30f));
c.ipady = 0; //reset to default
c.ipadx = 0;
c.anchor = GridBagConstraints.FIRST_LINE_END;
c.insets = new Insets(10,0,0,0); //top padding
bp.add(hi1, c);
mainf.setContentPane(bp);
};
});
mainf.pack();
mainf.setVisible(true);
How would I go about positioning the label on top of the blue box, and what would I need to do to have a random number generated, similar to a dice-roll?
Upvotes: 0
Views: 89
Reputation: 324197
1.Locate Ludo on the top of the blue-ish board
Well I don't know what that means. Does it mean in the absolute center of the blue area. Or does it mean top/left, top/center, top/right?
Be more descriptive so we don't have to guess.
Right now it looks to me like the label is in the center of the entire image. This is the default behaviour of a GridBagLayout. If you don't want the image in the center then you need to play with the weightx/weighty constraints.
Read the section from the Swing tutorial on How to Use GridBagLayout for an explanation on how the constraints work.
However, I don't think this will solve your problem because you can't position components relative to the "blue" area of the larger image. I would suggest you need two images, one for the game board and one for the blue area. Then you can start to position components relatively on the blue area.
2.Insert an randomly generated number under it so that it changes each time I press an image!
Once you split the image as suggested above then you might use a vertical BoxLayout on the second image. Then you can display two labels, one with the text and the other with the number.
Upvotes: 1