對於作業分配,我必須製作一個程序,其中一個窗口以三個按鈕打開:Drop,Retrieve和Quit。當按下按鈕時,一個圓從顯示面板的頂部落到底部並停留在那裏。當按下「恢復」按鈕時,一條線應該沿着屏幕落到圓圈上,然後將圓圈直接拉回到屏幕頂部。Java代碼中的計時器問題
我已經寫了幾乎所有的東西,我只是無法讓線返回到屏幕上,在我的代碼中只有球和線保持在那裏。
import java.awt.*;
import javax.swing.*;
public class DisplayWindow extends JFrame {
private Container c;
public DisplayWindow() {
super("Display");
c = this.getContentPane();
}
public void addPanel(JPanel p) {
c.add(p);
}
public void showFrame() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
我的代碼:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DropPanel extends JPanel implements ActionListener{
Timer ticker1= new Timer(20,this);
int x=150;
int y=0;
Timer ticker2= new Timer(20,this);
int x2=175;
int y2=0;
JButton drop=new JButton("Drop");
JButton retrieve=new JButton("Retrieve");
JButton quit=new JButton("Quit");
public DropPanel(){
setPreferredSize(new Dimension(300,600));
this.add(drop); drop.addActionListener(this);
this.add(retrieve); retrieve.addActionListener(this);
this.add(quit); quit.addActionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawOval(x,y,50,50);
g.drawLine(x2,0,x2,y2);
}
public void actionPerformed (ActionEvent e){
if(e.getSource() == ticker1){
if (y<550)
y=y+2;
}
if(e.getSource() == drop){
ticker1.start();
}
if(e.getSource()== ticker2){
if (y2<550){
y2=y2+2;
}
if (y2==550) {
ticker1.stop();
y=y-2;
y2=y2-2;
}
}
if(e.getSource() == retrieve){
ticker2.start();
if(y2==550){
y2=y2-2;
}
}
if(e.getSource()==quit){
System.exit(0);
}
repaint();
}
}
這裏是驅動程序:
public class DropDriver {
public static void main(String[] args) {
DisplayWindow d = new DisplayWindow();
DropPanel b = new DropPanel();
d.addPanel(b);
d.showFrame();
}
}