2011-08-31 5 views
2

지정된 색상의 사각형을 표시하는 JComponent를 만들었습니다. (이 효과를 얻는 다른 방법을 찾지 못했습니다). 문제는, 예상대로 JFrame.pack()과 Layout Manager를 따르지 않는다는 것입니다.내 JComponent가 JFrame.pack 및 레이아웃 관리자를 준수하도록 만드는 방법은 무엇입니까?

코드 :

import java.awt.*; 
import javax.swing.*; 

public class FooRunnable implements Runnable{ 

private class ColorSample extends JComponent{ 

    private Color sampleColor; 
    private int width, height; 

    public ColorSample(int rgb, int w, int h){ 
     sampleColor = new Color(rgb); 
     width = w; 
     height = h; 
    } 

    public Dimension getSize(){ 
     return new Dimension(width, height); 
    } 

    public int getWidth(){ 
     return width; 
    } 

    public int getHeight(){ 
     return height; 
    } 

    public boolean isDisplayable(){ 
     return true; 
    } 

    public void paintComponent(Graphics g){ 
     g.setColor(sampleColor); 
     g.fillRect(0, 0, width, height); 
    } 

} 

public void run(){ 
    JFrame mainFrame = new JFrame(); 
    //mainFrame.setSize(500, 300); 
    Container mainContent = mainFrame.getContentPane(); 
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    mainContent.setLayout(new BoxLayout(mainContent, BoxLayout.PAGE_AXIS)); 

    JPanel specifyFilePanel = new JPanel(); 
    specifyFilePanel.setLayout(new BoxLayout(specifyFilePanel, BoxLayout.LINE_AXIS)); 
    JLabel filenameLabel = new JLabel("File:  "); 
    JButton browseButton = new JButton("Browse..."); 
    specifyFilePanel.add(Box.createHorizontalStrut(8)); 
    specifyFilePanel.add(filenameLabel); 
    specifyFilePanel.add(browseButton); 
    specifyFilePanel.add(Box.createHorizontalStrut(8)); 

    JPanel colorStatusPanel = new JPanel(); 
    colorStatusPanel.setLayout(new BoxLayout(colorStatusPanel, BoxLayout.Y_AXIS)); 
    JLabel statusLabel = new JLabel(""); 
    JButton roll = new JButton("Operate"); 
    colorStatusPanel.add(new ColorSample(Color.red.getRGB(), 50, 100)); 
    colorStatusPanel.add(statusLabel); 
    colorStatusPanel.add(roll); 

    mainContent.add(Box.createVerticalStrut(5)); 
    mainContent.add(specifyFilePanel); 
    mainContent.add(Box.createVerticalStrut(10)); 
    mainContent.add(colorStatusPanel); 
    mainContent.add(new JPanel()); 
    mainFrame.pack(); 
    mainFrame.setVisible(true); 
} 

} 

나는 팩 사이에 실험을 명시 적으로 프레임의 크기를 지정했습니다.

일반 mainFrame.pack() : mainFrame.pack()

mainFrame.setSize (500, 500) : 여기에 다양한 설정에 내 GUI의 기본 모습이다 enter image description here

mainFrame.setSize (500, 300) : mainFrame.setSize(500, 300)

몇 가지 구성 요소를 더 추가 할 예정이지만 mainFrame.setSize (500, 500)이지만 가장 취약한 부분이 있습니다. 보시다시피, 다른 두 개의 "Operate"버튼은 ColorSample Component와 겹치므로 설정 한 레이아웃 관리자를 따르지 않습니다. 그리고 ColorSample Component의 팩을 어떻게 자르는 지보십시오. 내가 원하는 효과를 얻을 수있는 방법에 대한 조언?

+1

해결 방법 : 빈'JLabel'을 사용하고 크기를 원하는 것으로 설정 한 다음'setBackground (color)'를 호출하면 어떨까요? – Rom1

+0

와우. 정직하게 생각하지 않았습니다. 단, ColorSample은 미래에 모양을 변경해야합니다. 실제로 저는 어린 이용 보육 소프트웨어와 같은 것을 만들고 있습니다. 나는 마음에서 저것을 지킬 것이다. : D – skytreader

답변

4

LayoutManagers는 구성 요소의 크기와 위치를 자유롭게 지정할 수 있으므로 구성 요소는 강제로 설정할 수 없으며 getXXSize (XX == min/pref/max) 메서드에서만 힌트를 제공합니다. 그래서 할 수있는 최선의 구성 요소 구현은 이상적으로

  • 는 서로 다른 크기
  • 코드 조각에만

    public class MyBox extends JComponent { 
        Dimension boxSize; 
    
        public void setBoxSize(Dimension box) { 
         this.boxSize = new Dimension(box); 
         ... 
        } 
    
        @Override 
        public void paintComponent(Graphics g) { 
         super.paintComponent(g); 
         // position the box in the actual size 
         // and paint it 
        } 
    
        @Override 
        public Dimension getPreferredSize() { 
         return getBoxSize(); 
        } 
        @Override // same for min/max 
        public Dimension getM...Size({ 
         return getBoxSize(); 
        } 
    } 
    
    에 대처하기 위해 paintComponent에 구현 원하는 크기를 모든 getXXSize을 구현하고 반환

    • 입니다
    +0

    +1 완료. – trashgod

    +0

    코드 스 니펫을 보내 주셔서 감사합니다. :디 – skytreader

    4

    pack()은 구성 요소의 getPreferredSize()을 사용합니다. 그래서 사각형의 원하는 크기를 반환하면 크기는 LayoutManager에서 사용됩니다.

    +0

    ... 두들겨 맞고 너무 짧아서 :-) – kleopatra

    +0

    +1 간결함. – trashgod