对于家庭作业,我必须编写一个程序,其中打开一个带有三个按钮的窗口:“删除”、“检索”和“退出”。当按下下降键时,一个圆圈从显示面板的顶部落到底部并停留在那里。当按下检索时,一条线应该从屏幕上落到圆圈上,并在视觉上将圆圈拉回屏幕顶部。
我已经写了几乎所有内容,只是无法让线条回到屏幕上,在我的代码中,只有球可以,线条保留在那里。
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();
}
}
最佳答案
代码的格式使其难以阅读,但我想我已经发现了错误:
if(e.getSource()== ticker2) {
if (y2<550) {
y2=y2+2;
}
if (y2==550) {
ticker1.stop();
y=y-2;
y2=y2-2;
}
}
你有两个if语句,编译器将按照它们的编写顺序执行它们。那么当 y2==550
那么第二个 if 语句将执行 y2=y2-2
,所以现在y2==448
。现在在下一个刻度y2<550
为 true,因此第一个 if 语句将执行 y2=y2+2
所以现在y2==550
,那么第二个 if 语句将执行 y2=y2-2
,所以现在y2==448
...并且球将继续上下移动 2 个像素。
我的建议是使用 boolean
设置为 true
当球到达屏幕底部时,第一个 if 语句仅当此 boolean 值为 false 时才会执行。
关于java - Java代码中的定时器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16309842/