Search code examples
javaswingrepaintjcomponent

java - how do jcomponents draw?


im wondering how a jcomponent gets painted on the screen, is it painted inside paintComponent() from Graphics? Or is it painted separately. Im asking this because its weird how a jbutton changes color on mousehover even though repaint() is never called.

Thanks for your time.


Solution

  • Components are painted with their paint method. repaint is just a useful method that will call paint at some point in the near future on the Event Dispatch Thread.


    When the mouse enters a JButton, the following method is called (for JButtons with a default UI):

    public void mouseEntered(MouseEvent e) {
        AbstractButton b = (AbstractButton) e.getSource();
        ButtonModel model = b.getModel();
        if (b.isRolloverEnabled() && !SwingUtilities.isLeftMouseButton(e)) {
            model.setRollover(true);
        }
        if (model.isPressed())
                model.setArmed(true);
    }
    

    ButtonModel.setRollover will fire a ChangeEvent, which is handled by AbstractButton in the following way:

    public void stateChanged(ChangeEvent e) {
        Object source = e.getSource();
    
        updateMnemonicProperties();
        if (isEnabled() != model.isEnabled()) {
            setEnabled(model.isEnabled());
        }
        fireStateChanged();
        repaint();
    }
    

    So repaint is called when the mouse enters a JButton.