gpt4 book ai didi

java - 如何将图形放在 JPanel 上?

转载 作者:搜寻专家 更新时间:2023-11-01 01:45:58 24 4
gpt4 key购买 nike

我在向 JPanel 添加图形时遇到问题。如果我从 panel.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 像素。

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

关于java - 如何将图形放在 JPanel 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10488112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com