Java SWT – Label

File SWTApp.java

package vncoding;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class SWTApp {
    Shell shell;
    String lyrics =
"...\n"+
"And you'll never live until you love\n"+
"With all your heart and soul.\n"+
"It's a touch when I feel bad \n"+
"It's a smile when I get mad \n"+
"All the little things I am\n"+
"Everyday I love you...";

    public SWTApp(Display display) {
        shell = new Shell(display);
        shell.setText("Everyday I Love You");
        initUI();
        shell.pack();
        shell.setLocation(300, 300);
        shell.open();     

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }

    public void initUI() {
        Label label = new Label(shell, SWT.LEFT);
        label.setText(lyrics);
        Point p = label.computeSize(SWT.DEFAULT, SWT.DEFAULT);
        label.setBounds(5, 5, p.x+50, p.y+50);
    }
    
    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}

Giải thích:
Trong ví dụ này, lời bài hát “Every day I love you” được hiển thị trên cửa sổ.

String lyrics =
"...\n"+
"And you'll never live until you love\n"+
"With all your heart and soul.\n"+

Đây là cách chúng ta tạo ra text trên nhiều dòng.

Label label = new Label(shell, SWT.LEFT);
label.setText(lyrics);

Tạo 1 label widget; text sẽ được căn lề bên phía trái của label widget.

Point p = label.computeSize(SWT.DEFAULT, SWT.DEFAULT);
label.setBounds(5, 5, p.x+50, p.y+50);

Tính toán tọa độ để hiển thị text trong label widget.

shell.pack();

Phương thức pack() thay đổi kích thước cửa sổ đủ rộng để hiển thị toàn bộ nội dung text lên label widget.

Kết quả:

Java SWT - Label
Java SWT – Label

Be the first to comment

Leave a Reply