javaswingjlabel

Jlabel size and alignment wont change


I am trying to make a rock paper scissors game for school and the title JLabel doesnt change its size or alignment. No matter what i put in title.setAlignmentX(); it doesnt change but the vertical alignment works fine.

   public class Game extends JFrame implements MouseListener, ActionListener,KeyListener {
   public static void main(String[] args) {
         Game g = new Game();


    //frame
    JLabel title = new JLabel("ROCK PAPER SCISSORS");
    title.setPreferredSize(new Dimension(300,150));
    title.setAlignmentX(400);
    title.setVerticalAlignment(SwingConstants.TOP);
    title.setForeground(Color.black);
    g.setTitle("rockpaperscissors");
    g.setVisible(true);
    g.setResizable(false);
    g.setBounds(0,0,800,800);
    g.getContentPane().setBackground(Color.green);
    g.add(title);

Solution

  • Add this line to your code: g.setLayout(new FlowLayout());.

    enter image description here

    You can read more on Layouts and how to use them here.