自定义窗口小部件未显示在JFrame上

时间:2016-06-20 03:42:21

标签: java swing

我对java swing和界面创建非常陌生。所以,我应该在JFrame上创建一个橙色方块。所以,我试过这个

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Demo extends JPanel {
    public void paintComponent(Graphics g) {
        g.setColor(Color.orange);
        g.fillRect(20,50,100,100);
    }
}
public class Example implements ActionListener {
    public void atom() {
        Demo d = new Demo();
        JFrame frame = new JFrame();        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,200);
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        Example e = new Example();
        e.atom();
    }
    public void actionPerformed(ActionEvent e) {

    }
}

但广场没有出现,我无法找到,为什么会这样。任何人都可以指导我。

2 个答案:

答案 0 :(得分:2)

你忘了添加" d"小部件到框架的内容窗格。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Demo extends JPanel {
    public void paintComponent(Graphics g) {
        g.setColor(Color.orange);
        g.fillRect(20,50,100,100);
    }
}
public class Example implements ActionListener {
    public void atom() {
        Demo d = new Demo();
        JFrame frame = new JFrame();  
        frame.getContentPane().add(d); //      
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,200);
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        Example e = new Example();
        e.atom();
    }
    public void actionPerformed(ActionEvent e) {

    }
}

More information

答案 1 :(得分:1)

创建框架后,将d面板添加到其中:

         frame.getContentPane().add(d);

请参阅本教程:How to Use Panels

相关问题