'Dynamic'에 해당되는 글 1건

  1. 2021.12.20 java swing 동적 툴팁, 멀티 라인 툴팁

java swing 동적 툴팁, 멀티 라인 툴팁

프로그래밍/java 2021. 12. 20. 22:28
반응형

getToolTipText 메소드 override 로 구현

https://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#getToolTipText-java.awt.event.MouseEvent-

 

JComponent (Java Platform SE 8 )

Returns true if a paint triggered on a child component should cause painting to originate from this Component, or one of its ancestors. Calling repaint(long, int, int, int, int) or paintImmediately(int, int, int, int) on a Swing component will result in ca

docs.oracle.com

package test.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;

// dynamic tooltip
public class MainTest {
    public static void main(String[] args) {
        MainUI mainUI = new MainUI();
        mainUI.setVisible(true);
    }
}

class ToolTipButton extends JButton {
    boolean mIsNum = true;

    public ToolTipButton(String text) {
        super(text);
    }

    // 1. use setToolTipText
    @Override
    public String getToolTipText(MouseEvent event) {
        if (mIsNum) {
            setToolTipText("0123456789");
        }
        else {
            setToolTipText("ABCDEFG");
        }
        mIsNum = !mIsNum;
        return super.getToolTipText(event);
    }

    // 2. return text directly
    @Override
    public String getToolTipText(MouseEvent event) {
        String text = "";
        if (mIsNum) {
            text = "0123456789";
        }
        else {
            text = "ABCDEFG";
        }
        mIsNum = !mIsNum;
        return text;
    }
}

class MainUI extends JFrame {

    MainUI() {
        setPreferredSize(new Dimension(400, 300));
        setLayout(new FlowLayout());
        JButton button = new ToolTipButton("TEST");
        button.setToolTipText("");
        button.setPreferredSize(new Dimension(100, 100));
        add(button);
        pack();
    }
}

멀티라인 툴팁

setToolTipText("<html>a<br>b</html>");
반응형
: