对于家庭作业,我必须制作一个程序,其中打开一个带有三个按钮的窗口:Drop、Retrieve 和 Quit。当按下 drop 时,一个圆圈从显示面板的顶部落到底部并停留在那里。按下 Retrieve 时,一条线应从屏幕向下落到圆圈处,并在视觉上将圆圈拉回屏幕顶部。
我已经写了几乎所有我无法让线条回到屏幕上的东西,在我的代码中只有球可以,线条停留在那里。
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();
}
}