如何在Java中将鼠标悬停监听器添加到矩形

时间:2014-12-14 04:41:06

标签: java swing button java-2d rectangles

我正在尝试使用Rectangle对象创建一个按钮,并且还尝试在悬停时进行颜色更改,并且它不会更改。 我已经使我的代码有更多通用的变量名称,它不会混淆,这里是:

public class MouseHandler extends MouseAdapter {
    @Override
    public void mouseMoved(MouseEvent e) {
        int mx = e.getX();
        int my = e.getY();
        if(mx > button.x && mx < button.x+button.width &&
                my > button.y && my < button.y+button.height) {
                buttonHover = true;
        } else {
                buttonHover = false;

        }
    }
}

我也试过调用这些代码行,但它不起作用:

if(buttonHover)
g.setColor(hoverColor);
g.drawRect(button.x, button.y, button.width, button.height);

我将使用实际变量名将底部的完整代码放在底部。谢谢你的帮助!

package trivia;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Main extends JFrame{

boolean mainMenu = true;
boolean startHover;
static Color tan = Color.decode("#F4EBC3");
static Color darkGreen = Color.decode("#668284");
static Color buttonColor = Color.decode("#A2896B");
static Color borderColor = Color.decode("#333333");
static Color buttonHover = Color.decode("#F5B66E");
Rectangle header = new Rectangle(0, 0, 500, 100);
Rectangle body = new Rectangle(0, 100, 500, 400);
Rectangle start = new Rectangle(150, 150, 200, 40);
Rectangle howToPlay = new Rectangle(150, 225, 200, 40);
Rectangle quit = new Rectangle(150, 300, 200, 40);

public Main() {
    setTitle("Trivia Game!");
    setSize(500, 500);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

}
@Override
public void paint(Graphics g) {
    Dimension d = this.getSize();
    if(mainMenu = true){
        g.setColor(darkGreen);
        g.fillRect(header.x, header.y, header.width, header.height);
        g.setFont(new Font("Courier", Font.BOLD, 24));
        g.setColor(Color.BLACK);
        drawCenteredString("Trivia Game!", d.width, 125, g);
        g.setColor(tan);
        g.fillRect(body.x, body.y, body.width, body.height);
        g.setColor(buttonColor);
        g.fillRect(start.x, start.y, start.width, start.height);
        g.setColor(borderColor);
        g.drawRect(start.x, start.y, start.width, start.height);
        g.setFont(new Font("Courier", Font.BOLD, 20));
        g.setColor(Color.black);
        drawCenteredString("Start", d.width, 340, g);
        g.setColor(buttonColor);
        g.fillRect(howToPlay.x, howToPlay.y, howToPlay.width, howToPlay.height);
        g.setColor(borderColor);
        g.drawRect(howToPlay.x, howToPlay.y, howToPlay.width, howToPlay.height);
        g.setFont(new Font("Courier", Font.BOLD, 20));
        g.setColor(Color.black);
        drawCenteredString("How To Play", d.width, 490, g);
        g.setColor(buttonColor);
        g.fillRect(quit.x, quit.y, quit.width, quit.height);
        g.setColor(borderColor);
        g.drawRect(quit.x, quit.y, quit.width, quit.height);
        g.setFont(new Font("Courier", Font.BOLD, 20));
        g.setColor(Color.black);
        drawCenteredString("Quit?", d.width, 640, g);
        g.setColor(buttonColor);
        g.fillRect(start.x, start.y, start.width, start.height);
        g.setColor(borderColor);
        g.drawRect(start.x, start.y, start.width, start.height);
        g.setFont(new Font("Courier", Font.BOLD, 20));
        g.setColor(Color.black);
        drawCenteredString("Start", d.width, 340, g);
        if(startHover)
            g.setColor(buttonHover);
            g.drawRect(start.x, start.y, start.width, start.height);
    }
}
public void drawCenteredString(String s, int w, int h, Graphics g) {
    FontMetrics fm = g.getFontMetrics();
    int x = (w - fm.stringWidth(s)) / 2;
    int y = (fm.getAscent() + (h- (fm.getAscent() + fm.getDescent())) / 2);
    g.drawString(s, x, y);
}

public static void main(String[] args) {
    @SuppressWarnings("unused")
    Main m = new Main();
}
public class MouseHandler extends MouseAdapter {
    @Override
    public void mouseMoved(MouseEvent e) {
        int mx = e.getX();
        int my = e.getY();
        if(mx > start.x && mx < start.x+start.width &&
                my > start.y && my < start.y+start.height) {
                startHover = true;
                System.out.println("yes");
        } else {
                startHover = false;
                System.out.println("no");
        }
    }
}
}

2 个答案:

答案 0 :(得分:2)

我开始......

1)如果它真的只是一个你想要处理的矩形。请使用https://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html,Java非常友好,让您的生活变得简单,请不要丢弃它。 (忽略此处保留此处以供参考)

2)你应该实现MouseMotionListener ......我为你做了。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class test extends JFrame  implements MouseMotionListener {

boolean mainMenu = true;
boolean startHover;
static Color tan = Color.decode("#F4EBC3");
static Color darkGreen = Color.decode("#668284");
static Color buttonColor = Color.decode("#A2896B");
static Color borderColor = Color.decode("#333333");
static Color buttonHover = Color.decode("#F5B66E");
Rectangle header = new Rectangle(0, 0, 500, 100);
Rectangle body = new Rectangle(0, 100, 500, 400);
Rectangle start = new Rectangle(150, 150, 200, 40);
Rectangle howToPlay = new Rectangle(150, 225, 200, 40);
Rectangle quit = new Rectangle(150, 300, 200, 40);

public test() {
    setTitle("Trivia Game!");
    setSize(500, 500);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    this.addMouseMotionListener(this);
}

@Override
public void paint(Graphics g) {
    Dimension d = this.getSize();
    if (mainMenu = true) {
        g.setColor(darkGreen);
        g.fillRect(header.x, header.y, header.width, header.height);
        g.setFont(new Font("Courier", Font.BOLD, 24));
        g.setColor(Color.BLACK);
        drawCenteredString("Trivia Game!", d.width, 125, g);
        g.setColor(tan);
        g.fillRect(body.x, body.y, body.width, body.height);
        g.setColor(buttonColor);
        g.fillRect(start.x, start.y, start.width, start.height);
        g.setColor(borderColor);
        g.drawRect(start.x, start.y, start.width, start.height);
        g.setFont(new Font("Courier", Font.BOLD, 20));
        g.setColor(Color.black);
        drawCenteredString("Start", d.width, 340, g);
        g.setColor(buttonColor);
        g.fillRect(howToPlay.x, howToPlay.y, howToPlay.width,
                howToPlay.height);
        g.setColor(borderColor);
        g.drawRect(howToPlay.x, howToPlay.y, howToPlay.width,
                howToPlay.height);
        g.setFont(new Font("Courier", Font.BOLD, 20));
        g.setColor(Color.black);
        drawCenteredString("How To Play", d.width, 490, g);
        g.setColor(buttonColor);
        g.fillRect(quit.x, quit.y, quit.width, quit.height);
        g.setColor(borderColor);
        g.drawRect(quit.x, quit.y, quit.width, quit.height);
        g.setFont(new Font("Courier", Font.BOLD, 20));
        g.setColor(Color.black);
        drawCenteredString("Quit?", d.width, 640, g);
        g.setColor(buttonColor);
        g.fillRect(start.x, start.y, start.width, start.height);
        g.setColor(borderColor);
        g.drawRect(start.x, start.y, start.width, start.height);
        g.setFont(new Font("Courier", Font.BOLD, 20));
        g.setColor(Color.black);
        drawCenteredString("Start", d.width, 340, g);
        if (startHover)
            g.setColor(buttonHover);
        g.drawRect(start.x, start.y, start.width, start.height);
    }
}

public void drawCenteredString(String s, int w, int h, Graphics g) {
    FontMetrics fm = g.getFontMetrics();
    int x = (w - fm.stringWidth(s)) / 2;
    int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent())) / 2);
    g.drawString(s, x, y);
}

public static void main(String[] args) {
    @SuppressWarnings("unused")
    test m = new test();
}

@Override
public void mouseDragged(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseMoved(MouseEvent e) {
    System.out.println("lol");
    int mx = e.getX();
    int my = e.getY();
    if (mx > start.x && mx < start.x + start.width && my > start.y
            && my < start.y + start.height) {
        startHover = true;
        System.out.println("yes");
    } else {
        startHover = false;
        System.out.println("no");
    }
}
}

如果你在下面看到,你会发现你的代码有很多问题。不要让这吓到你学习。一步一步做,你会没事的。

答案 1 :(得分:2)

你在这里遇到了几个问题:

  • 您正在JFrame中直接绘图,这是一件危险的事情,因为JFrames包含许多组件,有些我确定您不熟悉,包括边框,rootpane,glasspane和contentpane,以及你弄乱了绘画,它会弄乱这些关键组件的绘制。
  • 此外,通过在绘画方法中绘画,您将失去Swing图形的所有优点。
  • 此外,您似乎在绘画方法中拥有大部分程序设计和逻辑,您应该从不做一些事情,因为您无法完全控制何时或甚至调用该方法
  • 相反,您应该在自己的类中创建按钮组件,与JFrame
  • 分开
  • 将您的课程能力放入JPanel
  • 并赋予其翻转功能。
  • 虽然我的钱,我只是扩展JButton或更好,只需使用JButton,让它看起来像我想要的方式,而不是试图重新发明轮子。

如,

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

@SuppressWarnings("serial")
public class Main2 extends JPanel {
   private static final Color TAN = Color.decode("#F4EBC3");
   private static final Color DARK_GREEN = Color.decode("#668284");
   private static final Color BUTTON_COLOR = Color.decode("#A2896B");
   private static final Color BORDER_COLOR = Color.decode("#333333");
   private static final Color BUTTON_ROLLOVER_COLOR = Color.decode("#F5B66E");
   private static final String TITLE = "Trivia Game!";
   private static final Font TITLE_FONT = new Font("Courier", Font.BOLD, 24);
   private static final int PREF_W = 500;
   private static final int PREF_H = PREF_W - 30;
   private JButton startButton;
   private JButton howToPlayButton;
   private JButton quitButton;


   public Main2() {
      JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
      titleLabel.setFont(TITLE_FONT);
      int blGap = 15;
      titleLabel.setBorder(BorderFactory.createEmptyBorder(blGap, blGap, blGap, blGap));
      JPanel titlePanel = new JPanel(new GridBagLayout());
      titlePanel.setBackground(DARK_GREEN);
      titlePanel.add(titleLabel);

      JPanel centerInnerPanel = new JPanel(new GridLayout(0, 1, blGap, 2 * blGap));
      centerInnerPanel.setOpaque(false);
      centerInnerPanel.setBorder(BorderFactory.createEmptyBorder(blGap, blGap, blGap, blGap));
      centerInnerPanel.add(startButton = createButton("Start"));
      centerInnerPanel.add(howToPlayButton = createButton("How To Play"));
      centerInnerPanel.add(quitButton = createButton("Quit?"));

      JPanel centerOuterPanel = new JPanel(new GridBagLayout());
      centerOuterPanel.setBackground(TAN);
      centerOuterPanel.add(centerInnerPanel);


      setLayout(new BorderLayout());
      add(titlePanel, BorderLayout.PAGE_START);
      add(centerOuterPanel, BorderLayout.CENTER);
   }

   private JButton createButton(String name) {
      final JButton button = new JButton(name);
      button.setFont(TITLE_FONT.deriveFont(20F));
      button.setBackground(BUTTON_COLOR);
      Border emptyBorder = BorderFactory.createEmptyBorder(5, 25, 5, 25);
      Border lineBorder = BorderFactory.createLineBorder(BORDER_COLOR);
      Border nestedBorder = BorderFactory.createCompoundBorder(lineBorder, emptyBorder);
      button.setBorder(nestedBorder);


      button.getModel().addChangeListener(new ChangeListener() {

         @Override
         public void stateChanged(ChangeEvent e) {
            ButtonModel model = (ButtonModel)e.getSource();
            if (model.isRollover()) {
               button.setBackground(BUTTON_ROLLOVER_COLOR);
            } else {
               button.setBackground(BUTTON_COLOR);
            }
         }
      });

      return button;
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      int w = Math.max(super.getPreferredSize().width, PREF_W);
      int h = Math.max(super.getPreferredSize().height, PREF_H);

      return new Dimension(w, h);
   }

   private static void createAndShowGui() {
      Main2 mainPanel = new Main2();

      JFrame frame = new JFrame("Main2");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}