Search code examples
javaswingjlabeljtextfield

Which Swing Component to use?


I am a newbie to Java and GUI programming. I have the following question.

In my GUI, I have a JTextField with a JLabel which reads "Radius". Now I want to put an icon next to the JTextField with a question mark which on clicked explains in details what the JLabel means. For instance, in this case, it should pop up a message explaining "The radius of the circle to be drawn on the image". The message should disapper when the mouse is moved Below is a pictorial description of what I am trying to implement.

My question is very basic. I want to know which Swing Component can I use to implement this? I tried looking it up on the web but I did not know which component to look for. Any help and suggestions would be appreciated. enter image description here


Solution

  • You can do it very easily. All you need to do is just use a JLabel and place no text on it. Rather, place an image on it

    This code let's you set the Image to the JLabel

    import java.awt.FlowLayout;
    
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class AddingIconJLabel {
      public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame();
        frame.setTitle("JLabel Test");
        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        ImageIcon imageIcon = new ImageIcon("yourFile.gif");
        JLabel label = new JLabel(imageIcon);
    
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
      }
    }
    

    Secondly, Place the ToolTip on the JLabel to make your text appear on when you over on the Image

    Here'e the helpful code hint for that

    JLabel label = new JLabel("Username");
    label.setToolTipText("Enter your username");