Basically im practising java and came up on a challenge that i have yet to overcome.

I have added an ActionListener but i want each button to have there own Action.

Also what i wanted is to hide the contents in the button.

Would be much appreciated to see how this is done.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyGrid {
    static JButton[] btnarray;
    static JFrame main;

    public static void main(String[] args)
    	{
             btnarray = new JButton[6];
             main = new JFrame("Grid with Fractions");
             main.setVisible(true);
             main.setLayout(new GridLayout(3,3));
             main.setBounds(350,250,350,350);
             main.setResizable(true);

 			for (int i = 0; i < 6 ; i++)
             	{

                btnarray[i] = new JButton(i/2+"");
                main.add(btnarray[i]);



                //Add action listener to button
        btnarray[i].addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
                //Execute when button is pressed
                System.out.println("You clicked the button");
                //System.out.println("Print" +btnarray[i]);
            }
        });

                }
     main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when the user press "X"




}}

Recommended Answers

All 19 Replies

I have added an ActionListener but i want each button to have there own Action.

make a conditional for every array index to execute a specific action

Also what i wanted is to hide the contents in the button.

what contents would you want to hide?

I know im suppose to make a condition for each index of the array but im unaware of the syntax

I want to hide the numbers in the buttons

The JComponent class's clientProperties methods could be used to store information in each button object. The methods provide access to a hashtable in each component.

Do you want to add an ActionListener to all buttons in the btnArray?
There are 2 code-snippets based on that, here:

Here are the code-snippets:

Code-Snippet #1 :

/**
* NOTE:
* This code-snippet only provides the button tutorial.
* Not any other java code.
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyGrid extends JFrame implements ActionListener
{
   private JButton[] btnArray = new JButton[6];
   
   public MyGrid()
   {

       setTitle("GridWithFractions");
       setLayout(new GridLayout(3,3));
       setBounds(350,250,350,350);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
       setVisible(true);

       for (int i=0; i<btnArray.length; i++)
       {
           btnArray[i].addActionListener(this);
           btnArray[i].setText("Button #"+i);
           btnArray[i].setOpaque(false);
           btnArray[i].setVisible(true);
           add(btnArray[i]);    
       }
       
   }
   // Maybe the interesting part
   public void actionPerformed(ActionEvent e)
   {
       if (e.getSource() == btnArray[0])
       {
           // Do something
       }
     
       else if (e.getSource() == btnArray[1])
       {
          // Do something
       }
       
       else if (e.getSource() == btnArray[2])
       {
          // Do something
       }

       else if (e.getSource() == btnArray[3])
       {
          // Do something
       }
       
       // I think you get how it works from now..
       ...
   }

   public static void main(String[] args)
   {
       java.awt.EventQueue.invokeLater(new Runnable()
       {
           public void run()
           {
               JFrame.setDefaultLookAndFeelDecorated(true);
               JDialog.setDefaultLookAndFeelDecorated(true);
               try
               {
                   UIManager.setLookAndFeel(
                        "javax.swing.plaf.metal.MetalLookAndFeel");
               }
               catch (Exception ex)
               {
                   ex.printStackTrace();
               }
              
               new MyGrid();
          }
      });
   }
}

Code-Snippet #2 :

/**
* NOTE:
* This code-snippet only provides the button tutorial.
* Not any other java code.
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyGrid extends JFrame implements ActionListener
{
   private JButton[] btnArray = new JButton[6];
   
   public MyGrid()
   {

       setTitle("GridWithFractions");
       setLayout(new GridLayout(3,3));
       setBounds(350,250,350,350);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
       setVisible(true);
       
       // This is different from code-snippet #1
       for (int i=0; i<btnArray.length; i++)
       {
           btnArray[i].addActionListener(new ActionListener()
           {
               public void actionPerformed(ActionEvent e)
               {
                   btnArray_actionPerformed(e);
               }
           });
           btnArray[i].setText("Button #"+i);
           btnArray[i].setOpaque(false);
           btnArray[i].setVisible(true);
           add(btnArray[i]);    
       }
       
   }
   // Added for implementation purposes
   public void actionPerformed(ActionEvent e){}

   // This may be the interesting part which differs from the other
   // Code-Snippet, The buttons have there own method...
   public void btnArray_actionPerformed(ActionEvent e)
   {
      if (e.getSource() == btnArray[0])
      {
          // Do something..
      }
    
      else if (e.getSource() == btnArray[1])
      {
          // Do something..
      }
      
      else if (e.getSource() == btnArray[2])
      {
          // Do something..
      }
    
      // Hopefully you can see the pattern which is going on here...
      // Just continue the btn-source
      ...
   }


   public static void main(String[] args)
   {
       java.awt.EventQueue.invokeLater(new Runnable()
       {
           public void run()
           {
               JFrame.setDefaultLookAndFeelDecorated(true);
               JDialog.setDefaultLookAndFeelDecorated(true);
               try
               {
                   UIManager.setLookAndFeel(
                        "javax.swing.plaf.metal.MetalLookAndFeel");
               }
               catch (Exception ex)
               {
                   ex.printStackTrace();
               }
              
               new MyGrid();
          }
      });
   }
}

Well, that was pretty much it.
Leave a comment if this was what you meant,
or if this is considered helpful.

Hope it works.

Got a probable idea of what you meant with "Hide the contents of the buttons":

Code-Snippet:

for (int i=0; i<6; i++)
   {
      btnArray[i] = new JButton();
      btnArray[i].setOpaque(false); // You probably dont want an opaque button.
      btnArray[i].setVisible(true);

      // This is probably the necessary code:
      btnArray[i].setContentAreaFilled(false);
      btnArray[i].setBorderPainted(false);
   }

I tried to run your code but im getting an error here

public class MyGrid(error) extends JFrame implements ActionListener
{
   private JButton[] btnArray = new JButton[6];
   
   public MyGrid()

Error: The serializable class MyGrid2 does not declare a static final serialVersionUID field of type long


Im trying to implement what i have learnt from your coding, but its coming up without the buttons.

import javax.swing.*;
import java.awt.*;


import java.awt.event.ActionEvent;

public class MyGridTest {
    static JButton[] btnarray;
    static JFrame main;

    public static void main(String[] args)
    	{
             btnarray = new JButton[6];
             main = new JFrame("Grid with Fractions");
             main.setVisible(true);
             main.setLayout(new GridLayout(3,3));
             main.setBounds(350,250,350,350);
             main.setResizable(true);
             main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when the user press "X"

 			for (int i = 0; i < 6 ; i++)
             	{
 				btnarray[i].addActionListener(null);
                btnarray[i] = new JButton(i/2+"");
                main.add(btnarray[i]);

             	}}

                //Add action listener to button
        
            public void actionPerformed(ActionEvent g)
            {
            	if (g.getSource() == btnarray[0])
                {
            		System.out.println("You clicked the button 1");
                }
              
                else if (g.getSource() == btnarray[1])
                {
                	System.out.println("You clicked the button 2");
                }
                
                else if (g.getSource() == btnarray[2])
                {
                	System.out.println("You clicked the button 3");
                }
            }
        
}

I did not try to implement hiding the buttons as yet because i wasnted to ge this running first.

Try moving the call to setVisible to after you have added everything you want shown.

Error: The serializable class MyGrid2 does not declare a static final serialVersionUID field of type long

Serialisable classes are supposed to have a serialVersionUID field so, in theory, you can update the serialisation in the future and know which version you are using. In practice this is complete rubbish, but the compiler warning is still there.
Just add this line to your class and forget about it:

private static final long serialVersionUID = 1L;

Sorry, I forgot something quite important in my code..
I was quite tired when I wrote that..

This is what you should add, in order for the code to work perfectly:

// Where buttons are initialized
for (int i=0; i<btnArray.length; i++)
{
    btnArray[i] = new JButton("Button #"+i); // This should be added to the code.
    // Same code as before here..
}

Now the buttons should appear.
Hope that will work.

lol @ 117. Thanks, but i tried another method, its a bit long but it worked.

Unfortunately i could not get the content of the buttons to be hidden.

In this code when i click a button a different action is carried out. Suppose i wanted to print out the number in the button and compare it with another button to test if its match

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyGrid {
   // static JButton[] btnarray;
    static JFrame main;

//Missing Codes
   
 //---------------Assigning Values to Buttons---------------//
		JButton button = new JButton("1");
        JButton button1 = new JButton(" 2");
        JButton button2 = new JButton(" 3");
        JButton button3 = new JButton(" 4");
        JButton button4 = new JButton(" 5");
        JButton button5 = new JButton(" 6");
        JButton button6 = new JButton(" 7");
        JButton button7 = new JButton(" 8");
        JButton button8 = new JButton(" 9");



  //---------------Adding Butttons to Frame---------------//
       main.add(button);
       main.add(button1);
       main.add(button2);
       main.add(button3);
       main.add(button4);
       main.add(button5);
       main.add(button6);
       main.add(button7);
       main.add(button8);



//---------------Action Listeners for the Nine Buttons---------------//

        button.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
             System.out.println("You clicked the button 1");
            }
        });

        button1.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
                 System.out.println("You clicked the button 2");
              }
        });

        button2.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
                 System.out.println("You clicked the button 3");
              }
        });


      button3.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
                 System.out.println("You clicked the button 4");
              }
        });

        button4.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
                 System.out.println("You clicked the button 5");
              }
        });

button5.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
                 System.out.println("You clicked the button 6");
              }
        });

button6.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
                 System.out.println("You clicked the button 7");
              }
        });

button7.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
                 System.out.println("You clicked the button 8");
              }
        });

button8.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
                 System.out.println("You clicked the button 9");
              }
        });

}}

print out the number in the button and compare it with another button to test if its match

What do you want to compare?
If the two buttons have the same labels?
or if two button reference variables refer to the same button?

Yes I want to compare the button labels.
When we find two that match a message show then the contents of the buttons are hidden again.

Im trying to implement something like a memory matching game.

The JButton class has methods for getting the text of the button as a String and the Strings could then be compared.
You can get a reference to the button that caused the event from the event object passed to the action listener method.

Thats what i tried to do, I tried couple text but i could not find that method.

I cannot compile right now, but can you examine this code?

button.addActionListener(new ActionListener()
        	{

            public void actionPerformed(ActionEvent g)
            {
             System.out.println("You clicked the button 1");
		btn=button1.getText; //btn is declared as string

	System.out.println("btn contains:" +btn);
            }
        });

What does the compiler say when you try to compile it? I'll wait until you can get to a compiler.

It worked but how do i compare the numbers in the buttons and if both is equal another set of numbers are generated in the butttons, if not the cottents should be hidden.

See code below:

            button1.addActionListener(new ActionListener()
        {

        public void actionPerformed(ActionEvent g)
        {

             buttn1="1";
             button1.setText(buttn1);
             btn1=Integer.parseInt(buttn1);


            System.out.println("btn contains:" +btn1);


          }
    });

    button2.addActionListener(new ActionListener()
        {

        public void actionPerformed(ActionEvent g)
        {
            buttn2="2";
         button2.setText(buttn2);
         btn2=Integer.parseInt(buttn2); 
            System.out.println("btn contains:" +btn2);



          }
    });


  button3.addActionListener(new ActionListener()
        {

        public void actionPerformed(ActionEvent g)
        {
            buttn3 = "3";
             button3.setText(buttn3);
             btn3=Integer.parseInt(buttn3); 
            System.out.println("btn contains:" +btn3);
          }
    });

What do you exactly mean by hiding the contents of the buttons?

Do you want the button text to disappear or do you want the button to disappear?

Here are some code-fragments, including explanations:

JButton button = new JButton();     // Create's a new JButton

button.setContentAreaFilled(false); // Will disable the contentArea inside the button.
                                    // The button will be transparent, or white if opaque is set to true.

button.setOpaque(false);            // If you use Windows Look And feel, this will look better,
                                    // as there will not be a white square behind the button.

button.setBorderPainted(false);     // Hides the border surrounding the button. However,
                                    // -it is not visible in Windows Look And Feel.

button.setVisible(false);           // Will make the button invisible.
button.setEnabled(false);           // The button will be visible, but not clickable.


//-------------------------------------------------
// Adding icons to buttons
// -Doesn't cover how to make Icons or ImageIcons.
//-------------------------------------------------

Icon image = new ImageIcon(getClass().getResource("img01.png")); // creates an icon which contains an image 
                                                                // -located inside the jar file.

JButton button = new JButton(image);         // Creates a button with above image.
button.setRolloverIcon(image);               // Displays the image when mouse hoovers over the button.
buttons.setSelectedIcon(image);              // Displays the image when the buttons is pressed (Selected).

Hope this was helpful.

how can we form a 2d array in jsp so that we can select its element just by clicking on the particular element..

Hi irhs,
Welcome to DaniWeb
1. Please don't hijack old threads with a new question - please start your own thread
2. For jsp questions please use the jsp forum, not the "ordinary" java forum.
Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.