gpt4 book ai didi

java - 如何将 Jlabel 从一个 JPanel 移动到另一个 JPanel

转载 作者:行者123 更新时间:2023-12-01 23:46:13 25 4
gpt4 key购买 nike

我有很多JPanel s 和 1 JLabel 。当我点击一个JPanel时我想要我的JLabel (含图片)移步此JPanel 。这如何通过代码来完成?我正在 NetBeans 中编码。

最佳答案

前提很简单,但实际的解决方案可能取决于您想要实现的目标。

因为组件一次只能存在于一个容器中,所以您只需担心将其添加到新容器中...

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class LabelMover {

public static void main(String[] args) {
new LabelMover();
}

public LabelMover() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BasePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

});
}

public class BasePane extends JPanel {

private JLabel label;

public BasePane() {
setLayout(new GridLayout(2, 2));
MouseHandler handler = new MouseHandler();
for (int index = 0; index < 4; index++) {
CellPane pane = new CellPane();
pane.addMouseListener(handler);
add(pane);
}
label = new JLabel(":)");
label.setHorizontalAlignment(JLabel.CENTER);
((CellPane)getComponent(0)).add(label);
}

public class MouseHandler extends MouseAdapter {

@Override
public void mousePressed(MouseEvent e) {
Component source = e.getComponent();
if (!label.getParent().equals(source)) {
((CellPane)source).add(label);
revalidate();
repaint();
}
}

}

public class CellPane extends JPanel {

public CellPane() {
setLayout(new BorderLayout());
setBorder(new LineBorder(Color.GRAY));
}

@Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}

}
}
}

关于java - 如何将 Jlabel 从一个 JPanel 移动到另一个 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17008623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com