我已经创建了一个正方形使用摆动组件,当被分配给它们的按钮点击时,摆动组件左右上下移动。现在我试图在点击时随意移动这个对象。这是我的代码。随机移动一个物体使用摆动组件
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class MovingObjects extends JFrame
implements ActionListener {
// GUI code omitted here...
@SuppressWarnings("unused")
private JButton button, leftButton,rightButton,upButton,downButton;
private JPanel panel,redPanel;
int x =10;
int y=10;
public static void main (String[] args) {
MovingObjects frame = new MovingObjects();
frame.setSize(400, 300);
frame.createGUI();
frame.show();
frame.getContentPane().setBackground(Color.blue);
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 200));
panel.setBackground(Color.black);
window.add(panel);
redPanel = new JPanel();
redPanel.setBackground(Color.red);
redPanel.setLocation(x, y);
redPanel.setSize(50, 50);
panel.add(redPanel);
leftButton = new JButton("Move Left");
leftButton.addActionListener(this);
window.add(leftButton);
rightButton = new JButton("Move Right");
rightButton.addActionListener(this);
window.add(rightButton);
upButton = new JButton("Move Up");
upButton.setLocation(260, 60);
upButton.setSize(100, 30);
upButton.addActionListener(this);
window.add(upButton);
downButton = new JButton("Move Down");
downButton.addActionListener(this);
window.add(downButton);
}
public void actionPerformed(ActionEvent event) {
//Move down
if (event.getSource() == downButton)
{
if (y < 180){
y=y+20;
redPanel.setLocation(x, y);
}
}
//Move Up
if (event.getSource() == upButton)
{
if (y > 10){
y=y-20;
redPanel.setLocation(x, y);
}
}
//Move Left
if (event.getSource() == leftButton)
{
if (x > 10){
x=x-20;
redPanel.setLocation(x, y);
}
}
//Move Right
if (event.getSource() == rightButton)
{
if (x < 280){
x=x+20;
redPanel.setLocation(x, y);
}
}
}
}
位置当你说随机时尚你是指随机单位还是随机预定义的方向。另外,这里没有实际的问题。无论如何,您可能会希望在您的代码中使用java.util.Random来生成一个随机数。 – 2015-02-10 23:32:35
随机定义的方向。我试图实现java.util.Random,但不幸的是我没有任何线索。 – 2015-02-10 23:34:16