我有一个非常简单的例子。在尝试将其应用于我计划的更复杂的程序之前,我正在尝试开始工作。但我试图能够拖放在流或垂直布局中的 JPanel。
我不确定从哪里开始,因为这不是我以前处理过的任何事情。但根据我的研究,似乎我肯定需要在每个 JPanel 上都有一个监听器,它监听点击。从这里它将从 mousePressed 收集初始数据,并运行一个覆盖的repaint()
,这将更新容器中面板的坐标。然后根据坐标放置的位置,它会 repack() 并希望调整面板的大小。
我走对了吗?
import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class DraggablePanels extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
int px, py;
JPanel main = new JPanel();
public DraggablePanels(){
this.setLayout(new FlowLayout());
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setResizable(false);
JPanel p1 = new JPanel();
p1.addMouseListener(new MouseListener(){
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
px = e.getX();
py = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
p1.setBorder(raisedbevel);
JPanel p2 = new JPanel();
p2.addMouseListener(new MouseListener(){
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
px = e.getX();
py = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
p2.setBorder(raisedbevel);
p1.add(new JLabel("Thing 1"));
p2.add(new JLabel("Thing 2"));
main.add(p1);
main.add(p2);
add(main);
pack();
setVisible(true);
}
public static void main (String args[]){
DraggablePanels d = new DraggablePanels();
}
}