[英]How to make my JComponent conform to JFrame.pack and Layout Managers?
我创建了一个显示指定颜色矩形的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之间进行试验并明确指定帧的大小。 以下是我在各种设置上的默认外观:
Plain mainFrame.pack():
mainFrame.setSize(500,500):
mainFrame.setSize(500,300):
最接近我打算实现的是mainFrame.setSize(500,500),但是,由于我计划添加更多组件,我预计它将是脆弱的。 如您所见,在另外两个中,“操作”按钮与ColorSample组件重叠---就像它没有遵循我设置的布局管理器一样。 然后看看ColorSample组件的包装切割方式。 关于如何达到我想要的效果的任何提示?
pack()
使用组件的getPreferredSize()
。 因此,只需返回矩形的所需大小,大小将在LayoutManager
。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.