2016-10-23 21 views
0

Java에서 프로젝트를 만드는 데 Java Swing 및 MigLayout (유용한 도구!)을 사용하고 있는데 문제가 있습니다.MigLayout 및 JLabel 파생물이 비정상적인 동작을 보이고 레이아웃을 따르지 않습니다.

모든 문자열을 최대한 크게 표시하려면 구성 요소의 크기에 따라 글꼴을 변경하는 JLabel의 하위 클래스를 만들었습니다. 제공 할 예제에서 코드를 첨부합니다.

프로젝트가 정말 크고 중첩 된 패널이 많으며, 메인 윈도우의 내용을 즉시 변경하여 이후의 모든 내용을 확인합니다.

그러나 MigLayout 내에서 구성 요소의 셀 처리를 사용하려고 시도하면 오류가 발생합니다.

같은 레이아웃으로 같은 제약 조건을 사용하지만 내 맞춤 레이블을 사용하는 대신 일반 JLabel을 사용하면 모든 것이 매력처럼 작동합니다. 여기

예의 요지 :

https://gist.github.com/bracco23/c47975ede0d857ac3b134f197c4371a2

코드는 두 파일이다

  • JAdaptiveLabel.java 단마다 텍스트 최적 폰트 크기를 계산 맞춤 컴포넌트 필요시 또는 변경 될 수 있습니다.

  • 모의 예입니다. 사용자 정의를 변경하면 내 구성 요소와 일반 JLabel간에 전환하여 차이점을 볼 수 있습니다. 의도 한 레이아웃은 일반 JLabel을 사용하는 레이아웃입니다.

아무도 나에게 무엇이 잘못되었는지, 어떻게 해결할 수 있습니까?

답변

0

좋아, 열심히 노력한 후에 해결되었습니다.

테스트를 마친 후 JAdaptiveLabel에서 somethig가 잘못되었다는 결론에 도달했습니다. 그래서 다른 버전을 온라인으로 검색하여 내 구현인지 적응성 자체인지 확인했습니다.

나는이 대답에 온 : 그것이 내 구현이 도청 그래서 그것이 작동으로 @Warren K

나는 자신의 클래스를 사용했다.

나는 자신의 버전에서 시작하여 크기 조정 알고리즘을 변경했는데, 이는 반복적 인 크기 (크기가 완벽해질 때까지 크기가 변함)와 제 수학이 수학적 이었기 때문에 (크기를 조정하고 완벽한 크기를 계산했습니다).

효과가있었습니다. 이제 레이아웃을 올바르게 배치하고 창 크기를 조정하면 레이블의 글꼴 크기가 바뀝니다. 여기에 코드

수정 : 당신은 내가 준 예를 들어 내부 클래스의 버전을 사용하는 경우

package it.bracco23.util; 

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ComponentAdapter; 
import java.awt.event.ComponentEvent; 

// Improved version of http://java-sl.com/tip_adapt_label_font_size.html 

public class JAdaptiveLabel extends JLabel { 

    private Graphics g; 
    private boolean init = false; 

    public JAdaptiveLabel(String text, Icon icon, int horizontalAlignment) { 
     super(text, icon, horizontalAlignment); 
     init(); 
    } 

    public JAdaptiveLabel(String text, int horizontalAlignment) { 
     super(text, horizontalAlignment); 
     init(); 
    } 

    public JAdaptiveLabel(String text) { 
     super(text); 
     init(); 
    } 

    public JAdaptiveLabel(Icon image, int horizontalAlignment) { 
     super(image, horizontalAlignment); 
     init(); 
    } 

    public JAdaptiveLabel(Icon image) { 
     super(image); 
     init(); 
    } 

    public JAdaptiveLabel() { 
     init(); 
    } 



    protected void init() { 
     addComponentListener(new ComponentAdapter() { 
      public void componentResized(ComponentEvent e) { 
       adaptLabelFont(JAdaptiveLabel.this); 
      } 
     }); 
     init = true; 
    } 

    protected void adaptLabelFont(JLabel l) { 
     if (g==null) { 
      return; 
     } 

     Rectangle r = l.getBounds(); 
     Insets ins = l.getInsets(); 
     r.x   = 0;  
     r.y   = 0;  
     Font f  = l.getFont(); 
     Dimension dim = getTextSize(l, f); 
     //0.9f is a scale factor to don't let the text take too much space 
     //without it will work, but the text may appear to close to the border 
     float xFactor = ((r.width - ins.left - ins.right) * 0.9f)/dim.width; 
     float yFactor = ((r.height - ins.top - ins.bottom) * 0.9f)/dim.height; 

     /*the next lines assure the scaling factors are not zero (can happen) 
     and are different enough from 1. Without this last check, it might happen 
     that the font starts to cycle between two sizes. */ 
     xFactor = (xFactor != 0 && Math.abs(xFactor - 1)>0.1) ? xFactor : 1; 
     yFactor = (yFactor != 0 && Math.abs(xFactor - 1)>0.1) ? yFactor : 1; 
     float fontSize = f.getSize() * Math.min(xFactor, yFactor); 

     setFont(f.deriveFont(f.getStyle(), fontSize)); 
     repaint(); 
    } 

    private Dimension getTextSize(JLabel l, Font f) { 
     Dimension size = new Dimension(); 
     FontMetrics fm = g.getFontMetrics(f); 
     size.width  = fm.stringWidth(l.getText()); 
     size.height  = fm.getHeight(); 
     return size; 
    } 

    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     this.g=g; 
    } 

     @Override 
    public void setText(String text) { 
     super.setText(text); 
     if(init){ 
      adaptLabelFont(this); 
     } 
    } 

} 

, 모든 작동합니다!

P. 또한 레이블 크기를 조정하거나 내용을 변경할 때 크기를 변경해야하므로 setText에서 크기 조정 메서드에 대한 호출을 추가했습니다.