如何使JFrame
匹配与保存动态大小内容的JPanel
的大小相匹配?
我创建了两个简单的类片段,如果有人可以指导我完成它们。
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CanvasExample {
public static void main(String[] args) {
JPanelEx dataOut = new JPanelEx();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Title!");
f.setMinimumSize(new Dimension(200,100));
f.getContentPane().add(dataOut);
f.pack();
f.setVisible(true);
}
});
}
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JPanelEx extends JPanel {
public JPanelEx() {
super(new FlowLayout());
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hello1", 10, 10);
g.drawString("Hello2", 10, 30);
g.drawString("Hello3", 10, 50);
g.drawString("Hello4", 10, 70);
g.drawString("Hello5", 10, 90);
g.drawString("Hello6", 10, 110);
g.drawString("Hello7", 10, 130);
g.drawString("Hello8", 10, 150);
g.drawString("Hello9", 10, 170);
g.drawString("Hello10", 10, 190);
g.dispose();
}
}
我理解类似的问题可能已被多次询问,但我扫描完毕并无法得到明确的解决方案。任何帮助表示赞赏。
答案 0 :(得分:3)
您的JPanelEx
需要提供大小提示,以便布局管理系统确定应该如何布置组件以及内容所需的空间量
另外,请勿在您未创建的dispose
个上下文中致电Graphics
!
作为一个例子......
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JPanelEx());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class JPanelEx extends JPanel {
private int numElements = 10;
public JPanelEx() {
super(new FlowLayout());
}
@Override
public Dimension getPreferredSize() {
FontMetrics fm = getFontMetrics(getFont());
int width = 0;
int height = fm.getHeight() * numElements;
for (int index = 0; index < numElements; index++) {
width = Math.max(width, fm.stringWidth("Hello" + index));
}
return new Dimension(width, height);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
int y = 0;
FontMetrics fm = g.getFontMetrics();
for (int index = 0; index < numElements; index++) {
g.drawString("Hello" + index, x, y + fm.getAscent());
y += fm.getHeight();
}
}
}
}
有关布局管理器API
的更多详细信息,另请参阅Laying Out Components Within a Container