昨天我试图制作一个可拖动,未修饰的JPanel,它工作得很好,然后今天我加载了项目,它不再工作(我不知道为什么会发生这种情况因为我确实保存了一切)。
非常感谢任何帮助:)
这是源代码:
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class CustomBubble extends JFrame {
public int xMouse;
public int yMouse;
JPanel pnl = new JPanel();
public CustomBubble()
{
super("CustomBubble");
setSize(150,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setUndecorated(true);
setLocationByPlatform(true);
setAlwaysOnTop(true);
setVisible(true);
pnl.addMouseMotionListener(
new MouseAdapter()
{
public void mouseDragged(MouseEvent e) {
int x = e.getXOnScreen();
int y = e.getYOnScreen();
setLocation(x - xMouse, y - yMouse);
}
});
pnl.addMouseListener(
new MouseAdapter() {
public void mousePressed(MouseEvent me) {
xMouse = me.getX();
yMouse = me.getY();
}
});
add(pnl);
}
public static void main(String[] args)
{
CustomBubble gui = new CustomBubble();
}
}
答案 0 :(得分:1)
我在计算机上对此进行了测试并将其运行起来。通常setVisible(true);
语句应该是你做的最后一件事。所以,只需在add(pnl);
电话后调低该声明,你应该做得很好。
...
add(pal);
setVisible(true);
} // end of constructor
答案 1 :(得分:0)
此代码工作正常。我在我的电脑上试过这个代码。没有给出任何错误。工作得很好..
package test;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
*
* @author ****
*/
public class Test extends JFrame {
public int xMouse;
public int yMouse;
JPanel pnl = new JPanel();
public Test()
{
super("CustomBubble");
setSize(150,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setUndecorated(true);
setLocationByPlatform(true);
setAlwaysOnTop(true);
setVisible(true);
pnl.addMouseMotionListener(
new MouseAdapter()
{
public void mouseDragged(MouseEvent e) {
int x = e.getXOnScreen();
int y = e.getYOnScreen();
setLocation(x - xMouse, y - yMouse);
}
});
pnl.addMouseListener(
new MouseAdapter() {
public void mousePressed(MouseEvent me) {
xMouse = me.getX();
yMouse = me.getY();
}
});
add(pnl);
}
public static void main(String[] args)
{
Test gui = new Test();
}
}