未示出的JPanel图形被添加到另一个的JPanel(Not showing graphics in

2019-06-26 03:06发布

当添加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);
    }
}

Answer 1:

请不要观看的构造Main类别,使这个你习惯中按照如图所示在这个例子中的顺序。 首先将组件添加到JFrame则仅做出这样的呼叫pack(), setSize() or setVisible(...)不是在这之前,。

务必使你的习惯中,无论何时你重写paintcomponent()方法,覆盖getPreferredSize()方法为好。

始终把像调用pack()/setVisible(...)的EDT内-事件调度线程。 请仔细阅读在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);
    }
}


文章来源: Not showing graphics in JPanel which is added to another JPanel