我创建了一个带有可移动组件的 UI。当我创建一个时,它看起来像最上面的图片。一旦我开始移动它,按钮周围的空间就会变成黑色,如中间所示。当我进入另一个窗口(例如 safari)时,收音机框周围的空间也会变黑。任何想法为什么?
编辑:
3button 组合是一个扩展的 JPalet 类,它嵌入到框架中的另一个面板 JPanel1 中。一旦我在 JPanel1 中重新验证并重新绘制,该错误就会再次消失。或者当我将一个 3button 鞭打在另一个上时(这可能也会触发重绘)。
我移动 3Button 并使用 MouseAdapter MouseDrag 将 mousemotionlistener 粘在 JButton 上
编辑:
希望这个代码片段足够小。
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class UiTestFrame {
public UiTestFrame() {
buildUi();
}
void buildUi() {
JFrame frame = new JFrame("TestFrame");
XButton jButton = new XButton();
frame.add(jButton);
jButton.setSize(jButton.getPreferredSize());
jButton.setLocation(10, 10);
frame.revalidate();
frame.repaint();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(500, 500);
frame.setVisible(true);
}
private class XButton extends javax.swing.JPanel {
public XButton() {
initComponents();
jButton1.addMouseMotionListener(new MotionEvent(this));
}
private void initComponents() {
jButton1 = new javax.swing.JButton();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
setBackground(new java.awt.Color(0, 0, 0, 0f));
setPreferredSize(new java.awt.Dimension(130, 30));
setLayout(null);
jButton1.setText("jButton1");
jButton1.setAlignmentY(0.0F);
jButton1.setContentAreaFilled(false);
jButton1.setFocusPainted(false);
jButton1.setFocusable(false);
jButton1.setMargin(new java.awt.Insets(-2, -2, -2, -2));
add(jButton1);
jButton1.setBounds(19, 0, 90, 30);
jRadioButton1.setEnabled(false);
jRadioButton1.setFocusable(false);
add(jRadioButton1);
jRadioButton1.setBounds(0, 0, 20, 30);
jRadioButton2.setEnabled(false);
jRadioButton2.setFocusable(false);
jRadioButton2.setName(""); // NOI18N
add(jRadioButton2);
jRadioButton2.setBounds(100, 0, 30, 30);
}
private javax.swing.JButton jButton1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
}
private class MotionEvent extends MouseAdapter {
javax.swing.JComponent button;
Point pt;
public MotionEvent(javax.swing.JComponent button) {
this.button = button;
}
public void mouseMoved(MouseEvent e) {
pt = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
Point p = SwingUtilities.convertPoint(button, e.getPoint(), button.getParent());
button.setLocation(p.x - pt.x, p.y - pt.y);
}
}
}