我想用監聽器編寫一個項目,我的按鈕正在工作,他們改變顏色,現在我需要我的mouseLIsteners來打印鼠標正在做什麼的文本。例如:「鼠標進入黃色區域,鼠標退出黃色區域,鼠標點擊/釋放黃色區域等。」 我有他們實現,但沒有任何工作,以獲得文本打印出來。這裏是我的代碼:回調和監聽器; MouseListener
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JComponent;
public class SwingLab
{
// frame properties
private static final int FRAME_WIDTH = 400; private static final int FRAME_HEIGHT = 400;
public static void main(String[] args)
{
// Instantiate a frame (the main window)
JFrame frame = new JFrame();
// The buttons (one for each color)
final JButton bRed = new JButton("Red");
JButton bYellow = new JButton("Yellow");
JButton bBlue = new JButton("Blue");
// Here we create a panel consisting of other panels (layed out in a
// Grid) to support the buttons and "Art" instance
final JPanel container = new JPanel(new GridLayout(2,1));
final JPanel panel = new JPanel(new GridLayout(1,1));
final JPanel buttonPanel = new JPanel(new GridLayout(3,1));
// An instance of a special class for you to play with (Art is defined
// below)
Art artBox=new Art();
panel.add(artBox);
// add the buttons to the panel
buttonPanel.add(bRed);
buttonPanel.add(bYellow);
buttonPanel.add(bBlue);
// put the panels together and add them to the frame
container.add(panel);
container.add(buttonPanel);
frame.add(container);
/* YOUR CODE GOES HERE */
// declare your listener classes and add them to the buttons
// here.
// you are going to call addActionListener and
// addMouseListener for each button
// you want to deal with the JPanel named "panel" declared
// above
/* END YOUR CODE */
class RedButtonListener implements ActionListener, MouseListener
{
public void actionPerformed(ActionEvent event)
{
panel.setBackground(Color.RED);
}
@Override
public void mouseClicked(MouseEvent e) {
bRed.addMouseListener(this);
addMouseListener(this);
// TODO Auto-generated method stub
}
您的代碼不顯示您的問題,除了你有很多不必要的冗餘,但再次,這不是你的錯誤的原因。爲了幫助我們,您需要展示足夠的代碼,以便我們能夠理解您的問題,但不要使用太多的代碼,以致於無法處理與手頭問題無關的太多代碼。最好是如果你可以花時間來創建和發佈一個[最小示例程序](http://stackoverflow.com/help/mcve) – 2014-10-18 01:55:51
我是新來的java,所以這可能是爲什麼冗餘。問題是我有聽衆和事件實施,但當我在輸入事件中寫入System.out.println(「鼠標已進入黃色區域」)時,我沒有texg – 2014-10-18 01:57:36
我們如何猜測可能是什麼問題,如果我們沒有看到你如何使用你的聽衆,你如何將它們添加到你的GUI?例如,我無處看到'addMouseListener(...)'。那麼它在哪裏?事實上,**是**你添加任何MouseListeners任何東西? – 2014-10-18 01:58:10