[英]using paintComponent method in JApplet
I have create a program in Java which allows dragging of two oval shapes. 我用Java创建了一个程序,该程序允许拖动两个椭圆形。 Now I want to convert it to a
JApplet
so I made the class extend JApplet
instead of original JPanel
. 现在,我想将其转换为
JApplet
因此使该类扩展了JApplet
而不是原始的JPanel
。 The problem with this is that super.paintComponent(g)
does not work as it is no longer a parent class. 问题是
super.paintComponent(g)
不再起作用,因为它不再是父类。
I have tried creating a JPanel
within the class then referring to this but I get the error: The method paintComponent(Graphics)
from the type JComponent
is not visible 我尝试在类中创建一个
JPanel
,然后引用它,但出现错误: JComponent
类型的方法paintComponent(Graphics)
不可见
Any heads up on what I need to do or any help would be much appreciated thanks. 感谢您提出我需要做的任何事情或任何帮助。
Here is my code. 这是我的代码。
public class Main extends JPanel
{
private static final String TITLE = "Drag me!";
private static final int W = 640;
private static final int H = 480;
private Point origin = new Point(W / 2, H / 2);
private Point mousePt;
public Main() {
this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
this.addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent e)
{
mousePt = e.getPoint();
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter()
{
@Override
public void mouseDragged(MouseEvent e)
{
int dx = e.getX() - mousePt.x;
int dy = e.getY() - mousePt.y;
origin.setLocation(origin.x + dx, origin.y + dy);
mousePt = e.getPoint();
repaint();
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(0, origin.y, getWidth(), origin.y);
g.drawOval(origin.x, 0, origin.x, getHeight());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame(TITLE);
f.add(new Main());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
Instead of modifying your JPanel
, keep it and create a new class, your JApplet
class: 不用修改您的
JPanel
,而是保留它并创建一个新类,您的JApplet
类:
public class YourJApplet extends JApplet{
public void init(){
final JPanel panel = new YourPanel();
this.setContentPane(panel);
}
}
That's it--now whatever was going on with your panel is now your JApplet. 就是这样-现在您的面板上发生的一切就是您的JApplet。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.