R
R
roman38472014-04-05 14:30:50
Java
roman3847, 2014-04-05 14:30:50

Java Swing button that changes shapes on hover

Need a button that changes shape from rectangular to round on hover.
It's not a problem to create a round button, but I can't make a button that changes its shape.
Round button:

public class RoundButton extends JButton
{
 public RoundButton(String label)
 {
  super(label); 
  Dimension size = getPreferredSize();
  // Делаем нашу кнопочку вписанной в квадрат.
  // Дабы не получился у нас овал:)
  size.width = size.height = Math.max(size.width, size.height);
  setPreferredSize(size);
  // Не закрашиваем кнопочку.
  setContentAreaFilled(false);
 }
 // Рисуем нашу кнопочку.
 protected void paintComponent(Graphics g)
 {
  if (getModel().isArmed())
  {
   // Устанавливаем цвет по умолчанию.
   g.setColor(Color.lightGray);
  } 
  else
  {
   g.setColor(getBackground());
  }
  // Рисуем окружность.
  g.fillOval(0, 0, getSize().width-1, getSize().height-1);
  // Прорисовываем сам JButton.
  super.paintComponent(g);
 }
 // Рисуем бордюр кнопочки.
 protected void paintBorder(Graphics g)
 {
  g.setColor(getForeground());
  g.drawOval(0, 0, getSize().width-1, getSize().height-1);
 }

 // Определяем принадлежность точки к нашей кнопочки.
 Shape shape;
 public boolean contains(int x, int y)
 {
  // Если кнопка изменилась в размере
  // создаем новый объект shape.
  if (shape == null ||!shape.getBounds().equals(getBounds()))
  {
   shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
  }
  // Возвращаем true если точка принадлежит
  // и false если не принадлежит кнопке.
  return shape.contains(x, y);
 }

As I understand it, the MouseListener needs to be built into the class and there should be something like this:
class RoundButton extends JComponent implements MouseListener {
 
    public RoundButton() {
       ....
        addMouseListener(this);
    }

    public void paintComponent(Graphics g) {
        ....
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }
}

How to do it? I will be glad for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fil, 2014-04-05
@roman3847

You have a paintComponent called on redraw that draws the button. It is necessary to make sure that this method knows what to draw now, that is, it knows where the mouse is. In the mouse listener (it can be the button itself, as you gave in the example, or maybe another object), you can add the value bool isMouseEntered; in mouseEntered() write isMouseEntered = true, and vice versa false in mouseExited(). It remains to add something like this to paintComponent:

if(isMouseEntered){
  //рисуем круглую кнопку 
}else{
  //вызываем дефолтный рисовальщик или сами рисуем.
  super.paintComponent(g);
}

And don't forget to add addMouseListener(this) in the button's constructor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question