2

So I am new in Java, and I want to create a menu. The first thing I have to do is a JLabel with the game name in it. I did everything, but I can't figure out how to center the JLabel to be in the center of the screen, and not on the side

My friend gave me a code, but It doesn't work very well, here it is:

public static String gameName = "Game Name Placeholder";
JLabel label = new JLabel(gameName);
        label.setBounds(this.getWidth()/2-100,this.getHeight()/2-150,1000,100);
        label.setFont(new Font("Dialog", Font.PLAIN, 34));

panel.add(label);
add(panel);

And here you can see clearly it is not centered:

https://i.stack.imgur.com/HTeoX.png

Sorry, I may look dumb. I just started learning Java 2 days ago on my own, so if someone could help me out I would appreciate it a lot!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 4
    You should look into [Java Swing Layout Managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) and use a layout manager to do the job instead of manually setting the bounds of your components. – maloomeister Aug 03 '20 at 08:26
  • I tried using panel.add(label, BorderLayout.PAGE_START); but now the label wont show, did i mess something up? All i did was change that – IlIkeMen2643 Aug 03 '20 at 08:46
  • I'm going to assume `panel` is a `JPanel` you created. Did you create a new `BorderLayout` and set it on your JPanel? Otherwise this won't work. `JPanel`s default layout is `FlowLayout` as far as I remember. – maloomeister Aug 03 '20 at 09:55
  • For your use case, maybe use a [BoxLayout](https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html). [Here](https://docs.oracle.com/javase/tutorial/uiswing/examples/layout/BoxLayoutDemoProject/src/layout/BoxLayoutDemo.java) is some simple demo code for the same thing you try to do. – maloomeister Aug 03 '20 at 10:01
  • Use `SwingConstants.CENTER` for the second argument when instantiating the `JLabel`. See: https://stackoverflow.com/questions/12589494/align-text-in-jlabel-to-the-right – Mr. Polywhirl Aug 03 '20 at 16:18
  • 2
    Don't use a null layout!!! The setBounds(...) statement implies that you are trying to manually position components. Don't! Swing was designed to be used with layout manager as has already been suggested. If you still have problems then post a proper [mre] demonstrating the problem. . – camickr Aug 03 '20 at 16:18

0 Answers0