为什么我的JFrame什么都没显示?

时间:2014-05-08 01:18:07

标签: java swing jframe jpanel

import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon; 
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MAIN_FILE extends JPanel implements ActionListener
{

    public void paintComponent(Graphics g)
    {
        int row = 0;
        int col = 0;
        int x, y;
        int colMax = 29;
        int rowMax = 41;

        super.paintComponent(g);
        ImageIcon ground = new ImageIcon("C:\\Programming\\Ground.jpg");

        for(col = 0; col <= colMax; col++)
        {
            for(row = 0; row <= rowMax; row++)
            {
                x = row * 30;
                y = col * 30;
                ground.paintIcon(this, g, x, y);
            }
        }
        ImageIcon wall = new ImageIcon("C:\\Programming\\WallTest0000.jpg");
    }

    public static void main(String[] args)
    {
        JPanel JP = new JPanel();
        JP.setVisible(true);
        JFrame jf =  new JFrame();
        jf.setTitle("Dungeon Thing");
        jf.setSize(1230, 870);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.add(JP);
    }

2 个答案:

答案 0 :(得分:3)

添加JPanel后,您需要在revalidate()上致电repaint()JFrame

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(300,300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new JLabel("Label"));
    frame.revalidate();
    frame.repaint();
}

注意,如果您在调用setVisible之前将组件添加到框架中,就像大卫所说的那样,那么您就不需要revalidate()repaint()

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new JLabel("Label"));
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

答案 1 :(得分:-1)

致电jf.setVisible(true)后,事件派发线程将被锁定,等待某事发生。

jf.add(JP)的调用甚至在窗口处理完毕之后才会发生。

尝试在main中重新排序您的操作,先将JPanel添加到JFrame,然后setVisible(true)