Wednesday, August 15, 2012

Add JList Data on Selecting a Radio Button

Here is some code displays a different JList content depending on which radio button is selected.

First here are the forms


here is the code. It uses validate() and repaint() methods on the JFrame to refresh the form

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;


public class mainForm extends JFrame implements ItemListener{
 private JPanel panel;
 private JPanel listPanel;
 private JPanel borderPanel;
 private JRadioButton one;
 private JRadioButton two;
 private JList list;
 private String[] arrayOne= new String[]{"Monday", "Tuesday", "Wednesday"};
 private String[] arrayTwo=new String[]{"Thursday", "Friday", "Saturday"};
 
 public mainForm(){
  CreatePanel();
  this.add(borderPanel);
  this.setBounds(100, 100, 200, 200);
  this.setVisible(true);
 }
 
 private void CreatePanel(){
  panel=new JPanel();
  borderPanel=new JPanel(new BorderLayout());
  
  one=new JRadioButton("one");
  one.addItemListener(this);
  two=new JRadioButton("two");
  two.addItemListener(this);
  list=new JList();
  
  ButtonGroup group = new ButtonGroup();
  group.add(one);
  group.add(two);
  
  panel.add(one);
  panel.add(two);
  listPanel=new JPanel();
  listPanel.add(list);
  
  borderPanel.add(panel, BorderLayout.CENTER);
  borderPanel.add(listPanel, BorderLayout.SOUTH);
  
 }

 @Override
 public void itemStateChanged(ItemEvent arg0) {

  
  Object source = arg0.getSource();
  if(source.equals(one)){
   
   list.removeAll();
   list.setListData(arrayOne);
   
   
  }
  else{
   list.removeAll();
   list.setListData(arrayTwo);
  }
  
  //borderPanel.add(listPanel, BorderLayout.SOUTH);
  //this.add(borderPanel);
  this.validate();
  this.repaint(); 
 }
 
 
}


No comments:

Post a Comment