Use of this. keyword

can anyone explain "this" in a clear concise way? I do know that its used to specify a value in a particular instance, but things like
this.x = x;
,confuse me a bit . Isn't the x already defined as x ?

thanks ever so much..so its the newly constructed x
that is being assigned the value that is being passed,
is that it?This is maybe clearer. The x (at the class level) is assigned the value of i (past as parameter to the constructor).
class Example {
    private int x;
    public Example (int i) {
        x = i;
}The reason for the use of this.x=x is I think that people don't want to invent two names for the same thing. You see this too,
class Example {
    private int x;
    public Example (int _x) {
        x = _x; // serves the same purpose as this.x = x

Similar Messages

  • Using the 'this' keyword

    What is the use of the this keyword:
    import java.util.*;
    public abstract class LegalEntity implements HasAddress{
    private String address;
    private String area;
    private String registrationDate;
    private ArrayList accounts;
    public LegalEntity()
         accounts = new ArrayList();
    public void addAddress(String address){this.address = address;}
    public String getAddress(){return address;}
    public void addAccount(Account account)
         accounts.add(account);
    public ArrayList returnAccounts()
         return accounts;
    }

    This can be used when there are lots of static functions and you want to be sure you are invoking the current objects methods/members.

  • Not getting the use of 'this' keyword in constructor as shortcut approach.

    class Box{
    int width;
    int height;
    int depth;
    Box(){ //no-arg constructor
    Width =1;
    Height = 2;
    Depth = 3;
    Box(int width){
    this.width = width;
    height = 2;
    depth = 3;
    Box(int width, int height){
    this.width = width;
    this.height = height;
    depth = 3;
    /*Box(int width, int height, int depth){
    this.width = width;
    this.height = height;
    this.depth = depth;
    *//short cut approach*
    *Box(int width, int height, int depth){*
    this(width, height); //calls matching constructor from the same class
    this.depth = depth;
    Box(Box b){
    this.width = b.width;
    this.height = b.height;
    this.depth = b.depth;
    public class ConstructorDemo {
    public static void main(String[] args) {
    Box b1 = new Box(1,2,3);
    Box b2 = new Box(b1);
    In the above example, 'this' pointing to current object is understood but
    this(width, height); is used instead of this.width=width; this.height=height;
    how can it be shortcut when we have declared constructors ? And really how its so useful in a big code?
    Edited by: 1010533 on Jun 7, 2013 12:54 PM

    Welcome to the forum!
    >
    class Box{
    int width;
    int height;
    int depth;
    Box(){ //no-arg constructor
    Width =1;
    Height = 2;
    Depth = 3;
    Box(int width){
    this.width = width;
    height = 2;
    depth = 3;
    Box(int width, int height){
    this.width = width;
    this.height = height;
    depth = 3;
    /*Box(int width, int height, int depth){
    this.width = width;
    this.height = height;
    this.depth = depth;
    //short cut approach
    Box(int width, int height, int depth){
    this(width, height); //calls matching constructor from the same class
    this.depth = depth;
    Box(Box b){
    this.width = b.width;
    this.height = b.height;
    this.depth = b.depth;
    public class ConstructorDemo {
    public static void main(String[] args) {
    Box b1 = new Box(1,2,3);
    Box b2 = new Box(b1);
    In the above example, 'this' pointing to current object is understood but
    this(width, height); is used instead of this.width=width; this.height=height;
    how can it be shortcut when we have declared constructors ?
    >
    Shortcut? Who said it is a shortcut?
    >
    And really how its so useful in a big code?
    >
    EXTREMELY useful - especially in 'big code' (whatever you mean by that).
    Constructors are meant to create VALID instances. The business rules for creating a valid instance may not be as simple as your example.
    Ideally code should be written once and used often. The use of constructors is no different.
    Once you have a contructor for a given set of arguments you should use it if you need to construct an instance like that.
    So when you need a constructor that uses those same arguments and then some additional ones your new constructor should call the existing constructor and should then apply the new logic needed for the new constructor.
    That is important because it means that the business logic needed for those two arguments is only implemented in ONE place. That logic might be very complicated and there is no valid reason to duplicate it.
    Once you have a piece of code that works reuse it whenever possible.

  • Using "this" keyword

    Please help me. I didn't find an explanation in manuals or tutorials. Thank you
    //THIS PROGRAM IS WORKING BUT I CANNOT UNDERSTAND IT
    class one{
         public one(){
         System.out.println("This is from constructor");
         //PLEASE MAKE ME UNDERSTAND THIS METHOD IN THE WAY IT IS DECLARED "one two()"!!!!!!!!
         //I'M ALSO CONFUSED ABOUT THE USE OF "THIS" KEYWORD
         one two(){
              System.out.println("This is from method two()");
              return this;
    class From_main{
         public static void main(String[] args){
              one a=new one();
              one b=new one();
              a.two();
              b.two();
         }

    IMHO the trouble with cute trivial Examples like this is that; the names are meaningless and/or tend to confuse
    and they don't represent anything useful that you might do in real life.
    It might help if we renamed the class and methods and added some comments
    class Trivial {
      public Trivial(){
        System.out.println("This is from constructor");
      /** Returns a reference to an instance of this class */
      Trivial getInstance(){
        System.out.println("This is from method getInstance()");
        return this;
    class From_main {
      public static void main(String[] args){
        Trivial a = new Trivial();
        Trivial b = new Trivial();
        Trivial aa = a.getInstance();
        // a and aa point to the same 'Trivial' instance
        if ( a == aa)
          System.out.println("a == aa");
        Trivial bb = b.getInstance();
        // b and bb point to the same 'Trivial' instance
        if ( b == bb)
          System.out.println("b == bb");
    }The method getInstance() is redundant as you have to have a reference to the object
    before you can invoke the method to get a reference to the object.
    There are better ways to illustrate how to use the 'this' keyword.

  • About "this" keyword in constructor

    Hi im new to java... Actually what is the use of "this" keyword? I have tried reference books and internet site still no prevail. As i see there are times when the constructor as
    public hello(int number, number2){
    n = number;
    m = number2;
    without this and some are
    public hello(int number, number2){
    this.number = number;
    this.number2 = number2;
    im so confused please help

    It is a context reference keyword.
    Basically, it is a safety word that tags a specific variable to a method or class.
    In a class, you can have a member variable called aNumber. Now, in method, you could supply an argument that is also called aNumber. Example below:
    public class MyClassExample {
        int aNumber;
        public MyClassExample(int aNumber) {
            aNumber = 1;
    }In the above example, how does Java know what 'aNumber' I am refering to? The class member variable (global variable) or to the method argument variable (local variable)?
    The "this" keyword marks the context to which we refer. If we wanted to tell Java to use the value of the method's argument as the value for our class variable, we would do (this):
    public MyClassExample(int aNumber) {
        aNumber = this.aNumber;
    }Now, what does this really do? Well, Java transparently switches the context for us, but this time we define it.
    When we use the variable name, Java actually records the full context of "MyClassExample.aNumber" with the "MyClassExample.MyClassExample.aNumber"
    See, I bet you never knew that!
    What happens if we want it the other way around, then change which object to place the this keyword to.

  • Can i use " this " keyword in session bean.

    Hi,
    I am working with session beans, in my business logic i need to use " this" keyword,
    but is it possible to use " this" keyword in EJB bean?.

    you can.
    do it !

  • How to reference a class without using the new keyword

    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();

    quedogf94 wrote:
    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();No.
    Using new does not erase anything. There's nothing to erase. It's brand new. It creates a new instance, and whatever that constructor puts in there, is there. If you then change the contents of that instance, and you want to see them, you have to have maintained a reference to it somewhere, and access that instance's state through that reference.
    As already stated, you seem to be confused between class and instance, at the very least.
    Run this. Study the output carefully. Make sure you understand why you see what you do. Then, if you're still confused, try to rephrase your question in a way that makes some sense based on what you've observed.
    (And not that accessing a class (static) member through a reference, like foo1.getNumFoos() is syntactically legal, but is bad form, since it looks like you're accessing an instance (non-static) member. I do it here just for demonstration purposes.)
    public class Foo {
      private static int numFoos; // class variable
      private int x; // instance varaible
      public Foo(int x) {
        this.x = x;
        numFoos++;
      // class method
      public static int getNumFoos() {
        return numFoos;
      // instance method 
      public int getX() {
        return x;
      public static void main (String[] args) {
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ();
        Foo foo1 = new Foo(42);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ();
        Foo foo2 = new Foo(666);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ("foo2.numFoos is " + foo2.getNumFoos ());
        System.out.println ("foo2.x is " + foo2.getX ());
        System.out.println ();
    }

  • Use of final keyword on methods arguements ?

    Hi All,
    Just say I have an input arguement for a method which is an int. If I wanted to access the value stored by the input arguement reference inside an anonymous class that is contained in the method one way would be to pass the input arguement reference to a instance variable of the class that contains the method and use that.
    // Declared at start of  class
    int arrayIndex = 0;
    methodName(nt inputNumber)
        arrayIndex = inputNumber;
        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Accessing here
                anArray[arrayIndex] = 100;
    }Just wondering, I used the final keyword on the the input arguement instead and then used the input arguement directly instead. It seemed to work ok. Is this good programming practice or are there some pitfalls to using this that I'm not aware of?
    (I don't need to change what the input arguement reference points to)
    // Alternate
    methodName(final int inputNumber)
        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Accessing here
                anArray[inputNumber)] = 100;
    }Regards.

    declaring it final guarantees that you will not change the value.Of course it does. That's what it's for. That's what it means. But you're only guaranteeing that to yourself. It doesn't form part of the interface contract so it's no use to anybody else. Which is the bigger picture.
    Whenever i use any anonymous classes i prefer to use the final variables as long as i dont need to change their values.No you don't 'prefer' it, you are forced to do that by the compiler.

  • Use of bind keyword

    Hi all,
    I read that 'bind' keyword would create relationship between two variables. I tried out an example but i could not make out the difference with and without this variable.
    //Bind a sequence
    var s1 = [1,2,3,4,5];
    def s2 = bind for(item in s1){
        item * 2
    printSeqs();
    function printSeqs(){
        println("First Sequence");
        for(i in s1){
             println(i);
        println("Second Sequence");
        for(i in s2){
              println(i);
    }The output is same. i.e the value change in s1 gets reflected in s2 without the bind keyword also. Then what is actual usage and benefit of this keyword. When should i go for this 'bind'?

    PhiLho wrote:
    Your question, mattmo, is relevant and opportune. Actually, I totally overlooked the 'def'... :-)
    I think that it is like 'fixed' in Java: the variable is constant, it is a reference on an object and you can't change this ref. But the content of the referenced object isn't constant...Thanks PhiLho. Do you mean 'final'? If so, that's what I figured, and it's clear to me in that context.
    I wonder if there is a better word than "constant" when talking about the "def" keyword in JavaFX. I guess I'll have to get used to it since that seems to be the way it's described in the documentation.
    Side note: on some examples on the Net, I saw stuff like
    content: bind "Foo"
    I thought it was absurd, and it is confirmed by a Sun authority.I agree, binding a "def" to an immutable object would be absurd.

  • Use of 'static' keyword in synchronized methods. Does it ease concurrency?

    Friends,
    I have a query regarding the use of 'synchronized' keyword in a programme. This is mainly to check if there's any difference in the use of 'static' keyword for synchronized methods. By default we cannot call two synchronized methods from a programme at the same time. For example, in 'Program1', I am calling two methods, 'display()' and 'update()' both of them are synchronized and the flow is first, 'display()' is called and only when display method exits, it calls the 'update()' method.
    But, things seem different, when I added 'static' keyword for 'update()' method as can be seen from 'Program2'. Here, instead of waiting for 'display()' method to finish, 'update()' method is called during the execution of 'display()' method. You can check the output to see the difference.
    Does it mean, 'static' keyword has anything to do with synchronizaton?
    Appreciate your valuable comments.
    1. Program1
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    end display:
    start update:
    end update:
    2. Program2
    package camel.java.thread;
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    start update:end update:
    end display:

    the synchronized method obtain the lock from the current instance while static synchronized method obtain the lock from the class
    Below is some code for u to have better understanding
    package facado.collab;
    public class TestSync {
         public synchronized void add() {
              System.out.println("TestSync.add()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.add() - end");          
         public synchronized void update() {
              System.out.println("TestSync.update()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.update() - end");          
         public static synchronized void staticAdd() {
              System.out.println("TestSync.staticAdd()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticAdd() - end");
         public static synchronized void staticUpdate() {
              System.out.println("TestSync.staticUpdate()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticUpdate() - end");
         public static void main(String[] args) {
              final TestSync sync1 = new TestSync();
              final TestSync sync2 = new TestSync();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.add();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.update();
              }).start();
              try {
                   Thread.sleep(3000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.staticAdd();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.staticUpdate();
              }).start();
    }

  • The this keyword

    I have a vague idea what the this keyword means. Its something to do with inheritance but I'm not sure how this works. For example I've just seen a program as shown below:
    import java.awt.*;
    import java.util.*;
    import java.applet.*;
    import java.text.*;
    import javax.swing.*;
    public class Clock extends JApplet
    implements Runnable {
    private volatile Thread clockThread = null;
    DateFormat formatter; //Formats the date displayed
    String lastdate; //String to hold date displayed
    Date currentDate; //Used to get date to display
    Color numberColor; //Color of numbers
    Font clockFaceFont;
    Locale locale;
    public void init() {
    setBackground(Color.white);
    numberColor = Color.red;
    locale = Locale.getDefault();
    formatter =
    DateFormat.getDateTimeInstance(DateFormat.FULL,
    DateFormat.MEDIUM, locale);
    currentDate = new Date();
    lastdate = formatter.format(currentDate);
    clockFaceFont = new Font("Sans-Serif",
    Font.PLAIN, 14);
    resize(275, 25);
    public void start() {
    if (clockThread == null) {
    clockThread = new Thread(this, "Clock");
    clockThread.start();
    public void run() {
    Thread myThread = Thread.currentThread();
    while (clockThread == myThread) {
    repaint();
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e){ }
    public void paint(Graphics g) {
    String today;
    currentDate = new Date();
    formatter =
    DateFormat.getDateTimeInstance(DateFormat.FULL,
    DateFormat.MEDIUM, locale);
    today = formatter.format(currentDate);
    g.setFont(clockFaceFont);
    //Erase and redraw
    g.setColor(getBackground());
    g.drawString(lastdate, 0, 12);                     
    g.setColor(numberColor);
    g.drawString(today, 0, 12);
    lastdate = today;
    currentDate = null;
    public void stop() {
    clockThread = null;
    Now the line : clockThread = new Thread(this, "Clock");
    What does the this keyword do here?

    Please use code tags as described in Formatting tips
    Classes and Inheritance: Using the this Keyword

  • How to use knowledge base keywords"?

    I have found links to the the knowledge base document "how to use knowledge base keywords" online but all the links lead to a dead end. The document number is 75178, and explains the use of prefixes in the knowledge base keyword search. Has anyone any info on where this page is or if it still exists?
    Thanks
    Nadya

    Apparently, the document's no longer available.

  • Which cache the Formula Engine will use in this case?

    Say that a MDX query contains:
    ❶a calculated measure defined in the targeted cube, ❷and another
    WITH MEMBER.
    Which cache the Formula Engine will use in this case:
    ❶Query,
    ❷Global, or
    ❸both (query & global)? and why? .... illustrate as possible please.

    Thanks Elvis ... but
    ❶ doesn't your reply, especially this part:
    ...But if we use WITH MEMBER keyword to define a calculated measure, it's the Storage Engine cache and not the Formula Engine cache....
    contradict with Microsoft's white
    paper: SQL
    Server 2008 R2 Analysis Services Performance Guide? ... check the figure below please:
    this is in page 36, where they are talking about the Formula Engine (or Query Processor, as they sometimes refer to it) types of cache. note the highlighted, they are saying that using the "WITH keyword within a query" forces the use of the "Query
    Context" which is one of the formula engine cache (as they said).
    Actually I've asked the main question because of this part of the same 36 page:
    I wanted to know
    ❷ what will happen to the calculated measures (those defined in the cube) if combined with another calculated members defined using the WITH keyword, in the same query? are they going to be recalculated even if they are already
    exist in the global cache?

  • Use VB Set keyword with Clone method?

    I am using the TestStand API with Visual Basic 6.0 SP5. Is is necessary to use the Set keyword when calling the Clone method of a PropertyObject? i.e. which is correct:
    Set thePropObj = existingPropObj.Clone("", 0)
    or
    thePropObj = existingPropObj.Clone("", 0)
    Seems the Set keyword would be required, but I am
    running into funny problems with this. I have a step
    that I am trying to create a copy of. (The step contains a call to a LabVIEW VI.) If I omit the Set keyword, execution hangs at the call to Clone. If I include the Set keyword, all information present in the original PropertyObject doesn't seem to get copied to the new one. (Also, oddly enough, if I omit the set keyword, and the step calls a CVI function, everything seems to work
    fine!)
    Anyone have any advice?
    Thanks in advance
    D. LaFosse

    Hello LaFosse,
    You need to use the Set keyword before the clone method statement. However, I have a couple of comments about the code you sent.
    This is the code you sent:
    ' Start up the testStand engine
    Dim theTS As TS.Engine
    Set theTS = New TS.Engine
    ' OK, load in the sequence file I
    ' created. This sequence file
    ' contains nothing more than a call
    ' to a VI in the main stepgroup of
    ' the MainSequence.
    Dim seqFile As SequenceFile
    Set seqFile =
    theTS.GetSequenceFile()
    ' get a handle to the MainSequence
    Dim seq As Sequence
    Set seq = seqFile.GetSequenceByName
    ("MainSequence")
    ' Get a handle to the step that calls
    ' the VI, and a property object for
    ' the step
    Dim theStep As Step
    Set theStep =
    seq.GetStep(0, StepGroup_Main)
    Dim theStepProp As PropertyObject
    Set theStepProp =
    theStep.AsPropertyObject
    ' Create another step. We will attempt
    ' to use Clone to fill in the
    ' properties of this step.
    Dim theOtherStep As Step
    Dim theOtherStepProp As PropertyObject
    Set theOtherStep = theTS.NewStep("",
    TS.StepType_Action)
    Set theOtherStepProp =
    theOtherStep.AsPropertyObject
    ' Call clone...this step will hang.
    theOtherStepProp =
    theStepProp.Clone("", 0)
    Basically the problem is that you are not loading the TypePallete after creating the engine. You shoud include right after the Set theTS = New TS.Engine:
    theTS.LoadTypePaletteFiles
    This should avoid the crash.
    Some Additional comments:
    1. With VB you don't need to create property objects from other objects. All the classes, except the Engine Class, inherit from the Property Object Class. The following Code does the same thing, but without creating propertyobjects directly:
    Sub MySub()
    'Variable Declaration
    Dim theTS As TS.Engine
    Dim seqFile As SequenceFile
    Dim seq As Sequence
    Dim theStep As Step
    Dim theOtherStep As Step
    'Create the Engine
    Set theTS = New TS.Engine
    'Load the Types
    theTS.LoadTypePaletteFiles
    'Get Sequence File
    Set seqFile = theTS.GetSequenceFile()
    'Get Sequence
    Set seq = seqFile.GetSequenceByName("MainSequence")
    'Get Step
    Set theStep = seq.GetStep(0, StepGroup_Main)
    'Clone the Step
    Set theOtherStep = theStep.Clone("", 0)
    'Using the inheritance functionality
    'gets the Step Status
    'Notice that theOtherStep is not a PropertyObject
    'and you can use all the properties and methods that
    'applies to the PropertyObject Class to a Step class
    'in this example
    'Also, in VB when you are typing the statement, you
    'will not see the PropertyObject Class properties and
    'and Methods automatically if the variable is not a
    'PropertyObject type. However, you can still use them
    'as mentioned before
    MsgBox (theOtherStep.GetValString("Result.Status", 0))
    End Sub
    2. When you create or modify sequence files programatically be carefull not to break the license Agreement. You need the development lisence when modifying sequences.
    3. This piece of code is not completed, and you will need to shutdown the engine by the end.
    4. Since you are not handling UI Messages, you will need to be carefull when loading sequences that have the SequenceFileLoad Callback. The engine posts UI Messages when executing this callback. Also when you shutdown the engine, UI Messages are posted. For both operations (Load Sequence and Shuutdown) you may prevent the engine from posting the message (You may check the options parameter for this two methods in TS Programmer Help.)
    5. If you want to run a sequence, again you will need to incorporate in your code the UIMessage Handler part. (You may check the TS Programmer Help->Writing an Application Using the API->UI Messages). Otherwise it may hang since the engine posts UI Messages eventually.
    Regards,
    Roberto Piacentini
    National Instruments
    Applications Engineer
    www.ni.com/support

  • Problem on referencing "this" keyword on addActionListener

    Hi!
    I'm Ryan, ahm I've been studying on Swing Applications, ahm on this program I'm trying to handle the JMenuItem event when the user clicks a menu item, here's my code below:
    import java.awt.event.*;
    import javax.swing.*;
    public class MenuTest implements ActionListener{
    private static void createAndShowGUI(){
    //Delarations
    JFrame frame = new JFrame("MP3Stego");
    frame.setSize(300,300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuBar menuBar;
    menuBar = new JMenuBar();
    JMenu menu;
    menu = new JMenu("File");
    menu.setMnemonic(KeyEvent.VK_F);
    menu.getAccessibleContext().setAccessibleDescription("Open/Edit a File");
    menuBar.add(menu);
    JMenuItem menuFileOpen = new JMenuItem("Open");
    menuFileOpen.setMnemonic(KeyEvent.VK_O);
    menuFileOpen.addActionListener(this);
    menu.add(menuFileOpen);
    frame.setJMenuBar(menuBar);
    //frame.pack();
    frame.setVisible(true);
    public void actionPerformed(ActionEvent e){
    JOptionPane.showMessageDialog(null,"File Open");
    public static void main (String[] args){
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    Sir, the problem is when I try to use menuFileOpen.addActionListener(this); it says that
    MenuTest.java:24: non-static variable this cannot be referenced from a static co
    menuFileOpen.addActionListener(this);
    I see that I'm using non-static "this" on static createAndShowGUI, ahm is there a way for me to reference this keyword on a static method? or should I create a non-static method to put the action listener?
    Thank you so much Sir
    Ryan

    First, when you post code, use the button to put [code][/code] tags around your code.
    Second, a static method does not have a this to reference. You should make createAndShowGUI non-static, and create an instance of your class in your static main method. You can then call createAndShowGUI. You do not need to use a Runnable. The event thread will invoke your actionPerformed method.
    I'm not sure where you got the ideas you use to create this program, but the Swing tutorial gives some pretty clear examples of how to write Swing applications.
    http://java.sun.com/docs/books/tutorial/uiswing/learn/index.html
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • How do I get my old printer off the network?

    Hello I have a Lexmark Z1480 - if I go onto Bonjour I can see the network webpage my my printer configurations... I have uninstalled all Lexmark software etc as best I could and that part seems OK... There is still however the Lexmark network webpage

  • Kernel panic and eMac Mac OS X 10.4.8

    I was watching a blockbuster DVD and without no reason, appeared the tipical kernel panic. I turned off the eMac, holding the power button, after 2 minutes, restarted it, zapped the ram, repaired permissions and it seems everything is fine. I found t

  • How to over clock a ms-7231

    how do i over clock a ms-7231  specs  http://www.msi.com/index.php?func=proddesc&maincat_no=134&cat2_no=&cat3_no=&prod_no=1117

  • [JS] File Naming Issues

    NOTE: I am writing JavaScript for InDesign CS2 and CS3. My script involves writing file names that a user will input. The filenames will later be displayed in a menu. Since characters like ? % " / : can present problems, what's the best way to avoid

  • Nullpointer error when trying to test dispatcher in Identity Center

    Hi all, I am getting a nullpointer exception when I am trying to test my dispatcher in Identity Center.  In tools/options/java I have defined where the java.exe and jvm.ddl are located. I had tried to use a Java 1.6 before, but I got a 126 error whic