如何将图形放在JPanel上? [英] How do I put graphics on a JPanel?

查看:126
本文介绍了如何将图形放在JPanel上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将图形添加到JPanel时遇到问题。如果我从panel.add(new graphics())更改该行; frame.add(new graphics());并且不要将JPanel添加到JFrame中,黑色矩形将出现在JFrame上。我只是不能让黑色的矩形出现在JPannel上,并想知道是否有人可以帮助我。

I am having a problem adding graphics to a JPanel. If I change the line from panel.add(new graphics()); to frame.add(new graphics()); and do not add the JPanel to the JFrame, the black rectangle appears on the JFrame. I just cannot get the black rectangle to appear on the JPannel and was wondering if someone could help me with this.

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

 public class Catch{

public class graphics extends JComponent{
    public void paintComponent(Graphics g){
    super.paintComponents(g);
    g.fillRect(200, 62, 30, 10);
    }
}

 public void createGUI(){
    final JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    frame.setSize(500,500);
    frame.addMouseListener(new MouseAdapter(){
        public void mouseClicked(MouseEvent e) {
            System.out.println(e.getPoint().getX());
            System.out.println(e.getPoint().getY());
        }
     });
    panel.add(new graphics());
    frame.add(panel);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE); 
}

public static void main(String[] args){
    Catch GUI= new Catch();
    GUI.createGUI();
   }
}


推荐答案

自定义组件是0x0 px。

The custom component was 0x0 px.

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

public class Catch {

    public class MyGraphics extends JComponent {

        private static final long serialVersionUID = 1L;

        MyGraphics() {
            setPreferredSize(new Dimension(500, 100));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fillRect(200, 62, 30, 10);
        }
    }

    public void createGUI() {
        final JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        panel.add(new MyGraphics());
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                Catch GUI = new Catch();
                GUI.createGUI();
            }
        });
    }
}

这篇关于如何将图形放在JPanel上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆