gpt4 book ai didi

Java:paintComponent() Oval 未出现在 Netbeans 中

转载 作者:行者123 更新时间:2023-11-30 08:11:47 25 4
gpt4 key购买 nike

我正在尝试学习如何在java中绘制椭圆形,但是我制作的paintComponent没有被任何东西调用,并且尝试调用它只会导致更多问题。

程序运行成功,但我想要显示的图像没有显示。

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


public class TEST2{
public void paintComponent(Graphics g){
g.drawOval(70, 70, 100, 100);
}
public static void main(String[] args) {
TEST2 gui = new TEST2();
gui.setUpFrame();
}
public void setUpFrame(){
JFrame frame = new JFrame();
frame.setTitle("Images should be in this program");
frame.setSize(600,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

最佳答案

首先查看 Painting in AWT and SwingPerforming Custom Painting

为了能够在 Swing 中执行自定义绘制,您必须...

  1. 继承自基于 swing 的组件(例如 JComponentJPanel)
  2. 然后您必须重写它的 paintComponent 方法并在此方法中执行自定义绘制。
  3. 将此组件添加到可显示的内容中(例如 JFrame)

您应该确保在进行任何自定义绘画之前调用super.paintComponent

为了确保您不会犯任何(常见)错误,您应该使用 @Override 注释

举个例子...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test2 extends JPanel {

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(70, 70, 100, 100);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame();
frame.setTitle("Images should be in this program");
frame.add(new Test2());
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}

}

关于Java:paintComponent() Oval 未出现在 Netbeans 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30294509/

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