지정된 색상의 사각형을 표시하는 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.setSize (500, 500) : 여기에 다양한 설정에 내 GUI의 기본 모습이다
mainFrame.setSize (500, 300) :
몇 가지 구성 요소를 더 추가 할 예정이지만 mainFrame.setSize (500, 500)이지만 가장 취약한 부분이 있습니다. 보시다시피, 다른 두 개의 "Operate"버튼은 ColorSample Component와 겹치므로 설정 한 레이아웃 관리자를 따르지 않습니다. 그리고 ColorSample Component의 팩을 어떻게 자르는 지보십시오. 내가 원하는 효과를 얻을 수있는 방법에 대한 조언?
해결 방법 : 빈'JLabel'을 사용하고 크기를 원하는 것으로 설정 한 다음'setBackground (color)'를 호출하면 어떨까요? – Rom1
와우. 정직하게 생각하지 않았습니다. 단, ColorSample은 미래에 모양을 변경해야합니다. 실제로 저는 어린 이용 보육 소프트웨어와 같은 것을 만들고 있습니다. 나는 마음에서 저것을 지킬 것이다. : D – skytreader