【发布时间】:2018-04-30 18:13:04
【问题描述】:
我正在用 Java 构建一个 UI。我想使用按钮创建新组件,例如 JLabel。所以每次我点击一个按钮时,它都会创建一个新的 JLabel 并将它们放在一个特定的 JPanel 中。
然后,我希望能够根据用户点击标签的方式对标签做一些事情。
通过鼠标左键,我希望他们能够在屏幕上拖动标签。
点击鼠标右键我想打开一个新窗口,可以在其中输入某些数据,绑定到标签(这可能涉及动态创建变量)。
我一直在玩弄一些我在 Google 上搜索过的代码。我可以在面板中获得一个按钮来创建新标签,但是当我尝试让它们拖动时,我一次只能显示一个标签,并且在按下第二个按钮后,移动标签并不顺畅,它跳来跳去。
我什至还没有尝试实现任何鼠标右键单击的东西。如果有人能指出我正确的方向,我将不胜感激。
public class Testing {
JFrame frame;
//Launch the application.
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Testing window = new Testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Create the application.
public Testing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JPanel area;
JButton btnCreate;
JLabel dragLabel;
frame = new JFrame();
frame.setBounds(100, 100, 511, 542);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setVisible(true);
area = new JPanel();
area.setBounds(10, 11, 477, 404);
frame.getContentPane().add(area);
area.setLayout(new BorderLayout());
btnCreate = new JButton("Create Label");
dragLabel = new JLabel("Drag Me");
btnCreate.setBounds(10, 425, 477, 67);
frame.getContentPane().add(btnCreate);
btnCreate.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
area.add(dragLabel);
area.revalidate();
DragListener drag = new DragListener();
dragLabel.addMouseListener(drag);
dragLabel.addMouseMotionListener(drag);
}
});
}
}
class DragListener extends MouseInputAdapter
{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me) {
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
if(SwingUtilities.isLeftMouseButton(me)){
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
}
}
编辑 - 我相当确定主要问题在于 JLabel 本身是如何添加到面板中的。每次按下按钮时,它都会重新添加相同的标签,这会使工作变得混乱。
很遗憾,我不知道该如何处理。我做了更多的挖掘,因为动态变量是不可能的,我将不得不使用数组或映射或某种类型。有了它,我似乎可以声明组件数组。出于我的目的需要这样的东西吗?
【问题讨论】:
标签: java events dynamic draggable