将具有图形的JPanel
添加到JFrame
时,它运行正常。但是当我尝试添加JPanel
时,我添加了另一个JPanel
图片,但它没有显示在JFrame
中。请参阅下面的代码
package sample;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
public static void main(String[] args) {
new Main();
}
public Main(){
setTitle("Sample");
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new SamplePanel2());
}
}
class SamplePanel2 extends JPanel{
public SamplePanel2(){
add(new JButton("Hi"));
add(new SamplePanel());
}
}
class SamplePanel extends JPanel {
public SamplePanel(){
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("HHHHHHHHHHHH", 100, 100);
}
}
答案 0 :(得分:4)
请注意Main
类的构造函数,使其成为您的习惯,以遵循此示例中所示的顺序。首先向JFrame
添加组件,然后只调用pack(), setSize() or setVisible(...)
之类的调用,而不是之前。
始终将其视为您的习惯,无论何时覆盖paintcomponent()
方法,都要覆盖getPreferredSize()
方法。
并且总是把像pack()/setVisible(...)
这样的调用放在EDT - 事件调度线程中。有关该主题的更多详细信息,请阅读Concurrency in Swing。
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
public static void main(String[] args) {
new Main();
}
public Main(){
setTitle("Sample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(new SamplePanel2());
pack();
setVisible(true);
}
}
class SamplePanel2 extends JPanel{
public SamplePanel2(){
add(new JButton("Hi"));
add(new SamplePanel());
}
}
class SamplePanel extends JPanel {
public SamplePanel(){
}
@Override
public Dimension getPreferredSize()
{
return (new Dimension(300, 300));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("HHHHHHHHHHHH", 100, 100);
}
}