![](/img/trans.png)
[英]Drawing multiple connected lines in JApplet by using paintComponent
[英]using paintComponent method in JApplet
我用Java創建了一個程序,該程序允許拖動兩個橢圓形。 現在,我想將其轉換為JApplet
因此使該類擴展了JApplet
而不是原始的JPanel
。 問題是super.paintComponent(g)
不再起作用,因為它不再是父類。
我嘗試在類中創建一個JPanel
,然后引用它,但出現錯誤: JComponent
類型的方法paintComponent(Graphics)
不可見
感謝您提出我需要做的任何事情或任何幫助。
這是我的代碼。
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);
}
});
}
}
不用修改您的JPanel
,而是保留它並創建一個新類,您的JApplet
類:
public class YourJApplet extends JApplet{
public void init(){
final JPanel panel = new YourPanel();
this.setContentPane(panel);
}
}
就是這樣-現在您的面板上發生的一切就是您的JApplet。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.