2012-09-28 3 views
1

사용자 정의 JButton을 그릴 때 시스템 모양과 느낌을 확장했습니다. com.my.package.MyButtonUI* ComponentUI 클래스 (Swing 앱)에서 기본 기본 크기 (UI 다시 정의)를 설정하는 방법은 무엇입니까?

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
UIManager.put("ButtonUI", "com.my.package.MyButtonUI"); 

:

public class MyButtonUI extends BasicButtonUI { 

    public static final int BTN_HEIGHT = 24; 
    private static final MyButtonUI INSTANCE = new MyButtonUI(); 

    public static ComponentUI createUI(JComponent b) { 
     return INSTANCE; 
    } 

    @Override 
    public void paint(Graphics g, JComponent c) { 
     AbstractButton b = (AbstractButton) c; 
     Graphics2D g2d = (Graphics2D) g; 
     GradientPaint gp; 
     if (b.isEnabled()) { 
      gp = new GradientPaint(0, 0, Color.red, 0, BTN_HEIGHT * 0.6f, Color.gray, true); 
     } else { 
      gp = new GradientPaint(0, 0, Color.black, 0, BTN_HEIGHT * 0.6f, Color.blue, true); 
     } 
     g2d.setPaint(gp); 
     g2d.fillRect(0, 0, b.getWidth(), BTN_HEIGHT); 
     super.paint(g, b); 
    } 

    @Override 
    public void update(Graphics g, JComponent c) { 
     AbstractButton b = (AbstractButton) c; 
     b.setForeground(Color.white); 
     paint(g, b); 
    } 
} 

지금 내가이 버튼에 그 제약 조건을 추가하고 싶습니다 : 나는 버튼이 setPreferredSize()가 클라이언트 코드에서 호출 된 경우를 제외하고 70x24의 크기를 갖고 싶어. 어떻게해야합니까?

참고 : MyButtonUI.update() 메서드에 setPreferredSize()을 입력하면 클라이언트가 setPreferredSize()을 무시하고 모든 내 버튼의 크기가 같아집니다.

감사합니다.

는 편집 : 기욤에

감사합니다,이 같은 (MyButtonUI에) getPreferredSize()를 오버라이드 :

@Override 
public Dimension getPreferredSize(JComponent c) { 
    AbstractButton button = (AbstractButton) c; 
    int width = Math.max(button.getWidth(), BUTTON_WIDTH); 
    int height = Math.max(button.getHeight(), BUTTON_HEIGHT); 
    return new Dimension(width, height); 
} 

하고 그것을 잘 작동합니다.

답변

3

클래스의 getPreferredSize() 메소드를 재정의하십시오. 프로그래머가 자발적으로 기본 크기를 다른 것으로 설정하면 코드가 호출되지 않습니다. 이것이 JComponent의 디폴트의 동작입니다.

getPreferredSize()의 코드를 참조하십시오 :

public Dimension getPreferredSize() { 
    if (isPreferredSizeSet()) { 
     return super.getPreferredSize(); 
    } 
    Dimension size = null; 
    if (ui != null) { 
     size = ui.getPreferredSize(this); 
    } 
    return (size != null) ? size : super.getPreferredSize(); 
} 
+0

Worked. 고맙습니다. –

0

버튼의 생성자에서 기본 설정 크기를 70x24로 설정하고 해당 환경 설정을 지정하지 않는 이유는 무엇입니까? 클라이언트가 setPreferredSize를 다시 호출하면이를 재정의합니다.

+0

이 JOptionPane.showXxxDialog (...)''에서 대화 상자의 버튼으로 작동하지 않기 때문에. 고맙습니다. –

+0

또한 사용자가 다른 L & F간에 전환 할 수있는 경우 해당 UI로 돌아가서 앞으로 이동하면 설정된 기본 크기가 삭제됩니다. –