-2

when i click adjacent two radio button then a line drawn between these button i put conditions in my code that line only will draw when two horizontal or vertical radio button selected else it show a error message ........... it works for me but if i click randomly two radio button it will throw an exception which i cant understand please give some discription about answer because i am beginner too............ and what is this means it shows when i compile prog..........Note: C:\Users\MUHAMMAD Umair\Desktop\ComponentLinkerTest.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.util.*;

/**
 * @see http://stackoverflow.com/a/12389479/909085
 */

public class ComponentLinkerTest extends JComponent
{
   // private Map<JComponent, JComponent> linked;
    Map<JComponent, java.util.List<JComponent> > linked;// = new HashMap<>();
    int n=1;
    public ComponentLinkerTest ()
    {
        super ();
        linked = new HashMap ();
    }
 static JRadioButton[] button = new JRadioButton[25];
    public void gui()
    {
        setupLookAndFeel ();

                JFrame frame = new JFrame ();

                linker = new ComponentLinkerTest ();
                frame.setGlassPane ( linker );
                linker.setVisible ( true );

                JPanel content = new JPanel ();
                content.setLayout ( new GridLayout ( 5, 5, 5, 5 ) );
                content.setBorder ( BorderFactory.createEmptyBorder ( 5, 5, 5, 5 ) );
                frame.add ( content );

                int i;
                for (i = 0; i < 25; i++ )
                {
                   // final JButton button = new JButton ( "Button" + i );
                   button[i] = new JRadioButton();
                        //  panel.add(fontButtons[i]);
                    button[i].addActionListener ( new ActionListener ()
                    {
                            public void actionPerformed ( ActionEvent e )
                            {
                                    link ((JRadioButton) e.getSource() );
                            }
                    } );
                    content.add ( button [i]);
                }

                frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
                frame.pack ();
                frame.setLocationRelativeTo ( null );
        frame.setVisible ( true );
    }

    /*public void link ( JComponent c1, JComponent c2 )
    {
        linked.put ( c1, c2 );
        repaint ();
    }*/

    public void link ( JComponent c1, JComponent c2 )
            {
                if(linked.containsKey(c1)){
                    linked.get(c1).add(c2);
                }else{
                java.util.List<JComponent> list = new LinkedList<>();
                list.add(c2);
                linked.put ( c1, list );
                }
                repaint ();
        }

  /*  protected void paintComponent ( Graphics g )
    {
        Graphics2D g2d = ( Graphics2D ) g;
        g2d.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

        g2d.setPaint ( Color.BLACK );
        for ( JComponent c1 : linked.keySet () )
        {
            Point p1 = getRectCenter ( getBoundsInWindow ( c1 ) );
            Point p2 = getRectCenter ( getBoundsInWindow ( linked.get ( c1 ) ) );
           /* Stroke stroke = new BasicStroke(8//,
                /*BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0,
                new float[] { 12, 12 }, 0);
g2d.setStroke(stroke);
            g2d.setColor(Color.RED);
            g2d.drawLine ( p1.x, p1.y, p2.x, p2.y );
        }
    }*/

    @Override
     protected void paintComponent ( Graphics g )
            {
                super.paintComponent(g);
                Graphics2D g2d = ( Graphics2D ) g;
                g2d.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

                g2d.setPaint ( Color.BLACK );
                for ( JComponent c1 : linked.keySet () )
                {
                    for(JComponent c2 : linked.get(c1)){
                    Point p1 = getRectCenter ( getBoundsInWindow ( c1 ) );
                    Point p2 = getRectCenter ( getBoundsInWindow ( c2 ) );
                   /* Stroke stroke = new BasicStroke(8//,
                        /*BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0,
                        new float[] { 12, 12 }, 0);
        g2d.setStroke(stroke);*/
                if(n==1)
                {
                    g2d.setColor(Color.RED);
                    n=2;
                }
                else
                {
                    g2d.setColor(Color.BLUE);
                    n=1;
                }
                    g2d.drawLine ( p1.x, p1.y, p2.x, p2.y );
                    }
                }
        }

    private Point getRectCenter ( Rectangle rect )
    {
        return new Point ( rect.x + rect.width / 2, rect.y + rect.height / 2 );
    }

    private Rectangle getBoundsInWindow ( Component component )
    {
        return getRelativeBounds ( component, getRootPaneAncestor ( component ) );
    }

    private Rectangle getRelativeBounds ( Component component, Component relativeTo )
    {
        return new Rectangle ( getRelativeLocation ( component, relativeTo ),
                component.getSize () );
    }

    private Point getRelativeLocation ( Component component, Component relativeTo )
    {
        Point los = component.getLocationOnScreen ();
        Point rt = relativeTo.getLocationOnScreen ();
        return new Point ( los.x - rt.x, los.y - rt.y );
    }

    private JRootPane getRootPaneAncestor ( Component c )
    {
        for ( Container p = c.getParent (); p != null; p = p.getParent () )
        {
            if ( p instanceof JRootPane )
            {
                return ( JRootPane ) p;
            }
        }
        return null;
    }

    public boolean contains ( int x, int y )
    {
        return false;
    }

    private static ComponentLinkerTest linker;

    public static void main ( String[] args )
    {
        ComponentLinkerTest ct = new ComponentLinkerTest();
        ct.gui();
    }



    private static JRadioButton last = null;

    private static void link ( JRadioButton buton )
    {
        int a=0;
        int i;
        if ( last == null )
        {
            last = buton;
            System.out.println(last.getX());
        }
        else
        {
            for( i=0 ;i<25 ;i++)
            {
                if(buton == button[i])
                {
                    if(button[i-1] == last || button[i+1]==last || button[i-5] == last || button[i+5]==last)
                    {
                            System.out.println("in cond");
                            linker.link ( last, buton );
                            buton.setSelected(false);
                            last.setSelected(false);
                            last = null;
                    }
                    else
                    {
                            System.out.println("out cond");
                            buton.setSelected(false);
                            last.setSelected(false);
                            last = null;
                            JOptionPane.showMessageDialog(null,"Wrong position clicked ");
                    }
                    break;
                }
                else
                {
                    System.out.println("button not found");
                }
            }

       }
    }

    private static void setupLookAndFeel ()
    {
        try
        {
            UIManager.setLookAndFeel ( UIManager.getSystemLookAndFeelClassName () );
        }
        catch ( ClassNotFoundException e )
        {
            e.printStackTrace ();
        }
        catch ( InstantiationException e )
        {
            e.printStackTrace ();
        }
        catch ( IllegalAccessException e )
        {
            e.printStackTrace ();
        }
        catch ( UnsupportedLookAndFeelException e )
        {
            e.printStackTrace ();
        }
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 1) Please add an upper case letter at the start of sentences. Also use a capital for the word I, and abbreviations and acronyms like JEE or WAR. This makes it easier for people to understand and help. 2) You've have so far not asked a question (let alone a specific, answerable question). What *is* your question? 3) Don't go compacting all your troubles into a single post. The idea of SO is that each thread be a single Q&A (SO is not a 'one stop, fix your code' shop). – Andrew Thompson Jun 12 '13 at 05:40
  • I only get a `Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException` if I select the last radio button (bottom right corner) as the second option. – MadProgrammer Jun 12 '13 at 05:47
  • I face a problem which i described in discription if u have any solution then help,java is new for me – Umair Manzoor Jun 12 '13 at 05:50
  • @Madprogrammer can you give me more discription about this exception ?? – Umair Manzoor Jun 12 '13 at 05:52
  • @UmairManzoor 1- You description doesn't (entirely) make sense. 2- Check answer – MadProgrammer Jun 12 '13 at 05:54
  • @MadProgrammer when i check two radio button which is not adjacent horizontal r vertical and have some distance like if i click last row buton and then click on first row button then it throws an exception still after modify your condition ........... n sory about my poor discription – Umair Manzoor Jun 12 '13 at 06:03
  • @UmairManzoor Added a new approach – MadProgrammer Jun 12 '13 at 06:48

1 Answers1

1

You do no range checking...

This is going to cause an exception if you the last button is the on the last line, or the second button is one the first row

if (button[i - 1] == last || button[i + 1] == last || button[i - 5] == last || button[i + 5] == last)

You need to modify your checks to ensure that they don't extend below (0) or beyond (button.length - 1)...

if ((i > 0 && button[i - 1] == last) ||
        (i < (button.length - 1) && button[i + 1] == last) ||
        (i > 5 && button[i - 5] == last) ||
        (i < (button.length - 1) && button[i - 5] == last)) {

Updated with alternative

Okay, that if statement was doing my head...so I took a different tact...

Basically, instead, I found the index of each button and calculated the distance that each button was from each other, they could only be 1 or 5 indices apart...

int lastIndex = indexOf(last);
int currentIndex = indexOf(buton);

int diff = Math.max(lastIndex, currentIndex) - Math.min(lastIndex, currentIndex);
if (diff == 1 || diff == 5) {
    System.out.println("in cond");
    linker.link(last, buton);
    buton.setSelected(false);
    last.setSelected(false);
    last = null;
} else {
    System.out.println("out cond");
    buton.setSelected(false);
    last.setSelected(false);
    last = null;
    JOptionPane.showMessageDialog(null, "Wrong position clicked ");
}

And the indexOf method...

protected static int indexOf(JRadioButton btn) {

    int index = -1;
    for (int value = 0; value < button.length; value++) {
        if (button[value].equals(btn)) {
            index = value;
            break;
        }
    }

    return index;

}

As a side note, I'd also beware of over using static. This suggest a bad design

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366