我正在學習java swing,並且在以下程序中遇到問題。它在頂部創建一個帶有退出按鈕的小框架。目的是在鼠標點擊的任何位置顯示座標。當我點擊鼠標2件不必要的事情正在發生:Java:重繪在Swing不工作
- 的退出按鈕被鼠標點擊無效,它不再響應(而不是對事件作出反應,並戒菸,它顯示的退出按鈕的頂部座標) 。
- 當我點擊一個新位置時,舊位置的座標依然存在。
我用removeAll()
和revalidate()
做基於this discussionrepaint()
之前,但是這並沒有幫助。此代碼取自here以及說明研究在線文檔爲何發生這種情況的代碼。
任何指針?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
public class QuitCoordinateTest {
public static void main(String[] args){
GUI gui = new GUI();
}
}
class MyFrame extends JFrame implements ActionListener{
int clickX;
int clickY;
public void paint(Graphics g){
g.drawString("" + clickX + ", " + clickY, clickX, clickY);
}
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
//=======================================================//
class GUI extends MyFrame {
JButton quitButton = new JButton("Quit");
public GUI(){
MyFrame displayWindow = new MyFrame();
displayWindow.setTitle("Title");
/*
JPanel buttonPanel = new JPanel();
buttonPanel.add(quitButton);
displayWindow.getContentPane().add(buttonPanel,BorderLayout.NORTH);
JPanel textPanel = new JPanel();
*/
displayWindow.getContentPane().add(quitButton,BorderLayout.NORTH);
quitButton.addActionListener(displayWindow);
displayWindow.setSize(201,201);
displayWindow.setVisible(true);
// displayWindow.pack();
displayWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
displayWindow.addMouseListener(new MouseProc(displayWindow));
}//end constructor
}//end class GUI definition
//=======================================================//
//This listener class monitors for mouse presses and
// displays the coordinates of the mouse pointer when the
// mouse is pressed on the source object.
class MouseProc extends MouseAdapter{
MyFrame refToWin;
MouseProc(MyFrame inWin){
refToWin = inWin;
}
//Override the mousePressed method to determine and
// display the coordinates when the mouse is pressed.
public void mousePressed(MouseEvent e){
refToWin.removeAll();
refToWin.clickX = e.getX();
refToWin.clickY = e.getY();
//Force the JFrame object to be repainted in order to
// display the coordinate information.
refToWin.removeAll();
refToWin.validate();
refToWin.repaint();
}
}
謝謝!我更新了代碼以顯示添加quitButton。對不起,新的擺動。我假設你的意思是爲(a)按鈕和(b)座標區域創建JPanel並在那裏使用繪畫。我試圖創建JPanel,以避免在退出按鈕上重疊座標。它改變了外觀和窗口大小。我必須提供一個201x201窗口,頂部有一個跨越窗口寬度的退出按鈕。我將致力於修復JPanel的大小。我使用removeAll來擺脫基於鏈接討論的舊座標。看來超級會解決這個問題。 – user3600280 2014-10-20 01:12:28