Jake_TheCoder
Jake_TheCoder

Reputation: 57

Swapping JButton elements in Java

updated my code I realized I should have but the actionListener on the JButton (since they're the ones actually doing all the work). My logic is off now on the sorting part. I'm able to get the jButtons to swap values, but I've got the output looking correct, but I'm trying to figure out where I'm screwing up my sorting mechanism. This program "should" work correctly by selecting a start point with the radio button, and selecting a different location for the JButton to swap. (for instance, radio 3 then jbutton 8 would move the 3rd element into the 8th location) I know I'm pretty close, but I've worked myself into a rut and can't see out. Any pointers? (disclaimer This is a bonus points programming 2 assignment).

new code

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class GUIswitch 
{
    public static void main(String[] args) 
    {


        GUIswitchClass myWindow = new GUIswitchClass();
        myWindow.setSize(300,350);
        myWindow.setLocation(100,100);
        myWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        myWindow.setVisible( true );



    }
}
//====================================================================================================================
class GUIswitchClass extends JFrame                                         //fields
{
        JPanel          leftPanel       =   new JPanel();
        JPanel          rightPanel      =   new JPanel();                       
        JPanel          allPanel        =   new JPanel();
        JRadioButton    rdoBut[]        =   new JRadioButton[10];
        JButton         teamBut[]       =   new JButton[10];
        ButtonGroup     rdBtGp          =   new ButtonGroup();
        String          rdoButNum[]     =   {"1","2","3","4","5","6","7","8","9","10"};
        String          teamName[]      =   {"A","BB","CCC","DDDD","EEEEE","FFFFFF",
                                            "GGGGGGG","HHHHHHHH","IIIIIIIII","JJJJJJJJJJ"};
        //String            from;
        //String            to;
        int from;
        int to;
        String fromTo;  //??
        int i;

    public GUIswitchClass()                                                 //constructor
    {
        super("Proj 3");


        fromTo  = setButs();
        //to        = teamBut[ teamName[i] ];

    }
    private String setButs()
    {
        int i;
        leftPanel.setLayout(new GridLayout(10,1));
        rightPanel.setLayout(new GridLayout(10,1));
        for(i=0;i<10;i++)
        {
            rdoBut[i] = new JRadioButton(rdoButNum[i]);
            rdoBut[i].setFont(new Font("Courier", Font.PLAIN, 30) );
            rdBtGp.add(rdoBut[i]);
            leftPanel.add(rdoBut[i]);   
        }

        /*for(i=0;i<10;i++)
            if(rdoBut[i].isSelected() )
            {
                from = Integer.parseInt(rdoBut[i].getText() );
            }
        */
        for(i=0;i<10;i++)
        {
            teamBut[i]  =   new JButton(teamName[i]);
            teamBut[i].setFont(new Font("Courier", Font.PLAIN, 30) );
            teamBut[i].setHorizontalAlignment(SwingConstants.LEFT);
            teamBut[i].addActionListener(new checkHdlr() );
            rightPanel.add(teamBut[i]);
        }

        allPanel.setLayout(new BorderLayout());
            allPanel.add(leftPanel, BorderLayout.WEST);
            allPanel.add(rightPanel, BorderLayout.CENTER);
        add(allPanel);

        return fromTo;



    }
    @SuppressWarnings("unused")
    private class checkHdlr implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            //String userNum;
            //userNum = event.getActionCommand();
            for(i=0;i<10;i++)
                if(rdoBut[i].isSelected() )
                {
                    from = Integer.parseInt(rdoBut[i].getText() );
                }

            for(i=0;i<10;i++)
            {
                if(event.getSource() == teamBut[i])
                {
                    //teamBut[i].
                    teamBut[i].setText(teamName[i]);
                    //to = (int)(teamBut[i]);
                }
            }
            rightPanel.revalidate();                //refresh the panels
            moveTeam(teamName, from, to);
        }
    }   

//--------------------------------------------------------------------------
     public void moveTeam(String teamName[],int from,int to)
      {
        //int             from=0;
        //int             to=0;

        if(from>to)                           //determine direction to move
          moveUp(teamName,from,to);
        else
          moveDown(teamName,from,to);
      }

 //---------------------------------------------------------------------move up
  public static void moveUp(String teamList[], int from, int to)
  {
    String clipboard;
    int    row;

    clipboard = teamList[from];           //copy

    for(row=from;row>to;row--)            //shift others down
      teamList[row] = teamList[row-1];

    teamList[row] = clipboard;            //paste
  }
  //-------------------------------------------------------------------move down
  public static void moveDown(String teamList[], int from, int to)
  {
    String clipboard;
    int    row;

    clipboard = teamList[from];           //copy

    for(row=from;row<to;row++)            //shift others up
      teamList[row] = teamList[row+1];

    teamList[row] = clipboard;            //paste
  }

}

old code

import java.awt.*;
import java.awt.event.*;
import java.util.StringTokenizer;

import javax.swing.*;

public class GUIswitch 
{
    public static void main(String[] args) 
    {


        GUIswitchClass myWindow = new GUIswitchClass();
        myWindow.setSize(300,350);
        myWindow.setLocation(100,100);
        myWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        myWindow.setVisible( true );



    }
}
//====================================================================================================================
class GUIswitchClass extends JFrame                                         //fields
{
        JPanel          leftPanel       =   new JPanel();
        JPanel          rightPanel      =   new JPanel();                       
        JPanel          allPanel        =   new JPanel();
        JRadioButton    rdoBut[]        =   new JRadioButton[10];
        JButton         teamBut[]       =   new JButton[10];
        ButtonGroup     rdBtGp          =   new ButtonGroup();
        String          rdoButNum[]     =   {"1","2","3","4","5","6","7","8","9","10"};
        String          teamName[]      =   {"A","BB","CCC","DDDD","EEEEE","FFFFFF",
                                            "GGGGGGG","HHHHHHHH","IIIIIIIII","JJJJJJJJJJ"};
        String          from;
        String          to;
        String fromTo;
        int i;

    public GUIswitchClass()                                                 //constructor
    {
        super("Swap Elements");


        fromTo  = setButs();
        //to        = teamBut[teamName[i]];

    }
    private String setButs()
    {
        int i;
        leftPanel.setLayout(new GridLayout(10,1));
        rightPanel.setLayout(new GridLayout(10,1));
        for(i=0;i<10;i++)
        {
            rdoBut[i] = new JRadioButton(rdoButNum[i]);
            rdoBut[i].setFont(new Font("Courier", Font.PLAIN, 30) );
            rdoBut[i].addActionListener(new checkHdlr() );
            rdBtGp.add(rdoBut[i]);
            leftPanel.add(rdoBut[i]);   
        }

        for(i=0;i<10;i++)
        {
            teamBut [i] =   new JButton(teamName[i]);
            teamBut[i].setFont(new Font("Courier", Font.PLAIN, 30) );
            teamBut[i].setHorizontalAlignment(SwingConstants.LEFT);
            rightPanel.add(teamBut[i]);
        }

        allPanel.setLayout(new BorderLayout());
            allPanel.add(leftPanel, BorderLayout.WEST);
            allPanel.add(rightPanel, BorderLayout.CENTER);
        add(allPanel);

        return fromTo;



    }
    @SuppressWarnings("unused")
    private class checkHdlr implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            String userNum;
            userNum = event.getActionCommand();

        }
    }   

//--------------------------------------------------------------------------
     public static void moveTeam(String teamName[],String fromTo)
      {
        int             from;
        int             to;

        if(from>to)                           //determine direction to move
          moveUp(teamName,from,to);
        else
          moveDown(teamName,from,to);
      }

 //---------------------------------------------------------------------move up
  public static void moveUp(String teamList[], int from, int to)
  {
    String clipboard;
    int    row;

    clipboard = teamList[from];           //copy

    for(row=from;row>to;row--)            //shift others down
      teamList[row] = teamList[row-1];

    teamList[row] = clipboard;            //paste
  }
  //-------------------------------------------------------------------move down
  public static void moveDown(String teamList[], int from, int to)
  {
    String clipboard;
    int    row;

    clipboard = teamList[from];           //copy

    for(row=from;row<to;row++)            //shift others up
      teamList[row] = teamList[row+1];

    teamList[row] = clipboard;            //paste
  }
  //---------------------------------------------------------------------display
  public static void disp(String teamList[])
  {
    int r;
    for(r=0;r<10;r++)
      System.out.printf("%2d %s\n",r+1,teamList[r]);
  }
}

Upvotes: 2

Views: 2792

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347204

I'd replace the JRadioButtons with JCheckBoxs, mostly because you can have two selected at the same time and it makes more sense to allow check boxes to be selected this way then it does to allow radio buttons.

I would create a single action listener for all the check boxes, so every click goes through it.

In the action listener, I would use a java.util.List to keep track of the currently selected options (you could walk the array, but I found this to be simpler).

When the list contains two items I would...

Some thing like...

int index0 = leftPanel.getComponentZOrder(cb0);
int index1 = leftPanel.getComponentZOrder(cb1);

Component comp0 = rightPanel.getComponent(index0);
Component comp1 = rightPanel.getComponent(index1);

rightPanel.setComponentZOrder(comp0, index1);
rightPanel.setComponentZOrder(comp1, index0);

You'll also need to revalidate() on the frame to update the layout ;)

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

I wouldn't swap JButtons per se, but rather give the JButton's AbstractActions and simply swap these Actions as that is immeasurably easier to do. Or you could swap the JButton's text and actionCommand (you should do both if you're going this route), but that would involve doing parallel swaps and doesn't feel as clean to me.

Upvotes: 4

Related Questions