【发布时间】:2014-12-13 15:50:20
【问题描述】:
我正在尝试编写一个带有监听器的项目,我的按钮在它们改变颜色的地方工作,现在我需要我的 mouseLIsteners 来打印鼠标正在做什么的文本。例如:“鼠标进入黄色区域,鼠标退出黄色区域,鼠标点击/释放黄色区域等。” 我已经实现了它们,但没有任何东西可以打印出文本。这是我的代码:
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
}
【问题讨论】:
-
你的代码没有显示你的问题,除了你有很多不必要的冗余,但同样,这不是你的错误的原因。为了让我们提供帮助,您需要展示足够多的代码以便我们理解您的问题,但不要显示太多代码,以免过多与手头问题无关的代码让我们不知所措。如果您能花时间创建和发布minimal example program,那就最好不过了
-
我是 java 新手,所以这可能就是冗余的原因。问题是我已经实现了侦听器和事件,但是当我在输入的事件中写 System.out.println("The mouse has enter the yellow area") 时,我没有 texg
-
如果我们看不到您如何使用您的听众,您如何将它们添加到您的 GUI 中,我们如何猜测可能是什么问题?例如,我在任何地方都看不到
addMouseListener(...)。那么它在哪里呢?事实上,是你添加任何 MouseListeners 到任何东西? -
我实现了类的鼠标监听器,那么我要为每个类添加MouseListener吗?
-
别问——试试吧!你有一个触手可及的计算机编程实验室,所以使用它。实验、玩耍、编写代码、运行、更改、将其推向极限然后超越,找出有效的方法和无效的方法。相信我,你不会炸毁你的电脑,你不会因为努力而带来厄运和诅咒。对于可以通过测试回答的简单问题,不要在这里问我们——自己去寻找。这就是学习和编程的意义所在!
标签: java swing callback awt listeners