Implementing ActionListener in inner class

Hi
I'm trying to add an action listener to a button. When i add the new actionlistener i create an anonymous non static inner class at the same time, which has a actionPerfomed(ActionEvent e) method. My checkString() method is in another package, Validate, which i have imported.
When i try to run the program, i get the following error message:
GUI/MyGraphics.java [74:1] non-static method checkString(java.lang.String) cannot be referenced from a static context
boolean textOk = Validator.checkString(userInput);
^
The problem is do with the face that the compiler sees actionPerfomed(ActionEvent e) as a static method/context. How is it static?
(when i preview my code, it loses all it's indentation. how can i fix this?)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import Interfaces.*;
import Validate.*;
public class MyGraphics
    public void startGui()
        JFrame f = new JFrame("Greetings!");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container c = f.getContentPane();
        JLabel lblTop = new JLabel("Who are you? Please enter your                             .       name...");
        c.add(lblTop, BorderLayout.NORTH);
        final JLabel lblResponse = new JLabel();
        c.add(lblResponse, BorderLayout.SOUTH);
        final JLabel lblResponse2 = new JLabel();
        c.add(lblResponse2, BorderLayout.EAST);
        final TextField tfOne = new TextField("My name is...", 50);
        c.add(tfOne, BorderLayout.CENTER);
        JPanel jp = new JPanel();
        JButton Bok = new JButton("Ok");
        jp.add(Bok);
        JButton Bbye = new JButton("Bye!");
        jp.add(Bbye);
        c.add(jp, BorderLayout.SOUTH);
        f.pack();
        f.show();  
        Bok.addActionListener(new ActionListener(){    
        public void actionPerformed(ActionEvent e)
            try
                String userInput = tfOne.getText();
                boolean textOk = Validator.checkString(userInput);
                    if(textOk == true)
                        lblResponse.setText("You Have Success!");
                    else
                        lblResponse.setText("Sorry, No Success.");
            catch (Exception a)
                lblResponse.setText("ERROR! You must enter a valid   value");
}

thank you, that is exactly what i needed.
also, i don't know how to keep my code indentation. i type it in the text field with proper indents but when i preview it, it loses all formatting. how can i prevent this happening?

Similar Messages

  • ActionListener and Inner Class Issue

    When I add ".addActionListener()" to buttons and create an inner class to listen/handle the action, my main class does not display the GUI. If I remove the ".addActionListener()" from the buttons and the inner class, the GUI displays. Below is my code. Anyone know what is wrong with my code?
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(new ButtonHandler());
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class package projects.web;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class FileBrowser{
         JFileChooser fileChooser = new JFileChooser();
         public FileBrowser(){
              int fileChooserOption = fileChooser.showOpenDialog(null);
         } // end constructor
    } // end class fileBrowser

    Encephalopathic wrote:
    Dan: When it doesn't display, what happens? Do you see any error messages? Also, please take a look at your other thread in this same forum as it has relevance to our conversations in the java-forums.org about whether to add GUIs to root containers or the other way around. /PeteI fiddled with the code some more and it seems that the problem is the inner code. When I changed from the inner class to the main class implementing ActionListener and had the main class implement the actionPerformed method, the GUI displayed and JFileChooser worked as well. I've add this version of the code at the bottom of this message.
    To answer your question: When it doesn't display, what happens? -- The web page loads and is blank. And there are no error messages.
    I took a look at the other thread is this forum (the one relates to our conversation in the other forum); the problem may be the way I've add the GUI. I'll try it the other way and see what happens.
    Thanks,
    Dan
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI implements ActionListener{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(this);
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class

  • Why and how to use "inner class"

    When i am learning advanced java language features,
    i could not understand why and when to use the "inner class",
    who can give me some examples?
    Thanks!

    You would use an inner class when an object needs visibility of the outer class. This is akin to a C++ friend.
    An example of this is an iterator. An iterator over some collection is typically implemented as an inner class of the collection class. The API user asks for an Iterator (from the Collection) and gets one - in fact they receive an instance of an inner class, but doesn't care. The iterator needs to be inner, as the iterator needs to see the internal data structures of the outer (collection) class.
    This could also be done with an anonymous class, as mentioned by spenhoet above. However, in the case of a collection, the role of the iterator is clear - thus it deserves its own class. And often there is more than one place an iterator can be returned (e.g. see java.util.List, which has several methods that return Iterators/ListIterators), thus it must be put in its own class to allow reuse of the code by outer class.

  • Assign value in a inner class

    Suppose, we have the following two classes.
    public class test{
    final trythis t;
    t = null;
    doMethod(t); // because of this, t has to be assigned a null value
    (new Thread(){public void run(){
        t = new trythis();  // t is assigned twice
      }}).start();
    class trythis{
    trythis(){
    t seems to have to be defined as final, but final instance cannot be set in the inner class.
    Does anyone know how to solve this problem?
    Thanks

    As the local variable has a lifetime of the executing method's
    duration, you must ensure the innerclass (which has a longer lifetime)
    has access to it by declaring it final.This is not quite exact. All this is due to the way inner classes are implemented. An inner class maintains the contents of the outer local variables used in two ways:
    - If it is primitive, use the value verbatim (so the class has no relationship to the outer variable, it just uses the same number, so the local var needs to be final or else there could be surprises for a programmer who would think that changing the local var would also change the value used in the inner class)
    - If it is a reference, copy it as a class member, and use that one wherever needed. For similar reasons as above, the two references have to be in sync, so the local var has to be final (the inner var can't change anyway)
    This apply only to local variables because class members are accessible through a secret reference of the enclosing object passed in the constructor of the inner class. Static members are anyway accessible.
    <teacher's mode off/>
    <sorry for that, but someone might find the explanation useful :-)/>
    By the way, the OP can get the value "t" out of the inner class by providing a special Thread subclass, ie
    class MyThread extends Thread {
      public void run() {
        t = something;
      trythis t;
    MyThread thread = new MyThread();
    thread.start();
    thread.join();
    thread.t; //This is accessibleI'm not sure if this would be preferable to the array approach (which is ), but it is useful to know your alternatives

  • Question about anonymous inner class??

    Is there any error occurs,If a class declear & implement two anonymous inner classes ??

    public class TryItAndSee {
        void m() {
            Runnable x = new Runnable(){
                public void run() {
                    System.out.println("?");
            Runnable y = new Runnable(){
                public void run() {
                    System.out.println("!");
    }

  • Main method not found and how to implement events in an inner class

    How would I put all the event handling methods in an inner class and I have another class that just that is just a main function, but when i try to run the project, it says main is not found. Here are the two classes, first one sets up everything and the second one is just main.
    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
    private JLabel dateLabel = new JLabel("Date: ");
    private JTextField dateField = new JTextField(20);
    private JPanel datePanel = new JPanel(new FlowLayout());
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel radioPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel textAreaPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    GridLayout gridLayout1 = new GridLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout2 = new GridLayout();
    GridLayout gridLayout3 = new GridLayout();
    JRadioButton personalButton = new JRadioButton();
    JRadioButton businessButton = new JRadioButton();
    JLabel status = new JLabel();
    JTextArea entryArea = new JTextArea();
    JButton clearButton = new JButton();
    JButton saveButton = new JButton();
    ButtonGroup entryType = new ButtonGroup();
    public JournalFrame(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void initWidgets(){
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    radioPanel.setLayout(gridLayout1);
    statusPanel.setLayout(flowLayout1);
    textAreaPanel.setLayout(gridLayout2);
    buttonPanel.setLayout(gridLayout3);
    personalButton.setSelected(true);
    personalButton.setText("Personal");
    personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
    businessButton.setText("Business");
    status.setText("");
    entryArea.setText("");
    entryArea.setColumns(10);
    entryArea.setLineWrap(true);
    entryArea.setRows(30);
    entryArea.setWrapStyleWord(true);
    clearButton.setPreferredSize(new Dimension(125, 25));
    clearButton.setText("Clear Journal Entry");
    clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
    saveButton.setText("Save Journal Entry");
    saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
    this.setTitle("Journal");
    gridLayout3.setColumns(1);
    gridLayout3.setRows(0);
    this.getContentPane().add(datePanel, BorderLayout.NORTH);
    this.getContentPane().add(radioPanel, BorderLayout.WEST);
    this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.EAST);
    entryType.add(personalButton);
    entryType.add(businessButton);
    datePanel.add(dateLabel);
    datePanel.add(dateField);
    radioPanel.add(personalButton, null);
    radioPanel.add(businessButton, null);
    textAreaPanel.add(entryArea, null);
    buttonPanel.add(clearButton, null);
    buttonPanel.add(saveButton, null);
    this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    statusPanel.add(status, null);
    this.pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    private void saveEntry() throws IOException{
    if( personalButton.isSelected())
    String file = "Personal.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    entryArea.getText();
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    else if (businessButton.isSelected())
    String file = "Business.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    void clearButton_actionPerformed(ActionEvent e) {
    dateField.setText("");
    entryArea.setText("");
    status.setText("");
    void saveButton_actionPerformed(ActionEvent e){
    try{
    saveEntry();
    }catch(IOException error){
    status.setText("Error: Could not save journal entry");
    void personalButton_actionPerformed(ActionEvent e) {
    class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.personalButton_actionPerformed(e);
    public class JournalApp {
    public static void main(String args[])
    JournalFrame journal = new JournalFrame();
    journal.setVisible(true);
    }

    Here is the complete code (with crappy indentation) :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
        private JLabel dateLabel = new JLabel("Date: ");
        private JTextField dateField = new JTextField(20);
        private JPanel datePanel = new JPanel(new FlowLayout());
        BorderLayout borderLayout1 = new BorderLayout();
        JPanel radioPanel = new JPanel();
        JPanel statusPanel = new JPanel();
        JPanel textAreaPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
        GridLayout gridLayout1 = new GridLayout();
        FlowLayout flowLayout1 = new FlowLayout();
        GridLayout gridLayout2 = new GridLayout();
        GridLayout gridLayout3 = new GridLayout();
        JRadioButton personalButton = new JRadioButton();
        JRadioButton businessButton = new JRadioButton();
        JLabel status = new JLabel();
        JTextArea entryArea = new JTextArea();
        JButton clearButton = new JButton();
        JButton saveButton = new JButton();
        ButtonGroup entryType = new ButtonGroup();
        public JournalFrame(){
            try {
                jbInit();
            catch(Exception e){
                e.printStackTrace();
        private void initWidgets(){
        private void jbInit() throws Exception {
            this.getContentPane().setLayout(borderLayout1);
            radioPanel.setLayout(gridLayout1);
            statusPanel.setLayout(flowLayout1);
            textAreaPanel.setLayout(gridLayout2);
            buttonPanel.setLayout(gridLayout3);
            personalButton.setSelected(true);
            personalButton.setText("Personal");
            personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
            businessButton.setText("Business");
            status.setText("");
            entryArea.setText("");
            entryArea.setColumns(10);
            entryArea.setLineWrap(true);
            entryArea.setRows(30);
            entryArea.setWrapStyleWord(true);
            clearButton.setPreferredSize(new Dimension(125, 25));
            clearButton.setText("Clear Journal Entry");
            clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
            saveButton.setText("Save Journal Entry");
            saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
            this.setTitle("Journal");
            gridLayout3.setColumns(1);
            gridLayout3.setRows(0);
            this.getContentPane().add(datePanel, BorderLayout.NORTH);
            this.getContentPane().add(radioPanel, BorderLayout.WEST);
            this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
            this.getContentPane().add(buttonPanel, BorderLayout.EAST);
            entryType.add(personalButton);
            entryType.add(businessButton);
            datePanel.add(dateLabel);
            datePanel.add(dateField);
            radioPanel.add(personalButton, null);
            radioPanel.add(businessButton, null);
            textAreaPanel.add(entryArea, null);
            buttonPanel.add(clearButton, null);
            buttonPanel.add(saveButton, null);
            this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
            statusPanel.add(status, null);
            this.pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        private void saveEntry() throws IOException{
            if( personalButton.isSelected()){
                String file = "Personal.txt";
                BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
                entryArea.getText();
                bw.write("Date: " + dateField.getText());
                bw.newLine();
                bw.write(entryArea.getText());
                bw.newLine();
                bw.flush();
                bw.close();
                status.setText("Journal Entry Saved");
            else if (businessButton.isSelected()){
                String file = "Business.txt";
                BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
                bw.write("Date: " + dateField.getText());
                bw.newLine();
                bw.write(entryArea.getText());
                bw.newLine();
                bw.flush();
                bw.close();
                status.setText("Journal Entry Saved");
        void clearButton_actionPerformed(ActionEvent e) {
            dateField.setText("");
            entryArea.setText("");
            status.setText("");
        void saveButton_actionPerformed(ActionEvent e){
            try{saveEntry();}catch(IOException error){
                status.setText("Error: Could not save journal entry");
        void personalButton_actionPerformed(ActionEvent e) {
        class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.personalButton_actionPerformed(e);
    }BadLands

  • How do i create a static function in a class and implement ActionListener?

    i am trying to create a pop up dialog box in a seperate class.
    and i want to make the Function static, so that i only need to access it with the class name.
    But how do i have a ActionListener ?
    everything in a static function is static rite?

    import java.awt.*;
    import java.awt.event.*;
    public class StaticFunction
        Dialog dialog;
        private Panel getUIPanel()
            Button button = new Button("show dialog");
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    if(dialog == null)
                        dialog = OutsideUtility.showDialog("hello world");
                    else if(!dialog.isVisible())
                        dialog.setVisible(true);
                    else if(dialog.isVisible())
                        dialog.dispose();
                        dialog = null;
            Panel panel = new Panel();
            panel.add(button);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        public static void main(String[] args)
            StaticFunction sf = new StaticFunction();
            Frame f = new Frame();
            f.addWindowListener(sf.closer);
            f.add(sf.getUIPanel());
            f.setSize(200,100);
            f.setLocation(200,200);
            f.setVisible(true);
    class OutsideUtility
        public static Dialog showDialog(String msg)
            Button button = new Button("top button");
            button.setActionCommand(msg);
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    Button button = (Button)e.getSource();
                    System.out.println(button.getActionCommand() +
                                       " from anonymous inner listener");
            button.addActionListener(new ButtonListener());
            Button anotherButton = new Button("bottom button");
            anotherButton.setActionCommand("another button");
            anotherButton.addActionListener(localListener);
            Panel north = new Panel();
            north.add(button);
            Panel south = new Panel();
            south.add(anotherButton);
            Dialog dialog = new Dialog(new Frame());
            dialog.addWindowListener(closer);
            dialog.add(north, "North");
            dialog.add(new Label(msg, Label.CENTER));
            dialog.add(south, "South");
            dialog.setSize(200,200);
            dialog.setLocation(425,200);
            dialog.setVisible(true);
            return dialog;
        private static WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                Dialog dialog = (Dialog)e.getSource();
                dialog.dispose();
        private static ActionListener localListener = new ActionListener()
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                System.out.println(button.getActionCommand() +
                                   " from localListener");
        private static class ButtonListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                String ac = button.getActionCommand();
                System.out.println(ac + " from ButtonListener");
    }

  • Cann't extend a inner class where as can Implement a nested Interface

    i cann't extend a inner class in some other outer class . Where as i can implement the nested Interface in some other class. Why????
    for example:-
    class ABC
    class Inner
    /* class body */
    interface TempInterface
    /* interfacebody */
    class OuterClass
    class InnerTwo extends ABC.inner //(line 1)Will give error
    class InnerTwo implements ABC.TempInterface //(line 2)Will run fine
    the line 1 is going to give compilation error i.e not in the scope but the line 2 will run fine .
    Both of the things are in the same class but giving 2 other results.
    I am not getting sufficient reasons for it.
    Can any one help me????
    Reagrds
    Arunabh

    As far as the language is concerned, the classonly
    exists in the context of an instance of theenclosing
    class.This still exhibits a class/object confusion to me.
    It should be 'instance only exists ...' or 'instance
    can only exist'. The class only exists in the
    scope of the enclosing class, but this is another
    issue.I'm not following what you're saying. The second sentence sounds like you're disagreeing with me. The last sentence sounds like you're agreeing with me.
    A non-static nested class is an instance member, just like an instance method or instance variable. As such, as far as the language is concerned, that class only exists in the context of an instance of the enlcosing class.It's not just instances of the nested class--its the class definition itself that only exists within the context of an instance of the enclosing class. That's why you have to do anEclosingIntstance.NestedClass and can't do EnclosingClass.NestedClass.

  • How to pass a variable value to an inner class?

    Hi there,
    Please have a look of the code below. It's a bit long, but my concern is I did have to declare the int "i" variable as static because it is used by an inner class (if "i" is not declare as static, the code cannot be compiled).
    Is there a more "clean" way to do the way work without declaring the "i" int as static? (because the scope of this variable is not the whole program).
    Thanks for your help.
    Denis
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Tools{
         static int i;
         static void longTask(){
              for (Tools.i=0; Tools.i<=100; Tools.i++) {
                   SwingUtilities.invokeLater( new Runnable(){
                        public void run(){
                             myApp.jpb.setValue(Tools.i);//--- static variable i
                   for (int j=0; j<200; j++)
                        System.out.println(Tools.i+" - "+j);
    class myListener implements ActionListener{
         public void actionPerformed(ActionEvent e){
              Thread t = new Thread() {
                   public void run(){
                        Tools.longTask();
              t.start();
    public class myApp {
         static JProgressBar jpb;
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JPanel panel = new JPanel(new FlowLayout());
              jpb = new JProgressBar();
              jpb.setValue(0);
              jpb.setStringPainted(true);
              JButton button = new JButton("go");
              button.addActionListener(new myListener());
              panel.add(jpb);
              panel.add(button);
              frame.getContentPane().add( panel, BorderLayout.CENTER);
              frame.setVisible(true);
              frame.pack();
    }

    Without compiling it, writing it in notepad, it would be something like this. You should also wonder if this longTask has to be static by the way. But I think this demonstrates the inner class stuff. You can also look in the tutorial on this site: http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    class Tools{
         static int i;
         static void longTask(){
              for (Tools.i=0; Tools.i<=100; Tools.i++) {
                   SwingUtilities.invokeLater( new Innerclass(i));
                   for (int j=0; j<200; j++) {
                        System.out.println(Tools.i+" - "+j);
         Class Innerclass implements Runnable(){
              int i;
              public Innerclass(int i) {
                   this.i = i;
              public void run(){
                   myApp.jpb.setValue(Tools.i);//--- static variable i
    }

  • Null pointer exception with inner class

    Hi everyone,
    I've written an applet that is an animation of a wheel turning. The animation is drawn on a customised JPanel which is an inner class called animateArea. The main class is called Rotary. It runs fine when I run it from JBuilder in the Applet Viewer. However when I try to open the html in internet explorer it gives me null pointer exceptions like the following:
    java.lang.NullPointerException      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2761)      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2722)      
    at Rotary$animateArea.paintComponent(Rotary.java:251)      
    at javax.swing.JComponent.paint(JComponent.java:808)      
    at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4771)      
    at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)      
    at javax.swing.JComponent._paintImmediately(JComponent.java:4668)      
    at javax.swing.JComponent.paintImmediately(JComponent.java:4477)      
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)      
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)      
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)      
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:448)      
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)      
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)      
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    Do inner classes have to be compiled seperately or anything?
    Thanks a million for you time,
    CurtinR

    I think that I am using the Java plugin ( Its a computer in college so I'm not certain but I just tried running an applet from the Swing tutorial and it worked)
    Its an image of a rotating wheel and in each sector of the wheel is the name of a person - when you click on the sector it goes red and the email window should come up (that doesn't work yet though). The stop and play buttons stop or start the animation. It is started by default.
    This is the code for the applet:
    import java.applet.*;
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.util.StringTokenizer;
    import java.net.*;
    public class Rotary extends JApplet implements ActionListener, MouseListener
    public boolean rotating;
    private Timer timer;
    private int delay = 1000;
    private AffineTransform transform;
    private JTextArea txtTest; //temp
    private Container c;
    private animateArea wheelPanel;
    private JButton btPlay, btStop;
    private BoxLayout layout;
    private JPanel btPanel;
    public Image wheel;
    public int currentSector;
    public String members[];
    public int [][]coordsX, coordsY; //stores sector no. and x or y coordinates for that point
    final int TOTAL_SECTORS= 48;
    //creates polygon array - each polygon represents a sector on wheel
    public Polygon polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
    polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
    polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
    polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
    polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48;
    public Polygon polySectors[]={polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
                      polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
                      polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
                      polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
                      polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48};
    public void init()
    members = new String[TOTAL_SECTORS];
    coordsX= new int[TOTAL_SECTORS][4];
    coordsY= new int[TOTAL_SECTORS][4];
    currentSector = -1;
    rotating = true;
    transform = new AffineTransform();
    //***********************************Create GUI**************************
    wheelPanel = new animateArea(); //create a canvas where the animation will be displayed
    wheelPanel.setSize(600,580);
    wheelPanel.setBackground(Color.yellow);
    btPanel = new JPanel(); //create a panel for the buttons
    btPanel.setLayout(new BoxLayout(btPanel,BoxLayout.Y_AXIS));
    btPanel.setBackground(Color.blue);
    btPanel.setMaximumSize(new Dimension(30,580));
    btPanel.setMinimumSize(new Dimension(30,580));
    btPlay = new JButton("Play");
    btStop = new JButton("Stop");
    //txtTest = new JTextArea(5,5); //temp
    btPanel.add(btPlay);
    btPanel.add(btStop);
    // btPanel.add(txtTest); //temp
    c = getContentPane();
    layout = new BoxLayout(c,layout.X_AXIS);
    c.setLayout(layout);
    c.add(wheelPanel); //add panel and animate canvas to the applet
    c.add(btPanel);
    wheel = getImage(getDocumentBase(),"rotary2.gif");
    getParameters();
    for(int k = 0; k <TOTAL_SECTORS; k++)
    polySectors[k] = new Polygon();
    for(int n= 0; n<4; n++)
    polySectors[k].addPoint(coordsX[k][n],coordsY[k][n]);
    btPlay.addActionListener(this);
    btStop.addActionListener(this);
    wheelPanel.addMouseListener(this);
    startAnimation();
    public void mouseClicked(MouseEvent e)
    if (rotating == false) //user can only hightlight a sector when wheel is not rotating
    for(int h= 0; h<TOTAL_SECTORS; h++)
    if(polySectors[h].contains(e.getX(),e.getY()))
    currentSector = h;
    wheelPanel.repaint();
    email();
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void email()
    try
    URL rotaryMail = new URL("mailto:[email protected]");
    getAppletContext().showDocument(rotaryMail);
    catch(MalformedURLException mue)
    System.out.println("bad url!");
    public void getParameters()
    StringTokenizer stSector;
    String parCoords;
    for(int i = 0; i <TOTAL_SECTORS; i++)
    {               //put member names in applet parameter list into an array
    members[i] = getParameter("member"+i);
    //separate coordinate string and store coordinates in 2 arrays
    parCoords=getParameter("sector"+i);
    stSector = new StringTokenizer(parCoords, ",");
    for(int j = 0; j<4; j++)
    coordsX[i][j] = Integer.parseInt(stSector.nextToken());
    coordsY[i][j] = Integer.parseInt(stSector.nextToken());
    public void actionPerformed(ActionEvent e)
    wheelPanel.repaint(); //repaint when timer event occurs
    if (e.getActionCommand()=="Stop")
    stopAnimation();
    else if(e.getActionCommand()=="Play")
    startAnimation();
    public void startAnimation()
    if(timer == null)
    timer = new Timer(delay,this);
    timer.start();
    else if(!timer.isRunning())
    timer.restart();
    Thanks so much for your help!

  • Main method not found and how to put event handlers in an inner class

    How would I put all the event handling methods in an inner class and I have another class that just that is just a main function, but when i try to run the project, it says main is not found. Here are the two classes, first one sets up everything and the second one is just main.
    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
    private JLabel dateLabel = new JLabel("Date: ");
    private JTextField dateField = new JTextField(20);
    private JPanel datePanel = new JPanel(new FlowLayout());
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel radioPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel textAreaPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    GridLayout gridLayout1 = new GridLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout2 = new GridLayout();
    GridLayout gridLayout3 = new GridLayout();
    JRadioButton personalButton = new JRadioButton();
    JRadioButton businessButton = new JRadioButton();
    JLabel status = new JLabel();
    JTextArea entryArea = new JTextArea();
    JButton clearButton = new JButton();
    JButton saveButton = new JButton();
    ButtonGroup entryType = new ButtonGroup();
    public JournalFrame(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void initWidgets(){
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    radioPanel.setLayout(gridLayout1);
    statusPanel.setLayout(flowLayout1);
    textAreaPanel.setLayout(gridLayout2);
    buttonPanel.setLayout(gridLayout3);
    personalButton.setSelected(true);
    personalButton.setText("Personal");
    personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
    businessButton.setText("Business");
    status.setText("");
    entryArea.setText("");
    entryArea.setColumns(10);
    entryArea.setLineWrap(true);
    entryArea.setRows(30);
    entryArea.setWrapStyleWord(true);
    clearButton.setPreferredSize(new Dimension(125, 25));
    clearButton.setText("Clear Journal Entry");
    clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
    saveButton.setText("Save Journal Entry");
    saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
    this.setTitle("Journal");
    gridLayout3.setColumns(1);
    gridLayout3.setRows(0);
    this.getContentPane().add(datePanel, BorderLayout.NORTH);
    this.getContentPane().add(radioPanel, BorderLayout.WEST);
    this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.EAST);
    entryType.add(personalButton);
    entryType.add(businessButton);
    datePanel.add(dateLabel);
    datePanel.add(dateField);
    radioPanel.add(personalButton, null);
    radioPanel.add(businessButton, null);
    textAreaPanel.add(entryArea, null);
    buttonPanel.add(clearButton, null);
    buttonPanel.add(saveButton, null);
    this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    statusPanel.add(status, null);
    this.pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    private void saveEntry() throws IOException{
    if( personalButton.isSelected())
    String file = "Personal.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    entryArea.getText();
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    else if (businessButton.isSelected())
    String file = "Business.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    void clearButton_actionPerformed(ActionEvent e) {
    dateField.setText("");
    entryArea.setText("");
    status.setText("");
    void saveButton_actionPerformed(ActionEvent e){
    try{
    saveEntry();
    }catch(IOException error){
    status.setText("Error: Could not save journal entry");
    void personalButton_actionPerformed(ActionEvent e) {
    class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.personalButton_actionPerformed(e);
    public class JournalApp {
    public static void main(String args[])
    JournalFrame journal = new JournalFrame();
    journal.setVisible(true);
    }

    Bet you're trying "java JournalFrame" when you need to "java JournalApp".
    Couple pointers toward good code.
    1) Use white space (extra returns) to separate your code into logical "paragraphs" of thought.
    2) Add comments. At a minimum a comment at the beginning should name the file, state its purpose, identify the programmer and date written. A comment at the end should state that you've reached the end. In the middle, any non-obvious code should be commented and closing braces or parens should have a comment stating what they close (if there is non-trivial separation from where they open).
    Here's a sample:
    // JournalFrame.java - this does ???
    // saisoft, 4/18/03
    // constructor
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        radioPanel.setLayout(gridLayout1);
        statusPanel.setLayout(flowLayout1);
        textAreaPanel.setLayout(gridLayout2);
        buttonPanel.setLayout(gridLayout3);
        personalButton.setSelected(true);
        personalButton.setText("Personal");
        personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
        businessButton.setText("Business");
        status.setText("");
        entryArea.setText("");
        entryArea.setColumns(10);
        entryArea.setLineWrap(true);
        entryArea.setRows(30);
        entryArea.setWrapStyleWord(true);
    } // end constructor
    // end JournalFrame.java3) What would you expect to gain from that inner class? It might be more cool, but would it be more clear? I give the latter (clarity) a lot of importance.

  • Event handling... inner classes or not? what do you recomend?

    Me question is should you
    use
    JButton addbutton=new JButton("Add");
    addbutton.addNewActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    or this
    class Window implements ActionListener
    public void actionPerformed(ActionEvent e)
    if (e.getSource()==addbutton)
    if (e.getSource()==...
    So when I would have say menu and 15 menuitems to listen, I would prefer the innerclass system becauses it somehow produces cleaner code, but it creates pretty much of those $1 $2 files... will it be a problem?

    I prefer to use inner classes since it makes clean code.
    However I prefer to define one innerclass per source
    type and not the getSource() trick. This gives a clean
    separation of responsability. You can use the same
    innerclass for different sources if the reaction should
    be the same for different user inputs.you mean something like this:
    Button b1=new Button("Edit1");
    Button b2=new Button("Edit2");
    b1.addActionListener(new InnerClass(b1));
    b2.addActionListener(new InnerClass(b2));
    ...

  • Private inner classes

    I'm trying to complete a "turn the lightbulb on and off" program, but when I try to draw circle2 in the
    ButtonListener class I get an error message cannot find symbol. This is in reference to the Graphics
    variable "page" created in the paintComponent method below. Shouldn't the inner class, private or
    public inherit all data variables including objects from the parent class, in this case, the Bulb class? The code is below.
    By the way, this IS NOT a school assignment so any help would be appreciated. I'm just trying to learn
    this language.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Bulb extends JPanel
         private JButton push;
         private Circle circle, circle2;
         private final int DIAMETER = 100;
         private final int X = 10;
         private final int Y = 10;
         public Bulb()
              circle = new Circle(DIAMETER, Color.white, X,Y);
              circle2 = new Circle(DIAMETER, Color.yellow, X, Y); // to separate class
              push = new JButton("Turn on the Bulb");
              push.addActionListener(new ButtonListener());
              add(push);
              setPreferredSize(new Dimension(500, 500));
              setBackground(Color.black);
         public void paintComponent(Graphics page)
              super.paintComponent(page);
              circle.draw(page);
    private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event) //PROBLEM AREA. I GET ERROR MESSAGE STATING
    // "CANNOT FIND SYMBOL" IN REFERENCE TO VARIABLE "PAGE."
    // I THOUGHT THE INNER CLASS INHERITS ALL DATA FROM
    // PARENT CLASS SUCH AS "PAGE."
                   circle2.draw(page);
    }

    There are fields, which are associated with either a class or an object (and thus live in the heap in an object on the heap), and there are local variables, which are associated with methods and threads (i.e., a method invoked within a thread, and which thus live on the stack).
    They're not the same thing.
    You can't use a local variable in your paintComponent method in a different method.
    Anyway you're designing your class wrong. Think model-view-controller. You have the model: a bunch of state and possibly behavior that represents the thing being seen, modified, and displayed. You have the view, which is how you see the model. And you have the controller, which modifies the model.
    Your event handlers are part of the controller. They should change the model.
    Your paintComponent method is part of the view.
    So the event handlers should change some data, e.g., add a note that a circle should be displayed.
    Then your paintComponent method should look at the data and act accordingly -- e.g., see that there's a circle to be displayed, and display it.

  • Inner classes should appear in jar?

    At first thanks for answering my question: I did resolve the problem of excluding files, so the .java and .html are not present anymore�.. but the problem stays: I do see the applet in the applet viewer but not on the safari (mac Version 3.0.4) browser. The tag, I think is ok:
    <applet code="Slides.class" width="500" height="500" archive="slides.jar"></applet>
    A second question related to this problem might be, that the two inner class files that show up in the build/class file are not present in the jar. The application consists of just one single class (I already moved some initialization stuff from the constructor to the init). The class is called Slides.class and the compiler generates the Slides$1, Slides$xxx and Slides$yyyy. Should they all be included in the jar I only so the main class.
    Thanks a lot
    willemjav
    The (still dirty) code is here (you need a folder with images files called xxxx#img01 etc.) and a first image called firstpic.jpg
    * Slides
    * Created on February 3, 2008, 10:25 PM
    * The application does an applet slide show
    * of a list of images files set in the folder
    * Imagestore each 7 seconds changes the picture
    * see DURATION
    * still to do an image list check on file extentions
    * and a fade in/ out
    * @author wdragstra
    import java.awt.*;
    import java.awt.Image;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.net.URL;
    import java.io.*;
    import java.awt.image.BufferedImage;
    public class Slides2 extends JPanel implements ActionListener {
    private int count, maxcount, x, y, duration,
    textposx, textposy, imgwidth, imgheight;
    static int framew, frameh;
    private boolean intro;
    private static final int LOAD = 7000, PAUSE=4000; // animation duration
    private static final String FILE_NAME="Imagestore"; // the image file name in work directory
    private File directory; // File object referring to the directory.
    private String[] picfilenames; // Array of file names in the directory.
    private JOptionPane infoPane;
    private JPanel picttextPanel;
    private JLabel textLabel;
    private Timer load, timer, pause;
    private Image firstpic;
    private BufferedImage OSC;
    public Slides2() { // construtor
    framew = 350; // frame size to be set
    frameh = 390;
    textposx = 130; // text position to be set
    textposy = 20;
    duration = 9000; // image duration to be set
    count=0; // image and textstring counters
    maxcount = 0;
    load = new Timer(LOAD, this); // the three animation timers
    readImageFilelist(FILE_NAME); // get the content of the image folder
    firstpic = downloadImage("firstpic.jpg");
    orderImages();
    timer = new Timer(duration, this);
    infoPane = new JOptionPane(); // containing the 1) firstpic.jpg the
    picttextPanel = new JPanel(); // first picture or only picture
    textLabel = new JLabel(" INFO ", JLabel.CENTER); // 2) the parameter file called
    this.setLayout(null); // imageanimater.txt 3) the imgefiles
    textLabel.setBounds(textposy,textposx, 300 , 50); // with name xxxxx#img01 - 99
    add(textLabel);
    intro = true;
    load.start();
    public void actionPerformed(ActionEvent evt) { // timer listner
    if (evt.getSource() == load) { // first timer only ones for first picture
    // second timer for image duration
    load.stop();
    timer.start();
    intro=false;
    repaint();
    if (evt.getSource() == timer) {
    if (count == maxcount)
    count = 0;
    repaint();
    count++;
    void readImageFilelist(String dirname) { // gets the list of images
    directory = new File(dirname); // of folder imagestore
    if (directory.isDirectory() == false) { // in work directory
    if (directory.exists() == false)
    JOptionPane.showMessageDialog(infoPane,
    " there is no directory called " + directory);
    else
    JOptionPane.showMessageDialog(infoPane, directory +
    " is not a directory. ");
    else {
    picfilenames = directory.list(); // stores the list of file names
    for (int i = 0; i < picfilenames.length; i++) {
    if (imageNamecheck(picfilenames)) { // check correct file extension #img
    picfilenamesmaxcount = picfilenames; // eliminate the incorrect ones
    maxcount++;
    if (maxcount == 0)
    JOptionPane.showMessageDialog(infoPane,
    "no valid files present ");
    private boolean imageNamecheck(String st) {
    int pos = st.indexOf("#img");
    if (pos == -1)
    return false;
    else return true;
    private int imagePos(String st) {
    int posnmb=0; // convert string-number into int
    int pos = st.indexOf("#img"); // when no image present returns -1
    if (pos==-1) {
    JOptionPane.showMessageDialog(infoPane,
    "The file has�t the correct format #img01-#img99 ");
    return 0;
    else
    return pos+4;
    private void orderImages() { // sort de file list of images 00-99
    int lastarray = maxcount-1;
    int trynmb=0, maxnmb=0, index=0, pos=0;
    String tempfl="";
    while(lastarray != 0) {
    index = 0;
    pos = imagePos(picfilenames[0]);
    try { maxnmb = Integer.parseInt(picfilenames[0].substring(pos, pos+2));
    catch ( NumberFormatException e ) {
    JOptionPane.showMessageDialog(infoPane,
    "File format: #img01-#img99 " + e);
    for (int i = 1; i <= lastarray; i++) {
    pos = imagePos(picfilenames);
    try { trynmb = Integer.parseInt(picfilenames.substring(pos, pos+2));
    catch ( NumberFormatException e ) {
    JOptionPane.showMessageDialog(infoPane,
    "File format: #img01-#img99 " + e);
    if (trynmb>maxnmb) {
    maxnmb = trynmb;
    index=i;
    tempfl = picfilenameslastarray;
    picfilenameslastarray = picfilenamesindex;
    picfilenamesindex = tempfl;
    lastarray--;
    // for (int i = 0; i < maxcount; i++) {
    //JOptionPane.showMessageDialog(infoPane,
    // "last array " + i + " filename " + picfilenames);
    private Image scaleImage(BufferedImage bimg) { // scale buffered image into image fill
    try {
    imgwidth = bimg.getWidth(this);
    catch (Exception e) {
    JOptionPane.showMessageDialog(infoPane, "can not get image width " + e);
    try {
    imgheight = bimg.getHeight(this);
    catch (Exception e) {
    JOptionPane.showMessageDialog(infoPane, "can not get image height " + e);
    double scalerate = calcScale(imgwidth, imgheight); // calls the actual scaling method
    imgwidth = (int)(imgwidth * scalerate);
    imgheight = (int)(imgheight * scalerate);
    x = (int)(framew - imgwidth)/2;
    y = (int)(frameh - imgheight)/2;
    DecimalFormat myFormatter = new DecimalFormat("######.##");
    String xx = myFormatter.format(scalerate);
    String yy = myFormatter.format(scalerate);
    //JOptionPane.showMessageDialog(infoPane,
    // "image size " + imgwidth + " / " + imgheight + " new size " + newidth + " / " + newheight + " scalerate " + xx
    // + " insets " + insetw + " / " + inseth );
    try {
    Image img = bimg.getScaledInstance(imgwidth, imgheight, bimg.SCALE_FAST); // the actual scaling
    return img;
    catch (IllegalArgumentException e) {
    JOptionPane.showMessageDialog(infoPane, " can not scale the image " + bimg + " " + e);
    return null;
    private double calcScale(int imgwidth, int imgheight) {
    double sc=0, x=0;
    if ((double)framew-imgwidth < frameh-imgheight) { // gets the smallest side of the picture
    sc = (double)framew/imgwidth; // to scale to frame size (sc)
    else {
    sc = (double)frameh/imgheight;
    return sc;
    private Image downloadImage(String filename) { //downloads image and call the scaling
    BufferedImage bufimg=null;
    Image img=null;
    ClassLoader cl = Slides2.class.getClassLoader();
    URL imageURL = cl.getResource(filename);
    try {
    bufimg = ImageIO.read(imageURL);
    img=scaleImage(bufimg);
    catch (Exception e){
    JOptionPane.showMessageDialog(infoPane, " can not download " + filename + " " + e);
    return img;
    private void displayText(int cnt) {
    textLabel.setFont(new Font("Serif", Font.BOLD, 18));
    textLabel.setForeground(Color.RED);
    textLabel.setText("xcount maxcount " + count + " / " + maxcount);
    public void paintComponent(Graphics g) { // the timer calls the component
    // to draw the pictures
    if (intro) { // the first pic and its display time
    g.drawImage(firstpic,0, 0, imgwidth, imgheight, this);
    else {
    //g.drawImage(img, dest_x1, dest_y1, dest_x2, dest_y2,
    // source_x1, source_y1, source_x2, source_y2, imageObserver); x=width y=height
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, framew+10, frameh+10);
    g.drawImage(downloadImage(picfilenamescount),x, y, imgwidth, imgheight,this);
    //g.drawImage(firstpic,0, 0, imgwidth, imgheight, this);
    displayText(7);
    }

    If the application is expecting to find an inner class in the jar - then yes, it must be there.
    Put it in there and see what happens - it is probably needed there.

  • Adding inner class object

    Hello to all
    I have one doubt regarding eventhandling. Consider i am having one class named outer which extends applet and with in outer class i am having one class inner which extends panel.
    Now when i try to add the inner class object in action performed of outer
    class it doesnt get added. How to overcome this.
    Eventhough sometimes it gets added it shouldnot appear for the first time. After resizing the window only it gets displayed.
    How to over come this.
    This is my coding
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JApplet implements ActionListener{
         JButton b1;
         Container c;
         public void init()
              c=getContentPane();
              b1=new JButton("First");
              c.add(b1,BorderLayout.NORTH);
              b1.addActionListener(this);
         public void actionPerformed(ActionEvent ae)
              System.out.println("Working");
              c.add(new panel());
         class panel extends JPanel
              int a=5;
              JLabel l=new JLabel("ADSF");
              public panel()
                   add(new JButton("ASDFASDFs"));
                   add(l);
              /*public void paint(Graphics g)
                   g.drawString("ASDFASDF123123123123",20,20);
    }

    You could try being more specific when you add ie
    c.add(new panel(), BorderLayout.CENTER);

Maybe you are looking for

  • How to get reference of UI controls in a JSON Controller?

    Hi Experts, This time I was looking to create a JSON view and I was successful in creating and including various UI controls in the view. However, I am not able to get the reference of the UI controls within the controller. Initially, I thought using

  • Does Boot Camp 3.0  support read/write capabilities from Window's (NTFS) to OS X?

    Will I be able to just click My Computer and view my complete OS X partition while in Window's (as well as write to it)? Supposedly I can according to the KB article, but after hand installing every part of the 3.0 update (because Apple just loves it

  • SA TIMED OUT errors

    Hello! I'm getting the following "SA TIMED OUT" errors in my amavis.log file and would like to solve the problem. The time outs seem to causing delays in the processing of mail. I have upgraded clamav to use clamd as per Alex's tutorial at topicdesk.

  • Problem with a 2 columns Range Partitioning for a indexed organized table

    have an indexed organized table with a 2 column PK. the first field (datum) is a date field the second field (installatieid) is a number(2) field. Every minute a 7 records are inserted (installatieid 0-6). I like to partition this table with one part

  • Audio stops after 2 seconds

    Why does my background music stop playing after a couple of seconds? I just went to Mountain Lion (10.8.2) and iMovie 11.