【发布时间】:2014-04-17 00:06:28
【问题描述】:
我正在编写一个取自电视节目《办公室》的节目,当时他们正坐在会议室里,看着屏幕上弹跳的 DVD 徽标试图冲到角落里。正方形应该在碰到边缘时改变颜色。 但是,我遇到了一些问题。
问题一:Square 有时会从边缘反弹。其他时候它会下沉,我不知道为什么。
问题二:我不知道如何改变方块碰到边缘时的颜色。
问题三:我正在尝试学习如何制作全屏 JFRAME。不仅在我的屏幕上全屏,而且在任何人的屏幕上。
代码已发布到在线 IDE 以方便阅读。可以找到HERE
否则,如果您太忙于该链接。这里贴在下面。
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BouncingMischievousSquare extends JPanel implements ActionListener {
private static final int SQUARE_SIZE = 40;
private static final int SPEED_OF_SQUARE = 6;
private int xPosit, yPosit;
private int xSpeed, ySpeed;
BouncingMischievousSquare(){
//speed direction
xSpeed = SPEED_OF_SQUARE;
ySpeed = -SPEED_OF_SQUARE;
//a timer for repaint
//http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
Timer timer = new Timer(100, this);
timer.start();
}
public void actionPerformed(ActionEvent e){
//Screensize
int width = getWidth();
int height = getHeight();
xPosit += xSpeed;
yPosit += ySpeed;
//test xAxis
if(xPosit < 0){
xPosit = 0;
xSpeed = SPEED_OF_SQUARE;
}
else if(xPosit > width - SQUARE_SIZE){
xPosit = width - SQUARE_SIZE;
xSpeed = -SPEED_OF_SQUARE;
}
if(yPosit < 0){
yPosit = 0;
ySpeed = SPEED_OF_SQUARE;
}
else if(yPosit > height - SQUARE_SIZE){
xPosit = height - SQUARE_SIZE;
xSpeed = -SPEED_OF_SQUARE;
}
//ask the computer gods to redraw the square
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(xPosit, yPosit, SQUARE_SIZE, SQUARE_SIZE );
}
}
主类
import javax.swing.*;
public class MischievousMain {
public static void main(String[] args) {
JFrame frame = new JFrame("Bouncing Cube");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// mischievous square input
frame.add(new BouncingMischievousSquare());
frame.setVisible(true);
}
}
无论如何,感谢您花时间阅读我的代码。值得赞赏。我真的对解决这个问题的不同方法很感兴趣。
【问题讨论】:
标签: java swing jtable jframe jpanel