6

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

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();
   }
}
4

2 回答 2

9

自定义组件为 0x0 像素。

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();
            }
        });
    }
}
于 2012-05-07T20:23:45.897 回答
1

这是您可以查看的内容:

import javax.swing.*;
import java.awt.*;
public class GraphicsOnJPanel extends JFrame
{
    public GraphicsOnJPanel ()
    {
        setSize (Toolkit.getDefaultToolkit ().getScreenSize ());
        setResizable (false);
        setContentPane (new JPanel ()
        {
            public void paint (Graphics g)
            {
                g.setColor (Color.RED);
                g.fillRect (100, 100, 100, 100);
             }
         }
    );
          setVisible (true);
}


    public static void main (String args[])
    {
        new GraphicsOnJPanel ();
    }
}

也许这有用?

于 2013-03-29T02:52:32.447 回答