views:

13

answers:

3

I want to have a set of JRadioButtons and next to each one a little 'i' image which when clicked will open a new window with information about the text next to the radio button. What is the best component to use to align the little 'i' label next to the Radio button?

+1  A: 

Pass your image as a javax.swing.ImageIcon to the constructor of the JRadioButton. Then listen for mouse clicks on the button and check if the coordinates of the mouse pointer are within the boundaries of your image.

Thomas
+1  A: 

There are some possibilties to do this with style.

The simplest one is obviously to put a JButton with the "i" image next to your radio button. Using the right layout manager (GridBagLayout of course) will allow you to align both easily.

Another one could be to set a client property in your radio button, then let your radio button renderer (in the look'n'feel) use this client property to display the "i" icon next to your button. Unfortunatly, it's a little harder top implement since it requires you to manage correctly the radio button bounds to incldue the image when required (which is also achieved in LnF, but not that easy to find).

Riduidel
A: 

I find something like a JLabel the most useful for the type of component for the 'i' part of the problem. JLabels like all components can have mouse listeners added to them and from there you have the required access to trigger something when the user clicks on one.

In the code below I have used a simple FlowLayout as that feels like a logical fit to provide the horizontal alignment if you don't fancy using a GridBayLayout. Ultimately it will depend on how you are setting up your layout but something like a FlowLayout helps in these situations.

Look at the following code for an example:

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                final JFrame f = new JFrame();
                f.setLayout(new BorderLayout());
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JPanel p = new JPanel(new FlowLayout());
                JLabel l = new JLabel(new ImageIcon(Main.class.getResource("info.png")));
                l.addMouseListener(new MouseAdapter(){
                    @Override
                    public void mouseReleased(MouseEvent e) {
                        JOptionPane.showMessageDialog(f, "Clicked");
                    }
                });
                p.add(new JRadioButton());
                p.add(l);

                f.add(p, BorderLayout.CENTER);
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }
}
gencoreoperative