0

我正在研究 Java swing 库,我创建了第一个简单的 Hello World 示例,它在BorderLayout.CENTER区域打印一条 Hello World 消息,并在周围区域放置一些按钮。

这是我的代码:

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);
    }

}

如您所见,Hello World消息出现在BorderLayout.CENTER区域的左侧。我该怎么做才能将此文本放在 CENTER 区域的中间?

肿瘤坏死因子

安德烈亚

4

1 回答 1

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

或者

myLabel.setHorizontalAlignment(SwingConstants.CENTER);

Javadocs 是您的朋友:JLabel.setHorizo​​ntalAlignment

于 2013-09-23T15:33:56.053 回答