对于作业分配,我必须制作一个程序,其中一个窗口以三个按钮打开: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();
}
}