我是新来的,所以我真的瞎了。因此,我想在单击开始按钮后添加一个移动球。但是我不知道如何。下面的代码是我遇到的问题。特别是在公共场合无效Actionperformed()。
我也尝试了几种方法来达到预期的结果,但我一无所获。 这是代码:
public static JFrame f1;
public JFrame f2;
public JLabel lstr, labu;
public JPanel screen;
public JButton btstr, btabu;
public Timer t;
public menu() {
f1.add(lstr = createLabel("Welcome to Quizzer Ball!", 227, 25, 400, 30));
f1.add(btstr = createButton("Start", 250, 50, 100, 30 ));
f1.add(btabu = createButton("About Us", 250, 90, 100, 30 ));
btstr.addActionListener(this);
btabu.addActionListener(this);
}
public JButton createButton(String string, int i, int j, int k, int l) {
// TODO Auto-generated method stub
JButton btn = new JButton(string);
btn.setBounds(i, j, k, l);
return btn;
}
public JLabel createLabel(String string, int i, int j, int k, int l) {
// TODO Auto-generated method stub
JLabel lb = new JLabel(string);
lb.setBounds(i, j, k, l);
return lb;
}
game gamescrn = new game();
public JPanel createPanel(String string, int i, int j, int k, int l) {
// TODO Auto-generated method stub
JPanel panel = new JPanel();
panel.setBounds(i, j, k, l);
btstr.setVisible(false);
btabu.setVisible(false);
lstr.setVisible(false);
gamescrn.paint(getGraphics());
return screen;
}
public static void main (String[]args) {
f1 = new JFrame ("Quizzer Ball");
f1.setLayout(null);
f1.setSize(600, 400);
f1.setVisible(true);
new menu();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==btstr) {
createPanel();
}
}
}
game.java在哪里
Timer t = new Timer(10, this);
int x = 0, y = 0, velX = 2, velY = 2;
Random r = new Random();
public Ball ball = new Ball(this);
public void paint (Graphics g) {
super.paint(g);
g.setColor(Color.red);
ball.paint(g);
t.start();
}
public void move() {
ball.move();
}
class Ball{
public int x = r.nextInt(540), y = r.nextInt(320), velX=2, velY=2;
public game anim;
public Ball(game anim) {
this.anim = anim;
}
public void move() {
if (x<0 || x>540) {
velX = -velX;
}
if (y<0||y>320) {
velY = -velY;
}
x += velX;
y += velY;
}
public void paint (Graphics g) {
g.fillOval(x, y, 40, 40);
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
move();
repaint();
}
}
我希望createPanel代码段位于actionPerformed内部。但它不会首先运行。