java将图片放到panel上_java – 如何将图形放在JPanel上?

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

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.

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

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值