Domanda

I made a program containing a lot of JCheckBox and JTextField and other components.

I have a LinkedHashMap containing the text of each JCheckBox as a key, and an explanation for each key as the map value. As soon as my mouse points to the text of one JCheckedBox, I want a JLabel to appear right at the mouse coordinates, displaying the value of the corresponding key.

I read that to be able to set my JLabel position wherever I want on the main JPanel, I needed to set this main JPanel's layout to null, then to repaint it. It works.

However when I switch from on JCheckBox to another, their position suddenly change and get back to original, in a blink of an eye. Moreover, the JLabel position (Y axis) is like 100 pixels below the mouse.

Could you please help me improving this feature? You will find below the necessary code for the mouseLlistener. "this" refers to the main JPanel, to which I set a layout. "this.lInformation" is the helping JLabel I am using. Maybe there are other and more simple ways around?

public void mouseExited(MouseEvent e) {

    if("JCheckBox".equals( e.getComponent().getClass().getSimpleName() ) ) {
        this.lInformation.setVisible(false);
        this.lInformation = null;
        // Here we make the help label disappear
    }
}


public void mouseEntered(MouseEvent e) {

    String id = e.getComponent().getClass().getSimpleName();
    if("JCheckBox".equals( id ) ) {

    JCheckBox tempCB = (JCheckBox) e.getComponent();
    JPanel tempPanel = (JPanel) tempCB.getParent().getParent();

    this.lInformation = new JLabel( (String) this.FormattedFields.get( tempCB.getText()) );
    this.lInformation.setBounds(e.getXOnScreen(), e.getYOnScreen(), 40, 25);
    this.lInformation.setBorder(BorderFactory.createLineBorder(Color.yellow, 1));
    this.setLayout(null);
    this.add(this.lInformation);
    this.repaint();
    tempPanel.add(this.lInformation);
    this.setVisible(true);
    }
}
È stato utile?

Soluzione

I think that you are looking for ToolTipText, what all you have to do just get the description value you want to appear and set it to the component's tool tip.

for example:

String description = getDescription();
jCheckBox.setToolTipText(description);

This will show the description value when you hover on that Component.

Please Read more about ToolTipText in Swing.

Altri suggerimenti

If you want a component to display on top of another component, you should add it to the layered pane, not the same container.

Recommended reading: http://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html

And: https://weblogs.java.net/blog/alexfromsun/archive/2006/09/a_wellbehaved_g.html

You also might just be talking about a tool tip: http://docs.oracle.com/javase/tutorial/uiswing/components/tooltip.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top