没有在JPanel中显示添加到另一个JPanel的图形

时间:2012-07-07 15:29:03

标签: java swing jpanel paintcomponent

将具有图形的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);
    }
}

1 个答案:

答案 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);
    }
}