gpt4 book ai didi

java - 尝试拖动时 JLabel 消失

转载 作者:行者123 更新时间:2023-11-30 08:26:52 25 4
gpt4 key购买 nike

我正在构建一个应用程序,将标签放置在用户点击面板 (jpanel2) 的位置,并允许它移动放置的标签。

我可以成功放置标签,但无法移动任何标签。事实上,当我尝试拖动标签时,在我所有的尝试中它都会消失。我还尝试在 jPanel2 和 JFrame 中调用重绘,但仍然没有成功。

JPanel 2 没有布局(自由设计),因为想要将标签准确放置在鼠标点击的位置。

更新

这是发生问题的一个最小示例。我无法减少面板的数量,因为我需要在屏幕上放置更多控件(例如 jtable、菜单和工具栏)。

public class Example extends javax.swing.JFrame {

static int count = 0;

public Example() {
initComponents();
}

@SuppressWarnings("unchecked")
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(600, 600));

jPanel2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jPanel2MouseClicked(evt);
}
});

jPanel3.setMinimumSize(new java.awt.Dimension(0, 0));
jPanel3.setLayout(new java.awt.BorderLayout());
jPanel3.add(jLabel1, java.awt.BorderLayout.CENTER);

javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

pack();
}// </editor-fold>

private void jPanel2MouseClicked(java.awt.event.MouseEvent evt) {

count++;
addAnnotation(String.valueOf(count), evt.getX(), evt.getY());
}

private void addAnnotation(String labelStr, int x, int y) {

final JLabel label = new JLabel(labelStr);
jPanel2.add(label);
label.setLocation(x, y);

System.out.println("Adding to " + x + " " + y);

label.setSize(20, 20);
label.setBackground(Color.WHITE);
label.setOpaque(true);
label.setBorder(new LineBorder(Color.BLACK, 1, false));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setVisible(true);
label.setForeground(Color.BLACK);

label.addMouseMotionListener(new MouseMotionListener() {

@Override
public void mouseDragged(MouseEvent e) {
Component c = e.getComponent();

int moveToX = c.getX() + e.getX();
int moveToY = c.getY() + e.getY();
c.setLocation(moveToX, moveToY);
System.out.println("Moving to " + moveToX + " " + moveToY);
}

@Override
public void mouseMoved(MouseEvent e) {
}
});
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Example().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration
}

最佳答案

如果您要使用 GUI Builder 制作程序,您需要做的是将面板的布局设置为空。然后,当您向面板添加标签时,您需要为它们设置边界。以下是您如何实现这一目标的示例。

  • 首先,我向框架表单 (jPanel1) 添加了一个空白的 JPanel。我将它扩展到框架的大小。
  • 然后我在构造函数中添加了所有其余代码。我添加了一个 JLabeljPanel 然后 revalidate()repaint() jPanel1.
  • 然后我添加了 MouseMotionListener

这是我添加的唯一代码。都在构造函数中。除了作为类成员的 pXpY 变量

int pX, pY;
public NewJFrame() {
initComponents();
jPanel1.setLayout(null);
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setBounds(50, 50, 50, 50);
label.setBorder(new LineBorder(Color.black, 3));
label.setText("Hello");

label.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent me) {
label.setLocation(label.getLocation().x + me.getX() - pX,
label.getLocation().y + me.getY() - pY);
jPanel1.revalidate();
jPanel1.repaint();
}
});
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// Get x,y and store them
pX = me.getX();
pY = me.getY();
}
});

jPanel1.add(label);
jPanel1.revalidate();
jPanel1.repaint();
}

enter image description here


这是完整的程序

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;

public class NewJFrame extends javax.swing.JFrame {

int pX, pY;
public NewJFrame() {
initComponents();
jPanel1.setLayout(null);
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setBounds(50, 50, 50, 50);
label.setBorder(new LineBorder(Color.black, 3));
label.setText("Hello");

label.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent me) {
label.setLocation(label.getLocation().x + me.getX() - pX,
label.getLocation().y + me.getY() - pY);
jPanel1.revalidate();
jPanel1.repaint();
}
});
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// Get x,y and store them
pX = me.getX();
pY = me.getY();
}
});

jPanel1.add(label);
jPanel1.revalidate();
jPanel1.repaint();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 388, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 288, Short.MAX_VALUE)
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

pack();
}// </editor-fold>

public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
// End of variables declaration
}

关于java - 尝试拖动时 JLabel 消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21217368/

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