So I programmed am applet that makes a ball roll in circles for ever, and I wanted to make the user decide what speed the circle should roll in, but something failed when I added the JFrame:
applet(the stop,destroy and update do not appear because they aren't important, and in start there is nothing):
public class Main extends Applet implements Runnable{
private Image I;
private Graphics GfU;
int ballX, ballY=249;
static int radius=20;
double Memory;
int changeY ,changeX=1;
Speed S = new Speed();
@Override
public void init() {
setSize(750,750);
S.setVisible(true);
}
@Override
public void run() {
while(true){
if(ballY>=250 || ballY<=-250){
changeY=0-changeY;
changeX=0-changeX;
}
ballY+=changeY;
Memory=(double)ballY/250;
Memory=Math.asin(Memory);
Memory=Math.cos(Memory);
ballX=(int)(Memory*250);
if(changeX==-1)
ballX=0-ballX;
repaint();
try {
Thread.sleep(17);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillOval(ballX-radius+250, ballY-radius+250, radius*2, radius*2);
}
public void setChangeY(int changeY) {
this.changeY = changeY;
}
public void Done(){
S.setVisible(false);
Thread BallRun = new Thread(this);
BallRun.start();
}
}
JFrame:
public class Speed extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
public Speed(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel P = new JPanel();
JLabel L = new JLabel("please enter velosity(pixels per second)");
final JTextField TF = new JTextField("00");
final Main M = new Main();
JButton B = new JButton("OK");
B.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
M.setChangeY(Integer.parseInt(TF.getText()));
M.Done();
}
});
P.add(L,BorderLayout.NORTH);
P.add(TF,BorderLayout.WEST);
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
}
thanks (and sorry if it's bothering you the lack of information)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…