Fri*_*lin 0 java swing jtable jpanel jframe
我正在写一个从电视节目THE OFFICE拍摄的节目,当他们坐在会议室里,看着屏幕上弹跳的DVD标志试图到达角落时.正方形应该在碰到边缘时改变颜色.但是,我遇到了一些问题.
问题一:广场有时会从边缘反弹.其他时候它下沉,我无法弄清楚为什么.
问题二:我不确定如何在碰到边缘时改变方形的颜色.
问题三:我正在尝试学习如何制作JFRAME全屏.而不只是在我的屏幕上全屏,而是在任何人的屏幕上.
该代码已发布到在线IDE以便更轻松地阅读.这可以在这里找到
否则,如果你太忙于该链接.这里发布在下面.
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
主类
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);
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何,感谢您花时间阅读我的代码.非常感谢.我真的对不同的方法感兴趣.
问题一:广场有时会从边缘反弹.其他时候它下沉,我无法弄清楚为什么.
你会讨厌这个,但是
} else if (yPosit > height - SQUARE_SIZE) {
xPosit = height - SQUARE_SIZE;
xSpeed = -SPEED_OF_SQUARE;
}
Run Code Online (Sandbox Code Playgroud)
应该...
} else if (yPosit > height - SQUARE_SIZE) {
yPosit = height - SQUARE_SIZE;
ySpeed = -SPEED_OF_SQUARE;
}
Run Code Online (Sandbox Code Playgroud)
你正在使用xPosyit和xSpeed替代yPosyit和ySpeed...
问题二:我不确定如何在碰到边缘时改变方形的颜色.
基本上,每当您检测到边缘碰撞并改变方向时,只需将面板的前景色更改为其他内容......
这可能需要您有一个颜色列表,您可以从中随机选择或只是随机生成颜色
然后在你的paintComponent方法中,g.setColor(getForeground())在填充矩形之前简单使用...
... PS ...
为了让生活更轻松,你可以编写一个生成随机颜色或将前景设置为随机颜色的方法,例如......
protected void randomiseColor() {
int red = (int) (Math.round(Math.random() * 255));
int green = (int) (Math.round(Math.random() * 255));
int blue = (int) (Math.round(Math.random() * 255));
setForeground(new Color(red, green, blue));
}
Run Code Online (Sandbox Code Playgroud)
问题三:我正在尝试学习如何制作JFRAME全屏.而不只是在我的屏幕上全屏,而是在任何人的屏幕上.