我制作了一个显示指定颜色矩形的 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);
}
}
我尝试在 pack 和明确指定框架的大小之间进行试验。以下是我的 GUI 在各种设置下的默认外观:
普通 mainFrame.pack():
mainFrame.setSize(500, 500):
mainFrame.setSize(500, 300):
最接近我打算实现的是 mainFrame.setSize(500, 500) 虽然,因为我计划添加更多组件,我预计它会很脆弱。如您所见,在另外两个中,“操作”按钮与 ColorSample 组件重叠——就像它没有遵循我设置的布局管理器一样。然后看看 ColorSample 组件是如何打包的。关于如何达到我想要的效果的任何提示?