我有一个扩展JPanel的类,其中包含3个其他面板。 我想绘制3个面板。这是我的代码必须是什么样的,我做错了什么? 我执行后只有一个空框架。
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Thumbnail extends JPanel {
private JPanel bigPanel;
private JPanel panelOne;
private JPanel panelTwo;
private JPanel panelThree;
public Thumbnail() {
panelOne = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawString("writing something", 10, 10);
g.drawRect(10, 10, 50, 50);
}
};
bigPanel = new JPanel();
bigPanel.add(panelOne);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(bigPanel);
//other codes...
}
public static void main(String[] args) {
JFrame jf = new JFrame();
Thumbnail tb = new Thumbnail();
jf.add(tb);
jf.pack();
jf.setVisible(true);
}
}
答案 0 :(得分:2)
bigPanel = new JPanel(new GridLayout(3,1));
bigPanel.add(panelOne, BorderLayout.NORTH);
bigPanel.add(panelTwo, BorderLayout.CENTER);
bigPanel.add(panelThree, BorderLayout.SOUTH);
。
this.getContentPane().add(bigPanel);
修改强>
最好扩展一个JDialog,然后再添加JFrame然后添加所有面板,只是在目的是使用JDialog作为容器的情况下,否则,你的代码就可以了。
答案 1 :(得分:2)
panelOne
未向布局管理器提供任何布局信息,默认情况下,它的首选尺寸为0x0
尝试添加类似......
的内容@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
到panelOne
...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Thumbnail extends JPanel {
private JPanel bigPanel;
private JPanel panelOne;
private JPanel panelTwo;
private JPanel panelThree;
public Thumbnail() {
panelOne = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawString("writing something", 10, 10);
g.drawRect(10, 10, 50, 50);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
bigPanel = new JPanel();
bigPanel.add(panelOne);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(bigPanel);
//other codes...
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Thumbnail tb = new Thumbnail();
jf.add(tb);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
});
}
}
您可以查看Initial Threads和Laying Out Components Within a Container了解详情