我有以下代碼來移動未裝飾的擺動框架,但是每當我按下滑鼠按鈕時,都會出現以下例外:
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
這是我的代碼
class Gui extends Frame
{
JFrame frame;
JLabel label;
Gui()
{
frame = new JFrame();
label = new JLabel("...");
label.setForeground(Color.white);
//label.setBounds(300,300, 100,30);
frame.add(label);
frame.setSize(30, 30);
frame.setUndecorated(true);
frame.setLocation(1550, 1045);
frame.setBackground(new Color(0,0,0,0));
frame.setAlwaysOnTop(true);
frame.setVisible(true);
listenMouse();
}
public void listenMouse()
{
MouseAdapter ma = new MouseAdapter() {
int lastX, lastY;
@Override
public void mousePressed(MouseEvent e) {
lastX = e.getXOnScreen();
lastY = e.getYOnScreen();
}
@Override
public void mouseDragged(MouseEvent e) {
int x = e.getXOnScreen();
int y = e.getYOnScreen();
// Move frame by the mouse delta
frame.setLocation(getLocationOnScreen().x x - lastX,
frame.getLocationOnScreen().y y - lastY);
lastX = x;
lastY = y;
}
};
frame.addMouseListener(ma);
frame.addMouseMotionListener(ma);
}
會不會是視窗太小或者位置有問題?任務欄上是否已經關閉螢屏?
uj5u.com熱心網友回復:
洗掉extend Frame- 您有兩個基于視窗的類,Gui它們從 擴展Frame,在多個帳戶上不是一個好主意*,frame它是JFrame.
frame.setLocation(getLocationOnScreen().x x - lastX,
frame.getLocationOnScreen().y y - lastY);
然后嘗試根據 的位置設定 的位置JFrame,Frame這在螢屏上尚未實作。
所以,簡短的回答是,你自己搞糊涂了。
Frame是一個基于 AWT 的組件,在這種情況下,這不是一個好的起點。通常不鼓勵從頂級容器擴展Frame,因為您沒有向類添加任何新功能,它會將您鎖定在單個用例中(減少重用),并且頂級容器往往是更復雜的結構,并且可以真的以你意想不到的方式惹惱你
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/516705.html
標籤:爪哇摇摆
