Question

I am studying the Java swing library and I have created this first simple Hello World example that print an Hello World message in the BorderLayout.CENTER area, and that put some buttons in the surrounding area.

This is my code:

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;

import org.jdesktop.application.SingleFrameApplication;

public class Main extends SingleFrameApplication {

    /*
    @Override
    protected void startup() {
        // TODO Auto-generated method stub
        show(new JLabel("Hello World"));
    }
    */

    public static void main(String[] args) {
        Main a = new Main();
        a.startup();
    }


    @Override protected void startup() {
        /*
        JLabel label = new JLabel();
        label.setName("label");
        show(label);
        */
        JFrame frame = new JFrame("FrameDemo");                     // Creo il frame e gli setto il titolo

        /* What happens when the frame closes: EXIT_ON_CLOSE operation exits the program when your user closes the frame.
         * Utile se il programma contiene un solo frame: chiudere il frame significa chiudere l'intera applicazione
         */
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       

        JLabel myLabel = new JLabel("Hello World !!!");

        myLabel.setPreferredSize(new Dimension(600, 300));

        // Ottengo il riquadro del contenuto e gli aggiungo la label creata in una determinata posizione:

        frame.getContentPane().add(myLabel, BorderLayout.CENTER);

        frame.getContentPane().add(new Button("North"), BorderLayout.NORTH);
        frame.getContentPane().add(new Button("South"), BorderLayout.SOUTH);
        frame.getContentPane().add(new Button("East"), BorderLayout.EAST);
        frame.getContentPane().add(new Button("West"), BorderLayout.WEST);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

}

As you can see the Hello World message appear on the left of the BorderLayout.CENTER area. What have I to do to put this text in the middle of the CENTER area?

Tnx

Andrea

Was it helpful?

Solution

JLabel myLabel = new JLabel("Hello World !!!", SwingConstants.CENTER);

or

myLabel.setHorizontalAlignment(SwingConstants.CENTER);

Javadocs is your friend: JLabel.setHorizontalAlignment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top