【问题标题】:add Graphics to JFrame将图形添加到 JFrame
【发布时间】:2016-02-23 10:45:07
【问题描述】:

我刚开始学习 Java 中的图形。 有人能解释一下 super() 和 JFrame 有什么不同吗? 当我使用 super() 时,我可以绘制图形,但我不能在 JFrame 中绘制。

public class Screen extends JFrame {
public JFrame fra = new JFrame();

private static final long serialVersionUID = 1L;
BufferedImage img=null;
public void paint(Graphics g){
    try{
        img=ImageIO.read(new File("D:/strawberry.jpg"));
    }catch (IOException e){}
    try{
        g.drawImage(img, 100,100, null);
    }catch (Exception e){}
}

public Screen()
{
    /*
    super ("kingdom");
    setSize(700,700);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    */
    // normal JFrame--------------------------------------------------
    fra.setTitle("kingdom");
    fra.setSize(600,600);
    fra.setResizable(false);
    fra.setDefaultCloseOperation(EXIT_ON_CLOSE);

    JMenuBar bar = new JMenuBar();
    JMenu file = new JMenu("File");
    JMenu edit = new JMenu("Edit");
    JMenu option = new JMenu("Option");

    JMenuItem open = new JMenuItem("Open");
    JMenuItem save = new JMenuItem("Save");
    JMenuItem exit = new JMenuItem("Exit");
    JMenuItem controlkey = new JMenuItem("Control key");
    JMenuItem sound = new JMenuItem("Sound");

    fra.setJMenuBar(bar);
    bar.add(file);
    bar.add(edit);
    bar.add(option);
    file.add(open);
    file.add(save);
    file.add(exit);
    edit.add(controlkey);
    edit.add(sound);

    fra.setVisible(true);
    //-------------------------------------------------------------
}

public static void main(String[] a){
    new Screen();
}
}

【问题讨论】:

标签: java swing graphics jframe


【解决方案1】:

在扩展JPanel 的类中进行绘图,然后将该类的一个实例设置为框架的内容窗格,或者将其添加到适合您的内容窗格中。当然,您也可以使用扩展裸 JComponent 的类来执行此操作。

该类中的绘图将在 paintComponent 的覆盖中完成。

【讨论】:

    猜你喜欢
    • 2013-07-11
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    相关资源
    最近更新 更多