所以我想通过x,y坐标使用绝对定位来移动按钮,我有一个没有图像的白色块移动而且无法点击
图像与使用图像的绘画方法一起使用,但我想使用按钮
//********************************************************************
// ReboundPanel.java Java Foundations
//
// Represents the primary panel for the Rebound program.
//********************************************************************
package ch0;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ReboundPanel extends JPanel
{
private final int WIDTH = 300, HEIGHT = 100;
private final int DELAY = 20, IMAGE_SIZE = 35;
private ImageIcon image;
private Timer timer;
private int x, y, moveX, moveY;
JButton button;
//-----------------------------------------------------------------
// Sets up the panel, including the timer for the animation.
//-----------------------------------------------------------------
public ReboundPanel()
{
this.setLayout(null); //Worked before I put this stuff but
super.setLayout(null);// I'm just trying stuff
timer = new Timer(DELAY, new ReboundListener());
image = new ImageIcon("smile.jpg");
button = new JButton(image);
button.setIcon(new ImageIcon("smile.jpg"));
x = 0;
y = 40;
moveX = moveY = 3;
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.black);
timer.start();
//button.setBounds(x, y, 10, 10);
//add(button);
}
//*****************************************************************
// Represents the action listener for the timer.
//*****************************************************************
private class ReboundListener implements ActionListener
{
//-----------------------------------------------------------------
// Updates the position of the image and possibly the direction
// of movement whenever the timer fires an action event.
//-----------------------------------------------------------------
public void actionPerformed(ActionEvent event)
{
x += moveX;
y += moveY;
if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
moveX = moveX * -1;
if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
moveY = moveY * -1;
button.setBounds(x, y, 100, 100);
add(button);
}
}
}
//********************************************************************
// Rebound.java Java Foundations
//
// Demonstrates an animation and the use of the Timer class.
//********************************************************************
package ch0;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Rebound
{
//-----------------------------------------------------------------
// Displays the main frame of the program.
//-----------------------------------------------------------------
public static void main(String[] args)
{
JFrame frame = new JFrame("Rebound");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReboundPanel());
frame.pack();
frame.setVisible(true);
}
}