Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào chúng ta có thể xoay một văn bản JLabel trong Java?


A JLabel là một lớp con của JComponent lớp và một đối tượng của JLabel cung cấp hướng dẫn văn bản hoặc thông tin trên GUI. JLabel có thể hiển thị một dòng văn bản chỉ đọc, một hình ảnh hoặc cả văn bản và một hình ảnh . A JLabel có thể tạo PropertyChangeListener một cách rõ ràng giao diện.

Theo mặc định, JLabel có thể hiển thị văn bản ở vị trí ngang và chúng tôi có thể xoay văn bản JLabel bằng cách triển khai xoay () phương pháp của Graphics2D bên trong paintComponent ().

Cú pháp

public abstract void rotate(double theta, double x, double y)

Ví dụ

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class RotateJLabelTest extends JFrame {
   public RotateJLabelTest() {
      setTitle("Rotate JLabel");
      JLabel label = new RotateLabel("TutorialsPoint");
      add(label, BorderLayout.CENTER);
      setSize(400, 300);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   private class RotateLabel extends JLabel {
      public RotateLabel(String text) {
         super(text);
         Font font = new Font("Verdana", Font.ITALIC, 10);
         FontMetrics metrics = new FontMetrics(font){};
         Rectangle2D bounds = metrics.getStringBounds(text, null);
         setBounds(0, 0, (int) bounds.getWidth(), (int) bounds.getHeight());
      }
      @Override
      public void paintComponent(Graphics g) {
         Graphics2D gx = (Graphics2D) g;
         gx.rotate(0.6, getX() + getWidth()/2, getY() + getHeight()/2);
         super.paintComponent(g);
      }
   }
   public static void main(String[] args) {
      new RotateJLabelTest();
   }
}

Đầu ra

Làm thế nào chúng ta có thể xoay một văn bản JLabel trong Java?