2012-04-14 20 views
5

tôi tạo ra một số nhãn:Làm thế nào để thay đổi khoảng cách về nhãn đu

leftLabel.setAlignmentX(Component.CENTER_ALIGNMENT); 
leftLabel.setFont(new Font(FONT, Font.PLAIN, 280)); 
leftLabel.setBorder(BorderFactory.createTitledBorder("aaa")); 
leftLabel.setText("0"); 

mà trông như thế này: enter image description here

Như bạn có thể thấy có khoảng cách lớn lên và xuống. Làm thế nào tôi có thể giảm nó?

+0

Điều gì sẽ xảy ra khi bạn không chọn cỡ chữ mà tôi có thể đọc từ dặm? – MarioDS

+0

Tôi cần thay đổi kích thước phông chữ – hudi

+0

setAlignmentY()? – Randy

Trả lời

10

Bạn cần phải tinh chỉnh các insets biên giới,

import java.awt.Component; 
import java.awt.FlowLayout; 
import java.awt.Font; 
import java.awt.Insets; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 
import javax.swing.border.TitledBorder; 

public final class TitledBorderDemo { 
    private static void createAndShowGUI(){ 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLayout(new FlowLayout()); 
     frame.add(new TitledLabel(String.valueOf(0))); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    private static class TitledLabel extends JLabel{ 
     private static final long serialVersionUID = 1L; 
     private static final String TITLE = "aaa"; 

     TitledLabel(String text){ 
      super(text); 
      setAlignmentX(Component.CENTER_ALIGNMENT); 
      setFont(new Font("Arial", Font.PLAIN, 280)); 
      setBorder(new TitledBorder(TITLE){ 
       private static final long serialVersionUID = 1L; 

       @Override 
       public Insets getBorderInsets(Component c, Insets insets){ 
        // arbitrary insets for top and bottom. 
        return new Insets(insets.top - 45, insets.left, insets.bottom - 55, insets.right); 
      }}); 

     } 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable(){ 
      @Override 
      public void run() { 
       createAndShowGUI();    
      } 
     }); 
    } 
} 

enter image description here

Hy vọng rằng điều này giúp bạn bắt đầu đi đúng hướng!

+0

wow ví dụ hay. Điều này hoạt động như một sự quyến rũ bây giờ tôi cần phải tạo ra biên giới trống rỗng – hudi

+2

leftLabel.setBorder (new EmptyBorder (Insets mới (-45, 0, -45, 0))); thx – hudi

+1

+1 cho [sscce] (http://sscce.org/). Xem thêm [ví dụ] có liên quan này (http://stackoverflow.com/a/4151403/230513). – trashgod

2

sự cố có thể nằm trong các thuộc tính của đường viền mới được tạo. Các đường viền này có insets. Đó là điều duy nhất tôi có thể nghĩ đến để ảnh hưởng đến những khoảng trống. Hãy thử gọi một phương thức trên đường viền để thay đổi các mẫu này thành [1,1,1,1].

+0

vấn đề không nằm trong biên giới tôi thêm đường viền để hiển thị khoảng trống trong JLabel – hudi

+1

@hudi Tôi sẽ xem xét kỹ hơn về quả cầu pha lê của tôi vào lần tới. – MarioDS

Các vấn đề liên quan