Anonymous inner class

Hello

I'm building a custom menu system and I'm using an anonymous inner class with a method of execution. Can you tell me how to run the run method... thx... Here is a code example.

MenuItem menuItem = new MenuItem ("priority", 10) {}
public void run() {}
setTitle ("Hello World! l ») ;
}
};

Thanks in advance

VECD

Simon, I thought about it... I had to implement Runnable in the class, which allows me to call the method run like this:

. run() menuItem;

Thanks for your patience, I know I'm not the sharpest tool in the shed.

Steve

Tags: BlackBerry Developers

Similar Questions

  • final in the inner class

    I am trying to manually do a drawing similar to this program
    http://JavaFX.com/samples/draw/

    However, I'm running in final questions and internal classes.

    "size of a local variable is accessible from the inner class; must be declared final.

    He wants me to do either in SIZE or full size. However, once final, I can't change the variable.

    I have often used the variable in a loop for to assign a value (although perhaps it was a bad practice?) but I don't know the best way to handle this.

    Any suggestions?
    Thank you!


    int SIZE = 1; //somewhere else
    ...
            for( int size = 0 ; size < 5 ; size++){
                  Circle circle = new Circle(D/Padding);
                  
                  circle.setOnMousePressed(new EventHandler<MouseEvent>(){
                      public void handle(MouseEvent me){
                          SIZE = size;
                      }
                  }
             );
    Edit:
    I'm well aware that's not necessarily something specific to javafx, but more a general java programming failure.
    I also know that the mouseadapter is an anonymous class and can only access the final.

    I'm just looking for some suggestions on how to better fit this.

    Published by: namrog on July 5, 2011 10:51

    Published by: namrog on July 5, 2011 10:59
    int SIZE = 1; //somewhere else
    ...
            for( int size = 0 ; size < 5 ; size++){
                  final int size1 = size;
                  Circle circle = new Circle(D/Padding);
    
                  circle.setOnMousePressed(new EventHandler(){
                      public void handle(MouseEvent me){
                          SIZE = size1;
                      }
                  }
             );
    

    And Yes, it is a question of Java, not specific to JavaFX.
    http://Java.Sun.com/docs/books/JLS/third_edition/HTML/classes.html#247496

    DB

  • Java if statement error: cannot reference a Variable no final inside an inner class defined in a different method

    Hi, I am a newbie to blackberry java development, and I need help. I want to check if my SearchBox is equal to 1, or any other number, but when I try and put this, I get an error, could you take a look and tell me where I'm wrong, and how I can solve this problem.

    See you soon,.

    Max.

     BasicEditField SearchBox = new BasicEditField("Go To Page Number: ", "", 3, EditField.FILTER_DEFAULT);
        add(SearchBox);
        ButtonField myPageButton = new ButtonField("Go to Page",ButtonField.CONSUME_CLICK);
        hfm3.add(myPageButton);
        add(hfm3);
    
        myPageButton.setChangeListener(new FieldChangeListener(){
            public void fieldChanged(Field Field, int context){
            if(SearchBox.equals("1"));
                Page1 Page1 = new Page1();
             UiApplication.getUiApplication().popScreen(Ui.getUiEngine().getActiveScreen());
             UiApplication.getUiApplication().pushScreen(Page1);
        }});
    

    If you want to access a local variable in an inner class you must make final.
    Another option would be to declare the variable in the class.

    Another thing: Searchbox will equal never '1', you need to use getText to return the text of the editfield.

  • Creating objects of Inner classes

    public class Test{
         
         public class InnerTest{
              public InnerTest(){
                   System.out.println("Hello World");
              }
         }
         
        public static void main(String[] args){
             try {
                 Class<?> c = Class.forName("InnerTest");
                 c.newInstance();
             } 
             catch (Exception e) {
                 System.err.println(e);
              }
        }
    }
    Output:
    java.lang.ClassNotFoundException: InnerTest
    I want to make a new instance of the inner class. I tried to make the static inner class. I tried to call like this: classObject.forName ("OutterClass.InnerClass");

    Anyone know what I am doing wrong? Thank you.

    Also, how can I set parameters to the constructor by using the newInstance() method? It would be like this: newInstance ("Hello World")
    Example:
         public class InnerTest{
              public InnerTest(String s){
                   System.out.println();
              }
         }
    Thanks for the help. I appreciate it.

    Without knowing all the details of your mission, not to mention the total number of internal classes available, could you not do something like:

    //read file
    
    if("InnerClass1"){
      //create InnerClass1 directly
    }
    // more if-conditions...
    }else{
      System.out.println("Invalid inner class...");
    }
    

    And then you don't have to worry about trying to find the correct constructor to be used by reflection.

  • How to access the inner class fields in refleciton?

    I have:
    class Outer {
        class Inner {
            int field;
        }
        Inner inner;
    }
    I use reflection to get the Outer.field field and recognize that it is a reference to the inner class. What should I do to get the inner.field (or something that looks remotely like this at Inner.field)?

    We would like to

    Well, precedent is too messy for me even follow my example. I've simplified it, and I think I found where my error was. I suspect that you were doing a similar error:

    package scratch;
    
    import java.lang.reflect.Field;
    
    public class Scratch {
    
      public static void main(String[] args) throws Exception {
        new Scratch().go();
      }
    
      void go() {
        Outer1 o1;
    
        Field[] fields = Outer1.class.getDeclaredFields ();
    
        for (Field field : fields) {
    
          final String fn = field.getName ();
          final Class ft = field.getType ();
          final Class fc = field.getClass ();
          final Class fdc = field.getDeclaringClass ();
    
          System.out.println ();
    
          System.out.println ("Outer1 field : " + fn);
    
          System.out.println ();
    
          System.out.println ("field's class (field.getType()) : " + ft.getName());
          System.out.println ("field.getType().isMemberClass() (" + ft.getName() +" isMemberClass()) : " + ft.isMemberClass ());
          System.out.println ("field.getType(). getDeclaringClass() (" + ft.getName() + "'s declaring class) : " + fdc);
    
          System.out.println ();
    
          System.out.println ("field.getClass()) : " + fc.getName());
          System.out.println ("field.getClass().isMemberClass() (" + fc.getName() +" isMemberClass()) : " + fc.isMemberClass ());
          System.out.println ("field.getClass().getDeclaringClass() (" + fc.getName() + "'s declaring class) : " + fc.getDeclaringClass ());
    
          System.out.println ();
    
          System.out.println ("Note the difference between Field.getClass() (" + field.getClass () + ") and Field.getType() (" + field.getType() + ")");
    
          System.out.println ();
        }
      }
    }
    
    class Outer1 {
      class Inner1 {
      }
    
      Inner1 i1;
    }
    
    Outer1 field : i1
    
    field's class (field.getType()) : scratch.Outer1$Inner1
    field.getType().isMemberClass() (scratch.Outer1$Inner1 isMemberClass()) : true
    field.getType(). getDeclaringClass() (scratch.Outer1$Inner1's declaring class) : class scratch.Outer1
    
    field.getClass()) : java.lang.reflect.Field
    field.getClass().isMemberClass() (java.lang.reflect.Field isMemberClass()) : false
    field.getClass().getDeclaringClass() (java.lang.reflect.Field's declaring class) : null
    
    Note the difference between Field.getClass() (class java.lang.reflect.Field) and Field.getType() (class scratch.Outer1$Inner1)
    

    field.getClass () does NOT get the class of the field. It get the class of the field object that points to the field reference variable, which is always java.lang.reflect.Field. To get the class of the field, use field.getType ().

    Do you see the difference?

    Edited by: jverd February 5, 2011 17:18

  • How to reduce the number of files in the bin folder class

    Hi, please, help me

    I'm new to BB development

    I create a project there are 100 .class files are created in the bin folder of my ex projects:

    MyClass.Java files give me files myclass.class and myclass$ 1.class.

    That's my project is not loaded on 8520 Simulator.

    How I use to avoid creating this .class files from $ sdk1.5

    Is there a setting on eclipse

    Thanks in advance

    Mahesh

    100 class files should not be a problem.
    I just checked two of my projects where I generate a lot of classes (webservices).
    classes of 1915 in 1493, one inside the other.

    .class $ means generally that you use an inner class or the anonymous inner class I think.

  • Impact of anonymous

    Hello

    I have two examples to explain my question:

    1)

    New Thread() {}
    public void run() {}

    do some process

    }

    }. start();

    2)

    Wire processThread = new Thread() {}
    public void run() {}

    do some process

    }

    };

    processThread.start ();

    Which option is right in the perspective of garbage collection? or are the same?

    Someone tell me that we should not have option 1) which is the creation of anonymous, he says to have option 2). is it so? Is THAT JVM verifies references of son for garbage collection?

    I want to know what are the benefits that option 2) which I'd rather not.

    Help, please.

    The JVM verifies references of thread for garbage collection. Normally, as Simon pointed out, a thread is subject GC upon return from the run method. (When a thread is started, the system keeps a reference to it until its run method returns, it will not GC'ed before that, even if you continue to reference in your code.) However, with option 2, the reference in your code prevents the GC thread'ed (even after it ended) as long as the reference is under tension (has not been reassigned or went out of scope).

    As arkadyz says, the only reason to avoid option 1 is if you need to interact with the object thread itself after that it started. In fact, there is a second reason: arbitrary code style standards.

    Edit: actually, both options 1 and 2 are examples of anonymous inner classes. Arkadyz option only 3 is not anonymous.

  • When is it OK for looping while you wait event?

    Newbie question: in a world of logic non-blocking, when is it a good idea to loop waiting for something finish?

    For example, I am told to check to END_OF_MEDIA (via PlayerListener) to see if a song I played with ToneControl is finished. So is it possible to just create a loop and wait for it be triggered?

    Here is a very simple (albeit artificial) example. I want to play a melody (using ToneControl) twice. I play once, wait until it's done, then play again. END_OF_MEDIA tells me it's done. But have I not need to sit in a loop, then waiting for END_OF_MEDIA? Is it OK? It looks bad, but I don't know what would be the 'right' way.

    Thank you.

    Roricka

    The code I used was something called an anonymous inner class Java. Here's another version that does not use this construction somewhat obscure:

    void startTune() {    Player p = Manager.createPlayer(...);    p.addPlayerListener( new MyPlayerListener() );    p.start();}
    
    class MyPlayerListener implements PlayerListener {    public void playerUpdate(Player player, String event, Object eventData) {        if (event == END_OF_MEDIA) {            processEndOfMedia();        }    }}
    

    Note This class myplayerlistener is declared inside the MyScreen, right as well as the methods of the class and variable fields. All this has done is to convert an anonymous inner class in an inner class with a name.

    Now, it might look like you can move then comes from the MyPlayerListener class in a separate file named MyPlayerListener.java. But this does not work, at least not directly. The reason is related to one of the strange features of inner classes in Java (anonymous or not): an instance of an inner class carries with it an implicit reference to an instance of the containing class. That's why playerUpdate() can call processEndOfMedia() as if it was a MyPlayerListener member function, even if it is a member of MyScreen function. Somehow, an instance of MyPlayerListener lives a dual identity as an instance of MyScreen.

    If you want that myplayerlistener has stated in its own file (or if you want her to be a top-level class, not public in MyScreen.java or a static inner class of MyScreen), the rules of the language to say that there can be more than double-identity of nature. At this time, you cannot call the processEndOfMedia() in the same way as a MyPlayerListener instance does not have a reference to an instance of MyScreen. (In fact, it has no way of knowing that processEndOfMedia() is a function in the class MyScreen!) The way out of this is to give MyPlayerListener a way to refer to a particular instance of MyScreen. Here's one way:

    class MyPlayerListener implements PlayerListener {    private MyScreen client;    public MyPlayerListener(MyScreen client) {        this.client = client;    }    public void playerUpdate(Player player, String event, Object eventData) {        if (event == END_OF_MEDIA) {            client.processEndOfMedia();        }    }}
    

    Then, back in MyScreen, you need to change the call to the constructor:

        p.addPlayerListener( new MyPlayerListener(this) );
    

    And if you put MyPlayerListener in another package that MyScreen, you must also change the visibility of public processEndOfMedia().

    Anonymous inner classes are very convenient for these listener classes little, but they do not have the code a bit difficult to read. Put them in their own compilation units are more work, but it makes the code a little easier to manage, especially when come back you after a few months and try to understand what made you the way back when.

  • Run the Code in a Java Applet

    I'm calling a Java to Javascript applet. The Java code must run in privileged mode.  Eventually it will display a file selector that allows you to view files on the local hard drive, but for now, she simply returns a dummy value simple.  The problem I have is that the JavaScript to Java call return PrivilegedActionException. The applet is in a signed Jar file.  I'm under 8u25.

    This is the Java class:

        // Java code
        public class OHLib extends Applet {
    
            public String getFile() {
                String result;
                try {
                    result = (String) AccessController.doPrivileged(new PrivilegedAction() {
                        public String run() {
                            // JFileChooser code will go here
                            return "xxx";
                       }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }
    
        }
    
    

    Can someone tell me what's wrong with this code?  I would also be interested to know why the try/catch block above does not catch the exception.  The only place where I see the exception is in browser F12 developer tools.

    Here's the JavaScript code:

        function BrowseForFile() {
            var x;
            try {
                 // this code generates PrivilegedActionException
                 x = ohApplet.getFile();
            } catch (e) {
                 console.log(e);
            }
    
        }
    
    

    The applet is deployed on my web page as follows:

    <script src="/plugins/deployJava.js"></script>
    <script>
         var attributes = { 
             id:'ohApplet',
             code:'OHLib',
             codebase: 'java',
             archive: 'OHLib.jar', 
             width:1, 
             height:1,
         } ;
         var parameters = { 
          jnlp_href: 'OHLib.jnlp',
          classloader_cache: 'false',
         } ;
         deployJava.runApplet(attributes, parameters, '1.8');
    <script>
    
    
    

    The applet is in a jar signed with the following manifest file:

    Application name: < appname >

    Permissions: permissions everything

    CodeBase: < domain > .dev < domain > ".com"

    The appellant eligible Codebase: < domain > .dev < domain > ".com"

    Application library eligible Codebase: < domain > .dev < domain > ".com"

    The JNLP file is as follows:

        <?xml version="1.0" encoding="UTF-8"?>
        <jnlp spec="1.0+" codebase="" href="">
    
            <information>
                <title>title</title>
                <vendor>vendor</vendor>
            </information>
    
            <security>
                <all-permissions />
            </security>
    
            <resources>
                <j2se version="1.8+" href="http://java.sun.com/products/autodl/j2se" />
                <jar href="OHLib.jar" main="true" />
            </resources>
    
            <applet-desc 
                 main-class="OHLib"
                 name="OHLib"
                 width="1"
                 height="1">
             </applet-desc>
        </jnlp>        
    
    

    The problem was that I was not including the anonymous inner class (OHLib$ 1.class) in the jar file. My original CD jar command looks like this:

    jar cfmv OHLib.jar "../../jar_manifest.txt" OHLib.class
    

    Change to below solved the problem:

    jar cfmv OHLib.jar "../../jar_manifest.txt" OHLib.class OHLib$1.class
    

    Credits go to this page for the solution.

  • Display lines in ComboBox

    The code below to get an ObservableList of lines and fill a ComboBox: the question is that when a line is selected, it is displayed as "fx-shot of...» "such as the following pictures

    http://S8.postimg.org/5fgejym05/Z039.PNG

    http://S8.postimg.org/c9qp9nen9/Z040.PNG

    How I change my code to display the selected line?

    Thank you all.

    import javafx.application.Application;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.ComboBox;
    import javafx.scene.control.ContentDisplay;
    import javafx.scene.control.ListCell;
    import javafx.scene.control.ListView;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Line;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    
    
    /**
     *
     * @author utente
     */
    public class ProvaComboRendering extends Application {
        
        @Override
        public void start(Stage primaryStage) {
            
            
            StackPane root = new StackPane();
            ComboBox<String> cb = new ComboBox<>();
            
            cb.setPrefSize(150, 20);
            root.getChildren().add(cb);
            
            
            Scene scene = new Scene(root, 300, 250);
            
            primaryStage.setScene(scene);
            primaryStage.show();
    
            ObservableList<String> data = FXCollections.observableArrayList(
         "-fx-stroke-dash-array: 12 2 4 2;", "-fx-stroke-dash-array: 2 2;", "-fx-stroke-dash-array: 15 5.0 15 5.0;",
          "-fx-stroke-dash-array: 0.8 8.0;", "-fx-stroke-dash-array: 3 3;", "-fx-stroke-dash-array: 6 3;");
    
    cb.setItems(data);
          
          cb.setCellFactory(new Callback<ListView<String>, ListCell<String>>(){
            @Override public ListCell<String> call(ListView<String> p){
                return new ListCell<String>(){
                    
                        private final Group group;
                        private final Line line;
                        private final Rectangle rect;
                        { 
                            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                            rect = new Rectangle(120, 20, Color.WHITE);
                            line = new Line(0, 10, 120, 10);
                            group = new Group();
                            group.getChildren().addAll(rect,line);
                        }
    
                        @Override protected void updateItem(String style, boolean empty){
                            super.updateItem(style, empty);
                            
                            if(style != null && !empty){
                                line.setStyle(style);
                                setGraphic(group);
                            }
                        }
                    };
            }
        });
    }
    
     public static void main(String[] args) {
            launch(args);
        }         
    }
    

    SetButtonCell (...) allows you to configure the display in the part 'button' from the drop-down list box. Here I just moved your anonymous inner class to a nested class in order to use it again. (Also changed the transparent background.)

    import javafx.application.Application;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.ComboBox;
    import javafx.scene.control.ContentDisplay;
    import javafx.scene.control.ListCell;
    import javafx.scene.control.ListView;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Line;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    
    /**
    *
    * @author utente
    */
    public class ProvaComboRendering extends Application {
    
      @Override
      public void start(Stage primaryStage) {
    
        StackPane root = new StackPane();
        ComboBox cb = new ComboBox<>();
    
        cb.setPrefSize(150, 20);
        root.getChildren().add(cb);
    
        Scene scene = new Scene(root, 300, 250);
    
        primaryStage.setScene(scene);
        primaryStage.show();
        ObservableList data = FXCollections.observableArrayList(
            "-fx-stroke-dash-array: 12 2 4 2;", "-fx-stroke-dash-array: 2 2;",
            "-fx-stroke-dash-array: 15 5.0 15 5.0;",
            "-fx-stroke-dash-array: 0.8 8.0;", "-fx-stroke-dash-array: 3 3;",
            "-fx-stroke-dash-array: 6 3;");
        cb.setItems(data);
    
        cb.setCellFactory(new Callback, ListCell>() {
          @Override
          public ListCell call(ListView p) {
            return new LineListCell();
          }
        });
    
        cb.setButtonCell(new LineListCell());
      }
    
      public static void main(String[] args) {
        launch(args);
      }
    
      public static class LineListCell extends ListCell {
    
        private final Group group;
        private final Line line;
        private final Rectangle rect;
       public LineListCell()  {
          setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
          rect = new Rectangle(120, 20, Color.TRANSPARENT);
          line = new Line(0, 10, 120, 10);
          group = new Group();
          group.getChildren().addAll(rect, line);
        }
    
        @Override
        protected void updateItem(String style, boolean empty) {
          super.updateItem(style, empty);
    
          if (style != null && !empty) {
            line.setStyle(style);
            setGraphic(group);
          }
        }
    
      }
    }
    
  • Cast does not

    The code refers to a drag and drop in a table
    When I run
    public boolean importData(TransferHandler.TransferSupport supp) {
       try { 
            System.out.println("Class name "+supp.getComponent().getClass());
            GridC theGrid= (GridC)supp.getComponent();
            System.out.println("Import data test "+theGrid.getSelectedRow());
          } catch(Exception e) {
            System.out.println("Import data cant cast "+e.getMessage());
          }
    }
    the message is
    Class name GridGen.GridC$ 1
    Import data can't go up $1 GridGen.GridC cannot be cast to GridGen.GridC

    GridC is declared like this:
    public class GridC extends JComponent implements TableModelListener  {
    ...
    }
    What is $ 1?
    Can I do this casting work?
    Thank you

    GridC$ 1 is an anonymous inner class within GridC.

  • initializer, instance and static initializer blocks

    Hi guys,.

    I have read the foregoing, mentioned in the JLS and also in a book before, but I still do not understand, what is the use of these. I have sort of a rough idea, but not exactly. I mean, what is the purpose of the initializer for instance and static initializer blocks, how can be useful? I understand that I can run pieces of code that initialize instance and static variables accordingly, but what is the difference then to use a constructor to initialize these areas? Are these pieces of code executed before the execution of any manufacturer, or when otherwise?

    Sorry for my noob, I learn.

    PR.

    Static initializer blocks are executed when the class is loaded, once (a classloader). So that they have some use. Initializers for instance differ a lot of builders (I think that code in the initializers of the instance has been copied to each manufacturer), but they can be useful with anonymous inner classes for example (since you cannot define constructors it (well, you can, but you can't call them)).

    They have a limited use, but it is good to recognize them if you see them.

  • public static class

    Hello
    A method of variable or member of the Member are accessible without creating the object of a static class.
    I know that inner classes can only be static.
    Please answer soon...

    Of course not: s

    You can make the variable or static method, but then it is therefore more a member of the class.

  • "new static class qualified."

    Hi all

    I have a class of RandomGenerator with a nested public static String class, which extends from CountingGenerator with a nested class public static String, which in turn has a next() method to generate a following string object. Now, how do I actually use, how do I get a reference to the nested class so that I can call the following method. I tried this code, but it throws RuntimeException: code source Uncompilable - qualified new static class:
    public class FillTreeSet {
        public static void main(String[] args) {
            RandomGenerator rg = new RandomGenerator();
            RandomGenerator.String rgs = rg.new String();   //throws the exception
        }    
    }
    It's the RandomGenerator class:
    public class RandomGenerator {
        public static class String extends CountingGenerator.String {
            { cg = new Character(); }
            public String() {}
            public String(int length) { super(length); }
        }
    }
    And it comes to the CountingGenerator class:
    public class CountingGenerator {
        public static class String implements Generator<java.lang.String> {
            private int length = 7;
            Generator<java.lang.Character> cg = new Character();
            public String() {}
            public String(int length) { this.length = length; }
            @Override
            public java.lang.String next() {
                char[] buf = new char[length];
                for (int i = 0; i < length; i++)
                    buf[i] = cg.next();
                return new java.lang.String(buf);
            }
        }
    }
    Thanks in advance.
    PR.

    Since this is a static inner class, you must specify:

    new RandomGenerator.String();
    

    Your code would work if it were a non-static inner class.

  • Error won't let me go to another class (has got me pulling out my hair)

    Good buddies, so basically I have 2 buttons in the mainfraime class. The first button leads to the candidate page and the second page of voters. The first button works and redirects the user to the PasswordDemo page, but to the hell out of me I can't understand why he refuses to acknowledge the 'profile' class as its supposed to go to when the user clicks the second button. He keeps telling me that "the Profile() method is not defined for the Mainframe type. Help, please.

    Class mainframe:
    //The applications first or the main frame
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Mainframe extends JFrame {
    
            private JButton myFirstButton;
            private JButton mySecondButton;
            private javax.swing.JButton jButton1;
            private javax.swing.JButton jButton2;
            private javax.swing.JLabel jLabel1;
            private javax.swing.JLabel jLabel2;
            private javax.swing.JLabel jLabel3;
    
            // Constructor for a new frame
    
            public Mainframe() {
    
                    super("Welcome Page");
                    
                    
    
                    myFirstButton = new JButton("Contestant");
                    myFirstButton.setFont(new Font( "Arial", Font.BOLD, 18));
                    myFirstButton.setBackground(Color.red);
    
                    mySecondButton = new JButton("Voter");
                    mySecondButton.setFont(new Font( "Arial", Font.BOLD, 18));
                    mySecondButton.setBackground(Color.ORANGE);
    
                    Container c = getContentPane();
                    FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
                    c.setLayout(fl);
    
                    c.add (myFirstButton);
                    c.add (mySecondButton);
    
                    ButtonHandler handler = new ButtonHandler();    //creation of a new Object
                    myFirstButton.addActionListener(handler);          // Attach/register handler to myFirstButton
                    mySecondButton.addActionListener(handler);        //Attach/register handler to mySecondButton
    
                    setSize(400, 300);
                    show();
                    
           
            
            }
    
    
            public static void main(String [] args) {
    
                    // Make frame
                    Mainframe f = new Mainframe();
    
                    f.addWindowListener(
                            new WindowAdapter() {
                                    public void windowClosing(WindowEvent e) {
    
                                            // This closes the window and terminates the
                                            // Java Virtual Machine in the event that the
                                            // Frame is closed by clicking on X.
                                            System.out.println("Exit via windowClosing.");
                                            System.exit(0);
                                    }
                            }
                    );
            } // end of main
    
            // inner class for button event handling
            private class ButtonHandler implements ActionListener {
                    public void actionPerformed(ActionEvent e) {
                            if (e.getSource() == myFirstButton) {
                            
                                 PasswordDemo inputForm = new PasswordDemo();
                                    //inputForm.setVisible(true);
                                    
                                    try
                                    {
                                    PasswordDemo.createAndShowGUI();
                                    inputForm.setVisible(false);
                                    }
                                    
                                    catch(Exception d)
                                    {
                                         
                                    }
                                   // new PasswordDemo();
                            }
                            if (e.getSource() == mySecondButton) {
                                 
                           //     Profile p = Profile();
                                
                           //     p.setVisible(true);
                                  
                           }
                    }       
            }
            
            public void actionPerformed (ActionEvent e)
            {
                String cmd = e.getActionCommand();
    
                if (mySecondButton.equals(cmd)) {
                     boolean success=true; 
                     if(success)
                     {
                     Profile p = Profile();
                    
                       p.setVisible(true);
                
                     }
                     
                }
    
            
          //  private void mySecondButtonActionPerformed(java.awt.event.ActionEvent evt)
        //    {
         //        Profile p = Profile();
                
         //       p.setVisible(true);
         //   }
    
            
    } // end of outer class
    }
    Profile class:
    import java.awt.event.ActionListener;
    import java.sql.*;
    
    public class Profile extends javax.swing.JFrame {
    
        public Profile() {
            initComponents();
        }
    
        @SuppressWarnings("unchecked")
    
        private void initComponents() {
    
            titleLabel = new javax.swing.JLabel();
            nameAccess = new javax.swing.JLabel();
            ageAccess = new javax.swing.JLabel();
            heightAccess = new javax.swing.JLabel();
            weightAccess = new javax.swing.JLabel();
            lastNameAccess = new javax.swing.JLabel();
            descriptionAccess = new javax.swing.JLabel();
            nameLabel = new javax.swing.JLabel();
            lastNameLabel = new javax.swing.JLabel();
            ageLabel = new javax.swing.JLabel();
            heightLabel = new javax.swing.JLabel();
            weightLabel = new javax.swing.JLabel();
            descriptionLabel = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            titleLabel.setFont(new java.awt.Font("Gungsuh", 1, 18)); // NOI18N
            titleLabel.setText("\"User\"'s Profile");
    
            nameAccess.setText("Name: ");
            nameLabel.setText("");
            
            lastNameAccess.setText("Last Name: ");
            lastNameLabel.setText("");
    
            ageAccess.setText("Age: ");
            ageLabel.setText("");
    
            heightAccess.setText("Height: ");
            heightLabel.setText("");
            
            weightAccess.setText("Weight: ");
            weightLabel.setText("");
            
            descriptionAccess.setText("Description: ");
            descriptionLabel.setText("");
            
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(nameAccess)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(nameLabel))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(lastNameAccess)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(lastNameLabel))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(ageAccess)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(ageLabel))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(heightAccess)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(heightLabel))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(weightAccess)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(weightLabel))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(descriptionAccess)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(descriptionLabel)))
                    .addContainerGap(151, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(titleLabel)
                    .addGap(13, 13, 13)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(nameAccess)
                        .addComponent(nameLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lastNameAccess)
                        .addComponent(lastNameLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(ageAccess)
                        .addComponent(ageLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(heightAccess)
                        .addComponent(heightLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(weightAccess)
                        .addComponent(weightLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(descriptionAccess)
                        .addComponent(descriptionLabel))
                    .addContainerGap(139, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        /**
         * @param args the command line arguments
         */
        
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new Profile().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JLabel ageAccess;
        private javax.swing.JLabel ageLabel;
        private javax.swing.JLabel descriptionAccess;
        private javax.swing.JLabel descriptionLabel;
        private javax.swing.JLabel heightAccess;
        private javax.swing.JLabel heightLabel;
        private javax.swing.JLabel lastNameAccess;
        private javax.swing.JLabel lastNameLabel;
        private javax.swing.JLabel nameAccess;
        private javax.swing.JLabel nameLabel;
        private javax.swing.JLabel titleLabel;
        private javax.swing.JLabel weightAccess;
        private javax.swing.JLabel weightLabel;
        // End of variables declaration
    }
    Class PasswordDemo:
    import javax.swing.*;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Arrays;
    import java.net.*;
    import java.io.*;
    import java.util.Scanner;
    
    public class PasswordDemo extends JPanel
                              implements ActionListener  {
        private static String OK = "ok";
        private static String HELP = "help";
        private static String Register = "Register";
    
        private JFrame controllingFrame; //needed for dialogs
        private JTextField username;
        private JPasswordField passreg;
        private JTextField usernamefield;
        private JPasswordField passwordField;
    
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
    
        private JTextField name;
        private JTextField age;
        private JTextField height;
        private JTextField weight;
    
     private javax.swing.JPanel jPanel1;
    
        private void gothere() {
    
                      JFrame f = new JFrame("This is a test");
                      f.setSize(400, 300);
                      Container content = f.getContentPane();
                      content.setBackground(Color.white);
                      content.setLayout(new FlowLayout());
                     // content.add(new JButton("Button 1"));
                      //content.add(new JButton("Button 2"));
                      //
    
    
    
             name = new JTextField("Please put your name here", 20);
              name.setFont(new Font("Serif", Font.PLAIN, 14));
              content.add(name);
    
              age = new JTextField("Please put your age here", 20);
              age.setFont(new Font("Serif", Font.PLAIN, 14));
              content.add(age);
    
              height = new JTextField("Please indicate your height here", 20);
              height.setFont(new Font("Serif", Font.PLAIN, 14));
              content.add(height);
    
              weight = new JTextField("Please indicate your weight here", 20);
              weight.setFont(new Font("Serif", Font.PLAIN, 14));
              content.add(weight);
    
              content.add(new JButton("Submit"));
    
    
               f.setVisible(true);
        }
    
    
         public PasswordDemo(JFrame f) throws Exception {
            //Use the default FlowLayout.
            controllingFrame = f;
    
            //Create everything.
            usernamefield = new JTextField(10);
            usernamefield.setActionCommand(OK);
            usernamefield.addActionListener(this);
    
            passwordField = new JPasswordField(10);
            passwordField.setActionCommand(OK);
            passwordField.addActionListener(this);
    
            passreg = new JPasswordField(10);
            passreg.setActionCommand(Register);
            passreg.addActionListener(this);
    
            username = new JTextField("This is a sentence", 20);
            username.setActionCommand(Register);
            username.addActionListener(this);
    
            JLabel reg = new JLabel("If you are a new contestant please register: \n");
            JLabel user = new JLabel("Username: \n");
            user.setLabelFor(username);
            JLabel pass = new JLabel("Password: \n");
            user.setLabelFor(passreg);
    
    
            JLabel label = new JLabel("Enter your username and password to log in: ");
            label.setLabelFor(usernamefield);
            label.setLabelFor(passwordField);
    
            JComponent buttonPane = createButtonPanel();
    
            //Lay out everything.
            JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
            textPane.add(reg);
            textPane.add(user);
            textPane.add(pass);
            textPane.add(username);
            textPane.add(passreg);
    
            textPane.add(label);
            textPane.add(usernamefield);
            textPane.add(passwordField);
    
    
    
            add(textPane);
            add(buttonPane);
        }
    
        public PasswordDemo() {
              // TODO Auto-generated constructor stub
         }
    
    
         protected JComponent createButtonPanel() {
            JPanel p = new JPanel(new GridLayout(0,1));
            JButton okButton = new JButton("OK");
            JButton helpButton = new JButton("Help");
    
            JButton regButton = new JButton("Register");
    
            okButton.setActionCommand(OK);
            helpButton.setActionCommand(HELP);
            regButton.setActionCommand(Register);
            okButton.addActionListener(this);
            helpButton.addActionListener(this);
            regButton.addActionListener(this);
    
            p.add(okButton);
            p.add(helpButton);
            p.add(regButton);
    
            return p;
        }
    
        public void actionPerformed (ActionEvent e)
        {
            String cmd = e.getActionCommand();
    
            if (OK.equals(cmd)) { //Process the password.   
    
                boolean success=true;                        //Sign In
    
                 String Username="";
                 String Password="";
                 
                 Username = this.usernamefield.getText();
                 Password = this.passwordField.getText();
    
                 try
                 {
                     success=check2(Username,Password);
                }
    
                 catch(Exception d)
                 {
                      System.out.println("Got out");
    
                 }     
    
    
                 if(success)
                 {
                 JOptionPane.showMessageDialog(controllingFrame, "Sign in Successful");
                 
                 
                 Form F = new Form(Username);
                 
                 F.setVisible(true);
                 
                 
                 }
                 else
                 JOptionPane.showMessageDialog(controllingFrame, "Sign in was unsuccessful");     
    
            }
    
            else if(HELP.equals(cmd)) { //The user has asked for help.
                JOptionPane.showMessageDialog(controllingFrame,
                    "You can get the password by searching this example's\n"
                  + "source code for the string \"correctPassword\".\n"
                  + "Or look at the section How to Use Password Fields in\n"
                  + "the components section of The Java Tutorial.");
            }
    
            else if(Register.equals(cmd)) {  //*****************************************************
                 boolean success=true;
    
                 String Username="";
                 String Password="";
    
    
    
                 Username = this.username.getText();
                 Password = this.passreg.getText();
    
    
    
                 try
                 {
                      success=check(Username,Password);
                 }
    
                 catch(Exception d)
                 {
                      System.out.println("Something bad happened");
    
                 }
    
    
                 if(success)
                 JOptionPane.showMessageDialog(controllingFrame, "Registration successful");
    
                 else
                 JOptionPane.showMessageDialog(controllingFrame, "Registration was unsuccessful");
    
    
            }
        }
    
        //Must be called from the event dispatch thread.
        protected void resetFocus() {
            passwordField.requestFocusInWindow();
        }
    
        static void createAndShowGUI() throws Exception {
            //Create and set up the window.
            JFrame frame = new JFrame("Registration Page");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            //Create and set up the content pane.
            final PasswordDemo newContentPane = new PasswordDemo(frame);
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
    
            //Make sure the focus goes to the right component
            //whenever the frame is initially given the focus.
            frame.addWindowListener(new WindowAdapter() {
                public void windowActivated(WindowEvent e) {
                    newContentPane.resetFocus();
                }
            });
    
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
        public static void main(String args[]) {
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    //Turn off metal's use of bold fonts
              UIManager.put("swing.boldMetal", Boolean.FALSE);
              try{
              createAndShowGUI();
              }
    
                catch(Exception e)
                {
    
                }
                }
                     });
                 }
    
        public void sendUserPass(String user,String pass)throws Exception
        {
    
             //Send request
    
    
             Class.forName("com.mysql.jdbc.Driver");
    
              Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","");
    
              System.out.println("connected :D:D:D:D");
    
              PreparedStatement state = con.prepareStatement("Insert Into Contestant (USERNAME,PASSWORD) values ('"+user+"','"+pass+"')");
    
              state.executeUpdate();
    
              /*while(Result.next())
              {
                   System.out.println(Result.getString(1)+"\t"+Result.getString(2));
    
              }*/
    
              //server should reply by updating database
        }
    
    
        public boolean check(String user,String pass)throws Exception
        {
    
             //Send request
             Socket Sock = new Socket ("LocalHost",5000);
             
             DataOutputStream toServer = new DataOutputStream(Sock.getOutputStream());
             BufferedReader buff = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
             
             String sentence="";
             
             toServer.writeBytes("1\n");
             
             sentence=buff.readLine();
             
             System.out.println(sentence+"\n");
             
             toServer.writeBytes(user+" "+pass+"\n");
             
             String answer="";
             
             answer = buff.readLine();
             
             if(answer.equals("No"))
                  return false;
             
             return true;
      
             /*Class.forName("com.mysql.jdbc.Driver");
    
              Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","");
    
              System.out.println("connected :D:D:D:D");
    
              PreparedStatement state = con.prepareStatement("Select Username From Contestant where '"+user+"'= username");
    
              ResultSet Result = state.executeQuery();
    
              if(!Result.next())
              return true;*/
    
              
    
              //server should reply by updating database
        }
        
        
        public boolean check2(String user,String pass)throws Exception
        {
             Socket Sock = new Socket("localhost",5000);
             
             DataOutputStream toServer = new DataOutputStream (Sock.getOutputStream());
             BufferedReader buff = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
             
             toServer.writeBytes("2\n");
             
             System.out.println("Well I sent the message");
             
             String sentence = buff.readLine();
             
             toServer.writeBytes(user+" "+pass+"\n");
             
             System.out.println(sentence);
             
             sentence=buff.readLine();
             
             System.out.println(sentence+"\n");
             
             
             if(sentence.equals("No"))
                  return false;
             
             return true;
        }
    
    
    }
    Profile p = Profile();
    

    Who says "call a 'Profile' method name that is defined in the current class"

    Maybe what you mean is:

    Profile p = new Profile();
    

    who says "create a new instance of the profile class and invoke its no. - arg constructor."

Maybe you are looking for

  • Electric shocks of MacBook Pro + iPhone?

    So I got a MacBook Pro 13 "mid 2012 and an iPhone 6s. When the charger is plugged into any one of these devices, if I touch my arm to the chassi of the macbook I get electric shocks (small, but still feelable). Also if I put something against the cam

  • Satellite P200 - 1EE 100% CPU with Toshiba Flash Cards usage

    Resource monitor shows 100% CPU usage constantly in recent weeks (no problem for the first 6 months that I have owned the machine) with 85 to 99% of my CPU used on 2 entries each shown as "Toshiba Flash Cards", no idea why and how I can sort this out

  • Transfer to VIEW report card

    Hello I'm trying to transfer a card from the DISPLAY Panel in the Panel REPORT. However, it is not serious as I do (by button or script), the card gets strechted. Do you guys know how to fix it? SEE the Image REPORT image Sincere greetings, Augusto S

  • Error 1074360317 - IMAQdx get image.vi

    I have an en program Labview and vision 8.2 which works very well.  Version of Notre Dame we changed of Labview and lately vision pour version 8.6. When I build and stretches target my application on the computer with the new version the program retu

  • PXI-5114 example LabVIEW Code

    Salvation; I'm looking for example LabVIEW PXI-5114 configuration including trigger code? I have the mounted 5114 in SMU-1065 chassis. I am using LabVIEW 2010. Thank you for all the examples. Steve