我有一个JPanel,我想设置它的宽度,但是让高度由它的内容决定。包含的JPanel应该保持其大小。如果我在“内容”中放置多行文本,它当然会自动跨越更多的高度。如果所需的高度超过容器的可用高度,滚动条将是理想的(但这不太重要)。
这可能真的很简单,但我就是搞不懂。。。
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JPanelContentSizedDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(JPanelContentSizedDemo::new);
}
JPanelContentSizedDemo() {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setResizable(false);
frame.setLayout(null);
// the containing panel
JPanel panelContainer = new JPanel();
panelContainer.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panelContainer.setBounds(50, 50, 300, 200);
panelContainer.setBackground(Color.RED);
frame.add(panelContainer);
// what to do...
//panelContainer.setLayout(new BoxLayout(panelContainer, BoxLayout.Y_AXIS));
panelContainer.setLayout(new BorderLayout());
// the panel that I want to size to its content
JPanel dialog = new JPanel(new BorderLayout());
dialog.setBackground(Color.GREEN);
dialog.setBorder(BorderFactory.createLineBorder(Color.BLACK));
dialog.add(new JLabel("This is some content!"));
panelContainer.add(dialog);
frame.setVisible(true);
}
}