指定した色の長方形を表示する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);
}
}
パック間で実験し、フレームのサイズを明示的に指定してみました。さまざまな設定でのGUIのデフォルトの外観は次のとおりです。
プレーンなmainFrame.pack():
mainFrame.setSize(500、500):
mainFrame.setSize(500、300):
私が達成しようとしているものに最も近いのはmainFrame.setSize(500、500)ですが、さらにいくつかのコンポーネントを追加する予定なので、壊れやすいと思います。ご覧のとおり、他の2つでは、[操作]ボタンがColorSampleコンポーネントと重なっています---私が設定したレイアウトマネージャーに従わないようです。次に、ColorSampleコンポーネントのパックカット方法を確認します。希望する効果を達成するためのヒントはありますか?