
java JPanel 怎么让jpanel平滑移动 20
for(intx=-430;x<=0;x+=2){jf.repaint();try{Thread.sleep(1);}catch(InterruptedException...
for(int x=-430;x<=0;x+=2){ jf.repaint(); try { Thread.sleep(1); } catch (InterruptedException e1) { // TODO 自动生成的 catch 块 e1.printStackTrace(); } jf.setLocation(x,0); System.out.println("x");
写在主函数可以完成。
但这代码写在类中,无法实现按按钮让它缓慢移动。而是直接到延时后直接在指定位置出现。
但怎么实现类中完成鼠标事件执行。 展开
写在主函数可以完成。
但这代码写在类中,无法实现按按钮让它缓慢移动。而是直接到延时后直接在指定位置出现。
但怎么实现类中完成鼠标事件执行。 展开
1个回答
2015-05-21
展开全部
附一个简单的示例代码
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* @author Jeky
*/
public class MainFrame extends JFrame {
private JPanel movePanel;
private JButton button;
public MainFrame() {
movePanel = new JPanel();
movePanel.setBorder(BorderFactory.createRaisedBevelBorder());
movePanel.setBounds(new Rectangle(50, 50, 50, 50));
button = new JButton("移动");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rectangle bounds = movePanel.getBounds();
Point location = bounds.getLocation();
location.x+=5;
location.y+=5;
bounds.setLocation(location);
movePanel.setBounds(bounds);
}
});
JPanel center = new JPanel();
center.setLayout(null);
center.add(movePanel);
JPanel south = new JPanel();
south.setLayout(new FlowLayout(FlowLayout.CENTER));
south.add(button);
this.getContentPane().add(center,BorderLayout.CENTER);
this.getContentPane().add(south,BorderLayout.SOUTH);
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* @author Jeky
*/
public class MainFrame extends JFrame {
private JPanel movePanel;
private JButton button;
public MainFrame() {
movePanel = new JPanel();
movePanel.setBorder(BorderFactory.createRaisedBevelBorder());
movePanel.setBounds(new Rectangle(50, 50, 50, 50));
button = new JButton("移动");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rectangle bounds = movePanel.getBounds();
Point location = bounds.getLocation();
location.x+=5;
location.y+=5;
bounds.setLocation(location);
movePanel.setBounds(bounds);
}
});
JPanel center = new JPanel();
center.setLayout(null);
center.add(movePanel);
JPanel south = new JPanel();
south.setLayout(new FlowLayout(FlowLayout.CENTER));
south.add(button);
this.getContentPane().add(center,BorderLayout.CENTER);
this.getContentPane().add(south,BorderLayout.SOUTH);
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
追问
已看过,不是要这个效果
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询