
1个回答
展开全部
首先将JPanel的容器的布局管理器设为null 即绝对布局
然后移动的时候只需要修改JPanel的bounds就行了
附一个简单的示例代码
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();
}
}
然后移动的时候只需要修改JPanel的bounds就行了
附一个简单的示例代码
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();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询