gpt4 book ai didi

java - 通过将 jpanel 组件作为参数传递来绘制一个圆圈

转载 作者:搜寻专家 更新时间:2023-10-31 08:13:46 24 4
gpt4 key购买 nike

我真的很困惑如何通过将它作为参数传递来在 jpanel 上画一个圆圈..

public class test extends JPanel{

public test(JPanel jpanelcomponent) {

}
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
int width = getWidth()/2;
int height = getHeight()/2;
g.fillOval(5, 5, width, height);
}


}

最佳答案

我认为更好的设计是将通过重写 JPanelpaintComponent(..) 获得的 Graphic 对象传递给将绘制到图形对象的类

这是我做的一个例子:

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

public Test() {
initComponents();
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test();
}
});
}

private void initComponents() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final DrawingClass dc = new DrawingClass();
JPanel testPanel = new JPanel() {
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
dc.draw(g2d, getWidth(), getHeight());

}

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

frame.add(testPanel);

frame.pack();
frame.setVisible(true);
}
}

class DrawingClass {

public void draw(Graphics2D g2d, int w, int h) {
g2d.setColor(Color.BLACK);
g2d.fillOval(5, 5, w / 2, h / 2);
}
}

关于java - 通过将 jpanel 组件作为参数传递来绘制一个圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13991180/

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