-2

隣接する2つのラジオボタンをクリックすると、これらのボタンの間に線が引かれます.2つの水平または垂直のラジオボタンが選択されている場合にのみ線が描画される条件をコードに入れます。それ以外の場合はエラーメッセージが表示されます........それは私にとってはうまくいきますが、ランダムに2つのラジオボタンをクリックすると、理解できない例外がスローされます. prog をコンパイルすると表示されます........注: C:\Users\MUHAMMAD Umair\Desktop\ComponentLinkerTest.java は未チェックまたは安全でない操作を使用します。注: 詳細については、-Xlint:unchecked で再コンパイルしてください。

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 ();
        }
    }
}
4

1 に答える 1

1

あなたは範囲チェックをしません...

最後のボタンが最後の行にある場合、または2番目のボタンが最初の行にある場合、これにより例外が発生します

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

チェックが (0) 未満または (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)) {

代替で更新

わかりました、そのif声明は私の頭を悩ませていました...だから私は別の戦術を取りました...

基本的に、代わりに、各ボタンのインデックスを見つけて、各ボタンが互いに離れている距離を計算しました.1つまたは5つのインデックスしか離れていません...

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 ");
}

そしてそのindexOf方法は…

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;

}

余談ですが、 の使いすぎにも注意してくださいstatic。これは悪い設計を示唆しています

于 2013-06-12T05:50:33.147 に答える