0

I'm trying to create a title screen and need the title to adjust position depending on the window size. Currently it is central when I initially run the code but the JLabel does not adjust if I go into full screen or change the size at all. How can I change my code so that this isn't the case? This is my code so far for the frame:

public Frame1() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel() {
        public void paintComponent(Graphics g) {
            Image img = Toolkit.getDefaultToolkit().getImage(Frame1.class.getResource("/images/bg.jpg"));
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
        }
    };
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    int width = ((this.getWidth() / 2) - 100);
    int height = ((this.getHeight() / 2) - 38);

    JLabel lblNewLabel = new JLabel("SCOPA!");
    lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
    lblNewLabel.setFont(new Font("Book Antiqua", Font.ITALIC, 40));
    lblNewLabel.setForeground(new Color(51, 255, 255));
    lblNewLabel.setBounds(width, height, 200, 75);
    contentPane.add(lblNewLabel);
}
Jude Ball
  • 5
  • 2
  • 1
    You will have to learn about [laying out components](https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html). Currently, by setting the layout to `null`, you use absolute positioning and are responsible for setting the bounds of the child components yourself. If you want to stick with absolute positioning, you can listen to component resize events, or override the doLayout method of the container. – Reto Höhener Dec 20 '20 at 13:25
  • Give the container (here the contentPane) a GridBagLayout, and then add the JLabel to the container. Don't forget to call `pack()` on the JFrame before displaying it. – Hovercraft Full Of Eels Dec 20 '20 at 13:42
  • Please check out [these similar questions on this site](https://www.google.com/search?q=java+swing+center+label+site:stackoverflow.com) as well as this valuable search strategy – Hovercraft Full Of Eels Dec 20 '20 at 13:42

0 Answers0