Results 1 to 9 of 9

Thread: Array of JButtons?

Threaded View

  1. #7
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    I guess you could create custom JButton's and add in an instance member which would be set to a certain value when each instance of each JButton is created then query the button later on to get the value.
    Code:
      import java.awt.*; 
      import javax.swing.*;
      import java.awt.event.*; 
    
      class XButton extends JButton{
        
       private String whichbutton;
    
       public XButton(){
          this("rubberbutton");
       }
     
       public XButton(String whichbutton){
         this.whichbutton = whichbutton; 
        }
    
       public XButton(String name, String whichbutton){
         super(name);
         this.whichbutton = whichbutton;  
        }
       public String getButton(){return whichbutton;}
      }
    
     public class X{
       static JLabel jl; 
       public static void main(String[] args){
         JButton[] jb = new JButton[3]; 
         jb[0] = new XButton(); 
         jb[1] = new XButton("metalbutton");
         jb[2] = new XButton("Cork Button","corkbutton");
    
         JFrame jf = new JFrame(); 
         Container c = jf.getContentPane();
         JPanel p1 = new JPanel();
         JPanel p2 = new JPanel();
         jl = new JLabel();    
     
         for(int i = 0; i < jb.length; ++i){  
          jb[i].addActionListener(new ButtonListener());
          p1.add(jb[i]);
        }
          p2.add(jl);
          c.add(p1,BorderLayout.NORTH); 
          c.add(p2,BorderLayout.SOUTH);       
         
        jf.addWindowListener(new WindowAdapter(){
         public void windowClosing(WindowEvent evt){
           System.exit(0);
         }
        });
        
        jf.setSize(400,300); 
        jf.setVisible(true);
     
      }
      static class ButtonListener implements ActionListener{ 
        public void actionPerformed(ActionEvent evt){
         XButton xb = (XButton) evt.getSource() ; 
         jl.setText("Button " + xb.getButton() + " was pressed");
      }
     }
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width