Java 中如何实现button在一个界面内的动态移动
运行程序后,button在界面的一端移动到另一端,并在那里定格。而且可以看到button的移动...
运行程序后,button在界面的一端移动到另一端,并在那里定格。而且可以看到button的移动
展开
1个回答
展开全部
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class Demo extends javax.swing.JFrame {
private JPanel jPanel1;
private JButton bnt;
private Timer timer;
public static void main(String[] args) {
Demo inst = new Demo();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
public Demo() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
jPanel1 = new JPanel();
getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.setLayout(null);
{
bnt = new JButton();
jPanel1.add(bnt);
bnt.setText("移动");
bnt.setBounds(56, 27, 60, 28);
}
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
int x = bnt.getX() + 50;
int y = bnt.getY() + 50;
if (x < Demo.this.getWidth() && y < Demo.this.getY()) {
bnt.setLocation(x, y);
}
}
});
timer.start();
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class Demo extends javax.swing.JFrame {
private JPanel jPanel1;
private JButton bnt;
private Timer timer;
public static void main(String[] args) {
Demo inst = new Demo();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
public Demo() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
jPanel1 = new JPanel();
getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.setLayout(null);
{
bnt = new JButton();
jPanel1.add(bnt);
bnt.setText("移动");
bnt.setBounds(56, 27, 60, 28);
}
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
int x = bnt.getX() + 50;
int y = bnt.getY() + 50;
if (x < Demo.this.getWidth() && y < Demo.this.getY()) {
bnt.setLocation(x, y);
}
}
});
timer.start();
}
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询