gpt4 book ai didi

java - 为什么我不能在我的 JPanel 上绘画?

转载 作者:行者123 更新时间:2023-11-29 07:07:55 25 4
gpt4 key购买 nike

当我运行这个程序时,我看到的只是一个空白的 JFrame。我不知道为什么 paintComponent 方法不起作用。这是我的代码:

package com.drawing;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyPaint extends JPanel {

private void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
frame.setVisible(true);
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(50, 50, 100, 100);
}

public static void main(String[] args) {
My paintTester = new MyPaint();
paintTester.go();
}
}

最佳答案

你必须这样做

private void go() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(this);
frame.pack();
frame.setVisible(true);
}

但我会重构你的类并分离职责..

go() 不应在此类中声明

public class MyPaint extends JPanel {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(50, 50, 100, 100);
}

}

在另一个类(class)

// In another class 
public static void main(String[] args) {
JPanel paintTester = new MyPaint();
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(paintTester);
frame.pack();
frame.setVisible(true);
}

或者如果你只想在一个站点中使用这个面板,你可以采用匿名类的方法

     JFrame frame = new JFrame();
frame.add(new JPanel(){
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(50, 50, 100, 100);
}

});

关于java - 为什么我不能在我的 JPanel 上绘画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17643089/

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