我想用监听器编写一个项目,我的按钮正在工作,他们改变颜色,现在我需要我的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