How to get name from JButton?

Hey
Is it possible to get the name from a clicked JButton in the actionPerformed so that if i have for example 2 JButtons i can do an
if statement to do different things when a button is clicked?
For example if button1 is clicked the screen writes "YippiKayYeah mother ......" and if button2 is clicked it writes "Go home Lazy Boy".
Here is my code, if it is for any use:
public class Main extends JPanel implements ActionListener {
    private Players players;
    JTextArea output;
    JScrollPane scrollPane2;
    JButton button1, button2;
    String newline = "\n";
    public Main(){
        players = new Players();
    public JMenuBar createMenuBar(){
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        menu.setMnemonic(KeyEvent.VK_A);
        menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
        menuBar.add(menu);
        // add menuitems/buttons
        JMenuItem menuItemSave   = new JMenuItem("Save");
        menuItemSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
        menuItemSave.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
        // add actionlistener       
        JMenuItem menuItemOpen   = new JMenuItem("Open");
        JMenuItem menuItemQuit   = new JMenuItem("Quit");
        // add to menu
        menu.add(menuItemSave);
        menu.add(menuItemOpen);
        menu.add(menuItemQuit);
        return menuBar;
    public Container createContent(){
        JPanel contentPane = new JPanel(new GridLayout(3,1));
        ImageIcon icon = createImageIcon("middle.gif", "a pretty but meaningless splat");
        JTable scrollPane = new JTable(players.showPlayers()); 
        //Create the first label.
        button1 = new JButton("Silkeborg IF");
        button1.setToolTipText("Klik her for at se Silkeborg IF");
        button1.addActionListener(this);
        button1.setActionCommand("enable");
        //Create the second label.
        button2 = new JButton("FC Midtjylland");
        button2.setToolTipText("Klik her for at se FC Midtjylland");
        button2.addActionListener(this);
        button2.setActionCommand("disable");
        //Create a scrolled text area.
        output = new JTextArea(5, 30);
        output.setEditable(false);
        scrollPane2 = new JScrollPane(output);
        //Add stuff to contentPane.
        contentPane.add(button1);
        contentPane.add(button2);
        contentPane.add(scrollPane);
        contentPane.add(scrollPane2, BorderLayout.CENTER);
        return contentPane;
    public void actionPerformed(ActionEvent e){
        String s;
        if ("enable".equals(e.getActionCommand())){
            s = "Silkeborg IF"+e.getSource();
            output.append(s + newline);
            button1.setActionCommand("disable");
            button2.setActionCommand("enable");
        } else{
            s = "FC Midtjylland"+e.getSource();
            output.append(s + newline);
            button1.setActionCommand("enable");
            button2.setActionCommand("disable");
    protected static ImageIcon createImageIcon(String path,
                                               String description) {
        java.net.URL imgURL = Main.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
    public static void createGUI(){
        JFrame frame = new JFrame("Test af yo yo yo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Main menu = new Main();
        frame.setJMenuBar(menu.createMenuBar());
        frame.setContentPane(menu.createContent());
        frame.setSize(500, 300);
        frame.pack();
        frame.setVisible(true);
     * @param args the command line arguments
    public static void main(String[] args) {
        createGUI();
}

what i do with my JButtons is create and inner class that implements actionListener like this:
     private JButton button;
     button = new JButton("Button");
     button.addActionListener(new BListener());
     private class BListener implements ActionListener{
          public void actionPerformed(ActionEvent e){
               if(e.getSource() == button){
                    //code for when the JButton button is pushed
     }Also, rather than comparing the names (Strings) and creating overhead, this compares the buttons reference variables :). Oh, and make sure that the buttons used are class variables. A good idea is to keep related buttons; listeners in one private class e.g. navigation buttons in a browser are all registered with the listener NavListener.

Similar Messages

  • How do spammers get names from my Contacts?

    Can someone explain how spammers get names from your contacts?  The typical e-mail says it is from a person that is in my contact list but of course the actual e-mail address is not from that person.  It says that it is addressed to my name and the e-mail will say something like, "Dan, you need to try this!" and then has a link which of course I never click on.  So how do they know both the name of my friend and me?  Is that something they got from my friend's computer, from mine or from other traffic they have intercepted between us?  I'll copy the headers below, removing the name of my friend and my comcast, if that helps.  I note that there is a spam rating of "00000".  Mail spam filters don't seem to help this kind of junk.  Any other way to catch it?
    Name from my contacts <bluedreams_182000@****>
    To: Dan <my email at comcast>
    Reply-To: Name from my contacts <rlhwygaoumbg@****>
    Return-Path: bluedreams_182000@****
    Received: from imta01.emeryville.ca.mail.comcast.net (LHLO imta01.emeryville.ca.mail.comcast.net) (76.96.30.13) by sz0012.ev.mail.comcast.net with LMTP; Wed, 27 Feb 2013 14:39:31 +0000 (UTC)
    Received: from nm25-vm2.bullet.mail.ne1.yahoo.com ([98.138.91.213]) by imta01.emeryville.ca.mail.comcast.net with comcast id 5Sf51l00Y4cByPW01SfVQG; Wed, 27 Feb 2013 14:39:30 +0000
    Received: from [98.138.90.53] by nm25.bullet.mail.ne1.yahoo.com with NNFMP; 27 Feb 2013 14:39:09 -0000
    Received: from [98.138.226.128] by tm6.bullet.mail.ne1.yahoo.com with NNFMP; 27 Feb 2013 14:39:09 -0000
    Received: from [127.0.0.1] by smtp215.mail.ne1.yahoo.com with NNFMP; 27 Feb 2013 14:39:09 -0000
    Received: from localhost ([email protected] with login) by smtp215.mail.ne1.yahoo.com with SMTP; 27 Feb 2013 06:39:09 -0800 PST
    X-Caa-Spam: 00000
    X-Authority-Analysis: v=2.1 cv=Y8ZABXuN c=1 sm=1 tr=0 a=yFh+eeAJilq5jagfoJ6Fqg==:117 a=CjxXgO3LAAAA:8 a=C_IRinGWAAAA:8 a=f8_S3n9t2uQA:10 a=T2eDSQWuq6oA:10 a=oJL9TIRMo0YA:10 a=wPDyFdB5xvgA:10 a=YbZ8FP2_cKMA:10 a=qHrs9QlyAAAA:8 a=SOyKGQC6J-v4blZxIL4A:9
    Authentication-Results: imta01.emeryville.ca.mail.comcast.net; dkim=pass header.d=yahoo.com header.b=My3CIG6B
    Dkim-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=yahoo.com; s=s1024; t=1361975949; bh=SJ8H66WD9dGkowyk01012kCKbuWqBy+0rI9R1qHqC2I=; h=X-Yahoo-Newman-Id:Message-ID:X-Yahoo-Newman-Property:X-YMail-OSG:X-Yahoo-SMTP :Received:Subject:To:Date:Reply-To:From; b=My3CIG6BbP+C/REBNH0Pl1rvm3yRuYtg8FtSI9ICCCs5C3CwVik60zu9fmZ2TDVhIX45i0GSorNyM VeTh+4xG3CW4ugdA6f1/d84sSiaUH069pESMpBzR4PanZjFJt+OjjqTIHZW1xUcMUbk6aRTDV9IjpJoV ob5uvvmpjqpAq8=
    X-Yahoo-Newman-Id: [email protected].****
    Message-Id: <[email protected].****>
    X-Yahoo-Newman-Property: ymail-3
    X-Ymail-Osg: mI56qykVM1m4NTZzp53SpESUznrR9CMCxL1wR5kVhIPDSm_ kgx2B8h0MD84jBKTlb1pB40CAsrAcfoA1ObW.pSgRW1HNt962Rte8ky0A.Yq kExYbORoTN8V3EDFYI31vSePX_zypIbH.LPF0Dknu2dL9HE2ORUPTQ9QqNxr MYgfV7xcMNkoTXbptAnMOyFotVy2WGQs8SGccKGnfGQngm7lXZirQ_4MxAVV R4d9JZcQJaBCjksPq7MIUchCs8L3HKkwkd2PT3i8X3ceu08kjN_gUx_NlNtN 0fL1_i5PcYCl0Rc3tuew.vndrrt2b7fevo1E3Xqd6imPee4FFHll_yWV2c1v yGEMAYsx7fB9XbomsYZtJK9k6JguE.VIGjx1xQpiqszDEPLqILJ6uChhhCyA 9pCaw0u_Qbmdie7VdZRwZT7P.6D8GyhUb5AZ9EbXRNIwX2Hgq8DkkQa9QbI6 tCtZFp40KLE45lJCgg1K5frkPDFS.hSRljN1G7HnkkIeDZh63TOQ2DjLO_3B Q80PjDp5FFz9.1LZI3AsPsdeBpz3B_VIHzz_suN1aFQ--
    X-Yahoo-Smtp: l_K7TJWswBDTfM_9zVF_23qtYt8VWAIMESQlX2QM
    <Emails Edited By Host>

    Someone has gained access to the Contact attached to your email account, probaby online (they don't need access to your computer) It is now too late to change that but change your password.
    Both Comcast and Yahoo are about as secure as a wet paper bag.

  • How to get name of table from front end

    Hi,
    How to get name of table from front end in EBS 11i?
    thanx
    Ashish

    Hi
    Sandeep is correct. The "Help"/"Record History" will give you the table/view name, but sometimes this particular menu function give me a "Record History is not available here." error message.
    I then use the following menu functions (this will also give you additional information, like column details).
    1) Open Forms
    2) Click on Help/Diagnostics/Examine (*you might have to enter the APPS password at this point)
    3) Change "Block" to "System"
    4) Change "Field" to "Last_query"
    The system will populate the "Value" field with the query that was executed in order to populate the form.
    Regards
    Frank

  • How to get file from server while click on link

    Hi,
    i created on link and i gave one server path to select file from server but while clickinng on link it no displaying any thing.
    following is the Destination url that i gave for the item.
    /u08/app/appvis/xxex/inst/xxex_apps/xxrbe/logs/appl/conc/log/
    please tell me how to get file from server while click on link.

    Ok I got your requirement now.
    If you are getting file names from view attribute then you should not be adding destination URI property for the link.
    Instead you can use OADataBoundValueViewObject API.
    Try below code in your controller processRequest method:
    I am assuming that you are using classic table.
    Also in below example it considers OAMessageStyleText and you can replace it with link item if you want.
    OATableBean tableBean =
    (OATableBean)webBean.findChildRecursive("<table item id>");
    OAMessageStyledTextBean m= (OAMessageStyledTextBean)tableBean.findChildRecursive("<message styled text in table item id>");
    OADataBoundValueViewObject tip1 = new OADataBoundValueViewObject(m, "/u08/app/appvis/xxex/inst/xxex_apps/xxrbe/logs/appl/conc/log/"+"<vo attr name which stores file name for each row>");
    m.setAttributeValue(oracle.cabo.ui.UIConstants.DESTINATION_ATTR, tip1);
    Regards,
    Sandeep M.

  • How to get BOOLEAN from STORED FUNCTION

    We are calling legacy PLSQL stored procedures and functions via named queries. This has worked fine so far, but there are some functions which return the type 'BOOLEAN'. e.g.
    FUNCTION some_function( some_argument IN NUMBER) RETURN BOOLEAN;
    Where the return type is BOOLEAN calling the named query fails with
    Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)): oracle.toplink.exceptions.DatabaseException
    Internal Exception: java.sql.SQLException: ORA-06550: line 1, column 13:
    PLS-00382: expression is of wrong type
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    Error Code: 6550
    A couple of threads have hinted that what we are trying to do is not possible:
    How to get BOOLEAN from STORED PROCEDURES
    Re: Creating Named Query: from OracleCallableStatement
    This would possibly be due to 'restriction in the OCI layer'. Can anyone help? Is there really now way to call a valid PLSQL stored function via a named query when the return type is BOOLEAN?
    thanks

    I can't comment on possible issues you might have with the driver, but if it can be done in JDBC, it should be possible in TopLink.
    TopLink has the StoredFunctionCall which extends the StoredProcedureCall but adds an unnamed ouput parameter in the first spot of its parameter list. You will need to get the databasefield and set its type to BOOLEAN ie:
      DatabaseField returnField = (DatabaseField)yourStoredFunctionCall.getParameters().firstElement();
            returnField.setName(name);
            returnField.setSqlType(Type.BOOLEAN);Be sure not to use the setType() method, as I believe TopLink will try to use the Type.BIT when a boolean class is used as the classtype.
    Best Regards,
    Chris

  • How to get coordinates from Google Map

    I wonder how to get coordinates from Google Map to JavaFX application when click has occured. Here is an example of code:
    public class JavaFXApplication extends Application {
    public void showCoordinates(String coords)
            System.out.println("Coordinates: " + coords);
        @Override public void start(Stage stage)
            final WebView webView = new WebView();
            final WebEngine webEngine = webView.getEngine();
            webEngine.load(getClass().getResource("googlemap.html").toString());
            webEngine.getLoadWorker().stateProperty().addListener(
                    new ChangeListener<State>() {
                        @Override
                        public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
                            if (newState == State.SUCCEEDED) {
                                JSObject window = (JSObject) webEngine.executeScript("window");
                                window.setMember("java", new JavaFXApplication());
            BorderPane root = new BorderPane();
            root.setCenter(webView);
            stage.setTitle("Google maps");
            Scene scene = new Scene(root,1000,700, Color.web("#666970"));
            stage.setScene(scene);
            stage.show();
       public static void main(String[] args){
            Application.launch(args);
    // googlemap.html file
    <!DOCTYPE html>
    <html>
        <head>
            <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
            <style type="text/css">
                html { height: 100% }
                body { height: 100%; margin: 0px; padding: 0px }
                #map_canvas { height: 100%; background-color: #666970; }
            </style>       
            <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
            </script>
            <script type="text/javascript">           
                function initialize() {
                    var latlng = new google.maps.LatLng(40.75089, -73.93804);
                    var myOptions = {
                        zoom: 10,
                        center: latlng,
                        mapTypeId: google.maps.MapTypeId.ROADMAP,
                        mapTypeControl: false,
                        panControl: true,
                        navigationControl: true,
                        streetViewControl: false,
                        backgroundColor: "#666970"
                    var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);    
                    document.map = map;
            google.maps.event.addListener(map, 'click', function(event) {
                //java.showCoordinates(event.latLng); ???
            map.setCenter(location);
            </script>
        </head>
        <body onload="initialize()">
            <div id="map_canvas" style="width:100%; height:100%"></div>
        </body>
    </html>Edited by: krbltik on 03.10.2012 22:59

    Hi, welcome!
    You may also have a look at GPS Info Qt, available for free at Ovi Store: http://store.ovi.com/content/165671
    GPS Info Qt is a nice Qt app. I have it on my C6-01 and I like it.
    Regards.

  • How to get names of sub tabs?

    Hi All,
    Could someone tell me how to get names of all sub tabs?
    I have Parent Tab T1. T1 has 3 sub tabs T1_1, T1_2 and T1_3.
    I would like to have T1_1, T1_2 and T1_3 sub tab names in the list.
    Thanks in advance!!
    Dip

    Dip,
    You can get the tab names from apex dictionary views, apex_application_tabs & apex_application_parent_tabs . Thanks.
    Regards,
    Manish

  • How to get photos from mac to iPhone 6? when i try it just comes up iCloud instead of my photos

    how to get photos from mac to iPhone 6? when i try it just comes up iCloud instead of my photos

    Make sure Settings > iCloud > Photos > iCloud Photo Library (Beta) = "Off"
    Then sync your iPhone using iTunes and make sure your sync settings for photos are set correctly in iTunes.

  • I got a new computer and don't know how to get music from ipod touch to itunes library

    I recently got a new computer and don't know how to get music from my ipod touch to show on my itunes library. 

    You need to transfer the iTunes folder from the old computer to the new one.
    iTunes: How to move your music to a new computer (Mac or Windows):
      http://support.apple.com/kb/HT4527

  • I have a new MacAir and don't know how to get info from my USB stick and my SD photo card.  Can anyone help me please?

    I have a new MacBook Air and don't know how to get info from my USB stick and get info from my SD card.  Can anyone help, please?

    Plug the stick and/or card into the appropriate slots on the side of your Air. Do you see icons for the devices appear on the desktop? Click into them to see what files are there.
    Matt

  • How to get data from a USB-UIRT device using Labview?

    How to get data from a USB-UIRT device using Labview?
    I'm trying to get data from a USB-UIRT device, is it posible with Labview?
    I really appreciate your help, 
    thanks

    You may want to contact the developer of the device for the API and DLL.
    http://65.36.202.170/phpBB2/viewforum.php?f=3

  • How to get value from list item

    Hi all,
    How to get value from list item?
    I have a problem with the List Item object
    in the Oracle forms.
    How can I retrieve the selected item from
    a list ?
    I didn't find any function like 'list.GET_
    SELECTED_ITEM()'...
    thanks
    Bala

    Hello,
    You get the value as for any other Forms item:
    :value := :block.list_tem ;Francois

  • How to get FILENAME from FILE PATH

    does anyone know how to get filename from a file path for example
    FILE PATH: C:\Project\uploadbean\web\uploads\Button.txt
    returns
    FILENAME: Button.txt

    @BalusC
    ust for a reference cause i'm new in JSP This has nothing to do with JSP, but with basic knowledge of an essential API. I have given you the link to the File API. Are you saying that you refused to read the API documentation, which clearly explains you how to use the File and shows which methods are all available to you undereach the straightforward getName() method, and expecting that the others may chew the answers for you? Loser.

  • How to get data from PDF form?

    PDF forms can send data in url like GET or POST method. Is it possible to get data from url, like in PHP http://sever/file.php?item1=value1&item2=value2&item3=value3
    In APEX url have specific construction and I don't know how to get value of items (1...3)
    Please let me help to find simple method of geting data from URL.
    Best Regards,
    Mark

    The APEX URL syntax is detailed here
    http://download.oracle.com/docs/cd/E14373_01/appdev.32/e11838/concept.htm#BCEDJBEH
    How to get it from PDF is another matter...
    I'm working on an app that downloads PDFs with a Large amount of data as a blob, takes that blob and changes it to XML, then goes through the xml to validate each section of data and then add it into the schema that my apex app is referencing....
    I didn't write the original code but I do know that it isn't a quick thing to implement and includes using some uploading some java jar files to your schema and writing some custom java code.
    Someone else may be able to help with grabbing PDF data into the URL for the amounts of data you want to pass to apex.
    Gus..
    REWARDS: Please remember to mark helpful or correct posts on the forum, not just for my answers but for everyone!
    Edited by: Gussay on Sep 21, 2009 5:52 PM

  • How to get Position from EmployeeInfo in DIAPI

    I am using DIAPI(JCO) for SAP B1. According to one or my reuirement i am in need of Position from the EmployeesInfo. But there  seems no option or method for getting position from that. Can anyone guide me how to get that from EmployeesInfo ? Any help is appreciated..

    Looking at the DI API properties vs. DB fields mapping documentation in the SAP Business One developer area (https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/c5f5dbcc-0a01-0010-5d82-f25f2bee715e)
    it seems that this field is not exposed (yet).
    I.e. you could only run a SQL statement to get this information.
    Sorry,
    Frank

Maybe you are looking for

  • Report in Pivot table

    Hi All, I have a "month" column in the column section of Pivot table. I want to put Year as a prompt. I want the request this way, When I select Year (for example 2010) from the Year Prompt, I should get result starting from Jan-2010 to Jan-2011.. Ho

  • Error while creating new app service plan for a webapp

    Greetings ! I have a new webapp created and I want to move it a separate web app service plan to apply custom domain (Not available on free tier). From the new Portal I try to create new Web App Service plan and get this error. "Failed to create App

  • CLIENT_OLE2 Question

    I currently have an application that is using Webutils client_ole2... I have it sending a CLOB to microsoft word spell checks it and then copies all the corrected text to the clipboard so i can paste it back in a field on the forms. Everything is wor

  • Need help in Floor Plan Manager-ABAP

    Dear Experts, I am a beginner in floor plan manager and i am trying to  develop an exercise. I created a Test WD Component and also implemented the Interface for FPM . I changed the component name and Interface view to the FPM_OIF_COMPONENT and FPM_W

  • Custom Tag problem - NoSuchMethodError at MyAttInfo

    I am having the following problem when trying to use a taglibrary in my web           application. Does anybody know why I am having this problem?           Thanks,           Ozzie Gurkan           Mon Jan 08 16:55:30 GMT+05:00 2001:<I> <WebAppServle