2016-06-20 75 views
0

我很新来java swing和界面创建。所以,我应该在JFrame上创建一个橙色方块。所以,我试过这个自定义小部件没有显示在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) { 

    } 
} 

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

+0

请考虑读一或两个教程。猜测从来不是学习编程的好尝试。 –

+0

@HovercraftFullOfEels谢谢。 – Adam

回答

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

+0

非常感谢@sudsparrowhawk – Adam

+0

Up投票全面解答(0: – c0der

1

创建帧后,d面板添加到它:

  frame.getContentPane().add(d); 

请参阅本教程:How to Use Panels