package Unit16;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Exercise16_3 extends JFrame{
private JButton jbtRight = new JButton("Right");
private JButton jbtLeft = new JButton("Left");
private JButton jbtUp = new JButton("Up");
private JButton jbDwon = new JButton("Dwon");
public Exercise16_3(){
setLayout(new BorderLayout());
JPanel p = new JPanel(new FlowLayout());
p.add(jbtUp);
p.add(jbDwon);
p.add(jbtLeft);
p.add(jbtRight);
add(BorderLayout.CENTER,new Ball());
add(BorderLayout.SOUTH,p);
Ball listener = new Ball();
jbtUp.addActionListener(listener);
jbDwon.addActionListener(listener);
jbtLeft.addActionListener(listener);
jbtRight.addActionListener(listener);
listener.y += 100;
}
public static void main(String[] args) {
Exercise16_3 frame = new Exercise16_3();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class Ball extends JPanel implements ActionListener{
private int radius = 5;
private int x = 100;
private int y = 100;
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawOval(x, y, 50, 50);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == jbtUp){
System.out.println("dwqdqdw");
y -= 20;
System.out.println(y);
repaint();
}else if(e.getSource() == jbDwon){
y += 5;
repaint();
}else if (e.getSource() == jbtLeft){
x -= 5;
repaint();
}else if(e.getSource() == jbtRight){
x += 5;
repaint();
}
}
}
}
java 我写的这个代码 圆为什么不能移动啊
答案:1 悬赏:10 手机版
解决时间 2021-03-17 16:35
- 提问者网友:無理詩人
- 2021-03-17 08:56
最佳答案
- 五星知识达人网友:思契十里
- 2021-03-17 10:36
//用了两个Ball 所以不行了 修改了一下有错误的地方,你看到就明白了为什么错了
public Exercise16_3() {
setLayout(new BorderLayout());
JPanel p = new JPanel(new FlowLayout());
p.add(jbtUp);
p.add(jbDwon);
p.add(jbtLeft);
p.add(jbtRight);
Ball listener = new Ball();
add(BorderLayout.CENTER, listener);
add(BorderLayout.SOUTH, p);
jbtUp.addActionListener(listener);
jbDwon.addActionListener(listener);
jbtLeft.addActionListener(listener);
jbtRight.addActionListener(listener);
}
public Exercise16_3() {
setLayout(new BorderLayout());
JPanel p = new JPanel(new FlowLayout());
p.add(jbtUp);
p.add(jbDwon);
p.add(jbtLeft);
p.add(jbtRight);
Ball listener = new Ball();
add(BorderLayout.CENTER, listener);
add(BorderLayout.SOUTH, p);
jbtUp.addActionListener(listener);
jbDwon.addActionListener(listener);
jbtLeft.addActionListener(listener);
jbtRight.addActionListener(listener);
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯