LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-12-2006, 01:26 AM   #1
alred
Member
 
Registered: Mar 2005
Location: singapore
Distribution: puppy and Ubuntu and ... erh ... redhat(sort of) :( ... + the venerable bsd and solaris ^_^
Posts: 658
Blog Entries: 8

Rep: Reputation: 31
how to get the "name" of a JButton in java ??


i created a jbutton with ::

PHP Code:
button01 = new JButton("??"); 
but how come in java , the name of a button is the text caption of it ?? how to get the "name" of this jbutton which is button01 , kind of like a unique name(though not exactly) for a component ...

i tried ::
PHP Code:
evt.getSource().getClass().getName() == javax.swing.JButton
evt
.getSource().getClass().toString() == class javax.swing.JButton
evt
.getSource().toString() == javax.swing.JButton[,0,0,636x459,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@d42d08,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=??,defaultCapable=true]
evt.getActionCommand() == ??
evt.paramString() == ACTION_PERFORMED,cmd=??,when=1147443026404,modifiers=Button1
evt
.hashCode() == 6330655 
i do this in public void actionPerformed(ActionEvent evt
am i doing something wrong or
what is the correct way to use this method or
are there other better methods to get that bloody "button01" in strings ??


//thanks in advance(dont laugh)

REASON EDIT ::you know what ?? ... "php" is damn cool ... ^_^

//cheers ...


.

Last edited by alred; 05-12-2006 at 01:44 AM.
 
Old 05-12-2006, 03:14 AM   #2
spooon
Senior Member
 
Registered: Aug 2005
Posts: 1,755

Rep: Reputation: 51
A button is a button; it has no "name" (what are you talking about?). You can have variables point to a Button object, but that has nothing to do with the button itself. You can test to see if your button is the same as the one that is being pointed to by "button01":
Code:
if (evt.getSource() == button01)
  // do stuff

Last edited by spooon; 05-12-2006 at 03:20 AM.
 
Old 05-12-2006, 10:02 AM   #3
alred
Member
 
Registered: Mar 2005
Location: singapore
Distribution: puppy and Ubuntu and ... erh ... redhat(sort of) :( ... + the venerable bsd and solaris ^_^
Posts: 658

Original Poster
Blog Entries: 8

Rep: Reputation: 31
>> "A button is a button; it has no "name" (what are you talking about?) ..."

language problem i believe , it should be "the name of a field" or "how to return a name in strings format of a given field" but i could be wrong too , for i'm just a few days old in java ...

your solution is correct and it works , but i found another solution through java reflection to *just* get that bloody name of a button as strings ... arrrrrrrggggh ... hopes that its not too expensive ...

any other methods are welcome ...


//thanks again spooon


.

Last edited by alred; 05-12-2006 at 10:06 AM.
 
Old 05-12-2006, 10:53 AM   #4
crewblunts
Member
 
Registered: Jan 2004
Location: Connecticut, USA
Distribution: Slackware & Ubuntu
Posts: 53

Rep: Reputation: 15
if you want to
Code:
evt.getActionCommand
you must first use
Code:
button01.setActionCommand("aString");
link to JButton API Documentation
link to documentation for ActionEvent
link to java API documentation

that last link is very helpful. You can access all the documentation for all the classes/interfaces/etc in Java 1.5.0

hth,

Phil V
 
Old 05-14-2006, 11:27 AM   #5
alred
Member
 
Registered: Mar 2005
Location: singapore
Distribution: puppy and Ubuntu and ... erh ... redhat(sort of) :( ... + the venerable bsd and solaris ^_^
Posts: 658

Original Poster
Blog Entries: 8

Rep: Reputation: 31
thanks for quick links ...

both button01.setActionCommand("aString"); and if (evt.getSource() == button01) work and probably faster but i think strings for ActionCommand could be use for other tricks ...

below is the trick that i tried ::

Code:
import java.lang.*; 
import java.lang.reflect.*; 
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

...

public JButton button01;

...

public String getPerformedComponent(Object PerformedObj) 
    {    
        Component comp1;
        String s1 , s2  ;
        s2 = "" ;
        s1 = "" ;

try {
                 
   Class c1 = Class.forName("nameOfthisClass"); 
 // Constructor construct[] = c1.getDeclaredConstructors();  
   Field f1[] = c1.getDeclaredFields(); 
   for (int i = 0; i < f1.length; i++) 
    {                            
      s1 = f1[i].getType().getName();
      if (s1.lastIndexOf(".") > 0) {
       s1 = f1[i].getType().getName().substring(s1.lastIndexOf(".")+1,s1.length());}
 
   Object obj = f1[i].get(this); 
   if(obj instanceof Component) 
   //     return (Component)obj ; 
   if((Component)obj == PerformedObj) {
   System.out.println("===================== found PerformedObj start ..."); 
   System.out.println(f1[i].getName()+" of <"+s1+">");
   s2 = f1[i].getName();
   System.out.println("===================== found PerformedObj end ..."); 
   
   continue ;     
     }
                           
   System.out.println(f1[i].getName()+" of <"+s1+">"); 
                           
 } 
} catch (ClassNotFoundException ERROR) {
    System.out.println("this ClassNotFoundException ==> another puff of cigarette ...");        
        }
catch (IllegalAccessException ERROR) {
    System.out.println("this IllegalAccessException ==> reinsert a better piece of music cd ...");        
}
 
   return s2;
    }



public void actionPerformed(ActionEvent evt){

String result = "" ;

...

result = getPerformedComponent(evt.getSource());

JOptionPane.showMessageDialog(null , "getPerformedComponent(Object PerformedObj):string;   \n\r\n\r==  "+result , "...",JOptionPane.INFORMATION_MESSAGE);

...

}
note :: could have some mistakes , i have to delete the extras ...


//thanks again ...


.

Last edited by alred; 05-14-2006 at 11:32 AM.
 
Old 05-14-2006, 02:51 PM   #6
mrcheeks
Senior Member
 
Registered: Mar 2004
Location: far enough
Distribution: OS X 10.6.7
Posts: 1,690

Rep: Reputation: 52
Using reflection a lot can slow down the program execution. If your program isn't big, using lots of interfaces and exposing services, I suggest that you avoid reflection.
 
Old 05-17-2006, 12:20 PM   #7
alred
Member
 
Registered: Mar 2005
Location: singapore
Distribution: puppy and Ubuntu and ... erh ... redhat(sort of) :( ... + the venerable bsd and solaris ^_^
Posts: 658

Original Poster
Blog Entries: 8

Rep: Reputation: 31
just found another method without reflection(i think) ...

Code:
...
public JFrame frame;
public JPanel panel1,panel2,panel3;
...

public String getPerformedComponentC(Container container , Object PerformedObj){   
    
    String s2= "" ;

 int count = container.getComponentCount();
//could probably be nested further more to do a GlobalFindComp   
  for (int i=0; i<count; i++) {

  Component comp = container.getComponent(i);

  if(comp == PerformedObj) {
  s2 = comp.getName();
  System.out.println("... found PerformedObj ===> " + s2);
  break;
    } 
  }

 return s2;
}

public String do_fetch(String L) {
        String title = L;
        JButton button[];
        button = new JButton[10];
        panel1.setName("panel1");        
        frame = new JFrame(title);
        panel1 = new JPanel();

//could probably be nested further more eg. JPanel panel[];  
        for (int i = 0; i<button.length ; i++) {
            
        button[i] = new JButton("??");
        button[i].setName("button"+(i+1));  
        button[i].setSize(80,32);
        button[i].addActionListener(this);
        panel1.add(button[i]);    
            
        }
        
        panel1.setLayout(new GridLayout(0,1,10,5));
        frame.getContentPane().add(panel1, BorderLayout.NORTH);
        frame.setSize(100, 480);
        frame.setVisible(true);

        return L ;

    }

public void actionPerformed(ActionEvent evt){

        JOptionPane.showMessageDialog(null, "getPerformedComponent(Object PerformedObj):string;   \n\r\n\r==  "+
                                      getPerformedComponentC(panel1, evt.getSource()) , "...",JOptionPane.INFORMATION_MESSAGE);
//probably give a frame.getContentPane() if global find ...

}
btw ... during the process i hit upon a c#(c sharp ??) snipplet ...
Code:
private int counter; 
private int locY; 

private void btnAdd_Click(object sender, System.EventArgs e)
{
counter += 1; 
locY += this.btnAdd.Height + 2; 

Button myButton = new Button();

myButton.Name="Button " + counter;
myButton.Text="Button " + counter;

//set the x location same as btnAdd, and y = locY
myButton.Location= new Point(btnAdd.Location.X, locY); 

//set its MouseEnter, MouseLeave and Click events
myButton.MouseEnter += new System.EventHandler(this.btn_MouseEnter);
myButton.MouseLeave += new System.EventHandler(this.btn_MouseLeave);
myButton.Click += new System.EventHandler(this.btn_Click);

//add this button to the form
this.Controls.Add(myButton);
}

arrrrgggghhhh ... days and days of music(specifically tang dynasty , the band , a china band) ... still havent pass that bloody button !!!!


note :: could have some mistakes which i wouldnt know ...


.

Last edited by alred; 05-17-2006 at 12:29 PM.
 
Old 05-22-2006, 11:31 PM   #8
alred
Member
 
Registered: Mar 2005
Location: singapore
Distribution: puppy and Ubuntu and ... erh ... redhat(sort of) :( ... + the venerable bsd and solaris ^_^
Posts: 658

Original Poster
Blog Entries: 8

Rep: Reputation: 31
just found another method , i think this is the one i'm looking for ...

something like ::

Code:
public class makebox01 implements  MouseListener,MouseMotionListener,ActionListener{

... 

public String do_fetch(String L) {

...

        for (int i = 0; i<button.length ; i++) {
            
        button[i] = new JButton("??");
        button[i].setName("button"+(i+1));  
        button[i].setSize(80,32);
        button[i].addActionListener(this);
        button[i].addMouseListener(this);
        button[i].addMouseMotionListener(this);
        panel1.add(button[i]);    
            
        }

...

}

...

public void mouseClicked(MouseEvent e){
        
        Component sender = e.getComponent();
        if (sender instanceof JButton) {
        System.out.println("sender as Jbutton onMouseClick ==> "
                           +sender.getName());    
        }

    }

...

}
i'm not sure how true is that but i think i will stick with this one for the time being and move on to ... ok ... JFrame , at my own sweet time ...


note :: could have some mistakes which i wouldnt know ...



.
 
Old 05-23-2006, 02:05 AM   #9
ppanyam
Member
 
Registered: Oct 2004
Location: India
Distribution: Redhat
Posts: 88

Rep: Reputation: 15
Going back to your first post, button01 is a variable name. It is an object of type JButton.
All objects wont have a name, in this case there is one.

Subsequently, you refer to an object by its variable name only. If your are "few days old in java", reflection is not
the correct thing to be mastering.

Everytime somebody calls out your name, you dont go about finding out your name first... you KNOW your name. Same in
programming. You refer to variable names, and they know what you want to do.

ppanyam
 
Old 05-23-2006, 05:41 AM   #10
alred
Member
 
Registered: Mar 2005
Location: singapore
Distribution: puppy and Ubuntu and ... erh ... redhat(sort of) :( ... + the venerable bsd and solaris ^_^
Posts: 658

Original Poster
Blog Entries: 8

Rep: Reputation: 31
i think my specific intention is after knowing that somebody is going to call without firstly giving "a unique name(though not exactly)" then i need to do something , etc , etc , etc and then only allow them to do what had been presumingly unilaterally or bilaterally(usually in the first case) agreed upon before-hand within the owner's panels/containers/or_whatever ... preferably we are able to set/get their declared(or not) fields or whatever ...

just an intention ... frankly speaking , i'm not too sure about what i'm talking about either ... ^_^

infact i'm kind of going into this JFrame with some kind of Listener now , one thing at a time ... slowly taking my own sweet time i guess , probably will be back to the above mentioned intention much much later on ...


//i think i will like this java ... just for the fun of it ...


.

Last edited by alred; 05-23-2006 at 05:46 AM.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
"Xlib: extension "XFree86-DRI" missing on display ":0.0"." zaps Linux - Games 9 05-14-2007 03:07 PM
Java error "Exception in thread "main" java.lang.StackOverflowError" nro Programming 1 09-04-2004 03:47 AM
I cannot use "java chat". Browser says plugin required "x-java-vm". jdruin Linux - Software 4 04-18-2004 05:44 PM
Java + Making a JButton to run something. Mega Man X Programming 2 02-09-2004 03:25 PM
Java does "age" or "Age" matter when declaring an Int?? Laptop2250 Programming 3 10-13-2003 12:34 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 08:28 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration