473,778 Members | 1,913 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with Non-Static/Static problem

23 New Member
I am having a compile-time problem with a simple program I am writing. When I attempt to compile, I get the error "non-static variable this cannot be referenced from a static context". The error point to where I try to create a new instance of 'ConvertToOunce s' inside the main method. Any help would be greatly appreciated.

Here is my source code.

Expand|Select|Wrap|Line Numbers
  1. /******************************************************************************\
  2. |
  3. |Try to make gui for both Projects 2a and 2b
  4. |
  5. |
  6. \******************************************************************************/
  7.  
  8.    import javax.swing.*;
  9.    import javax.swing.JOptionPane.*;
  10.    import java.awt.*;
  11.    import java.awt.event.*;
  12.  
  13.     public class WeightConverter extends JPanel{
  14.  
  15.           //main method will instantiate and display GUI
  16.  
  17.        public static void main(String[] args){
  18.  
  19.          JFrame frame = new JFrame("Weight Converter");
  20.          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  21.  
  22.          JTabbedPane pane = new JTabbedPane();
  23.          pane.addTab ("Convert To Ounces", new ConvertToOuncesPane());
  24.  
  25.       }
  26.       //ConvertToOuncesPane class will create the pane for converting to ounces. 
  27.        class ConvertToOuncesPane{
  28.  
  29.           //Set up new component identifiers
  30.          JLabel tonsLabel, stonesLabel, poundsLabel, ouncesLabel, resultLabel;
  31.          JTextField tonsField, stonesField, poundsField, ouncesField;
  32.          JButton btnConvert, btnClear, btnExit;
  33.          String resultString = "Total Number of Ounces: ";
  34.  
  35.           /*****************************************************************************\
  36.           |
  37.           |this method will be the primary constructor method for the class
  38.           |
  39.           \*****************************************************************************/
  40.           public ConvertToOuncesPane(){
  41.  
  42.              //set up the labels for the input boxes
  43.             tonsLabel = new JLabel("Enter number of tons:");
  44.             stonesLabel = new JLabel("Enter number of stones:");
  45.             poundsLabel = new JLabel("Enter number of pounds:");
  46.             ouncesLabel = new JLabel("Enter number of pounds:");
  47.             resultLabel = new JLabel(resultString + "---");
  48.  
  49.              //set up the input boxes
  50.             tonsField = new JTextField(10);
  51.             stonesField = new JTextField(10);
  52.             poundsField = new JTextField(10);
  53.             ouncesField = new JTextField(10);
  54.  
  55.              //set up the convert button and add action listener
  56.             btnConvert = new JButton("Convert");
  57.             btnConvert.addActionListener (new ConvertToListener());
  58.  
  59.              //set up the clear button and add action listener
  60.             btnClear = new JButton("Clear");
  61.             btnClear.addActionListener (new ClearToListener());
  62.  
  63.              //set up the exit button and add action listener
  64.             btnExit = new JButton("Exit");
  65.             btnExit.addActionListener (new ExitToListener());
  66.  
  67.              //add components to the pane
  68.             add (tonsLabel);
  69.             add (tonsField);
  70.             add (stonesLabel);
  71.             add (stonesField);
  72.             add (poundsLabel);
  73.             add (poundsField);
  74.             add (ouncesLabel);
  75.             add (ouncesField);
  76.             add (resultLabel);
  77.             add (btnConvert);
  78.             add (btnClear);
  79.             add (btnExit);
  80.  
  81.              //set default values for textFields
  82.             tonsField.setText("0");
  83.             stonesField.setText("0");
  84.             poundsField.setText("0");
  85.             ouncesField.setText("0");
  86.  
  87.              //set up the look of the pane
  88.             setBackground(Color.white);
  89.             setPreferredSize(new Dimension(200, 280));
  90.  
  91.  
  92.  
  93.          }
  94.  
  95.         /**********************************************************************\
  96.         |
  97.         |the ConvertToListener class is dedicated to the convert button 
  98.         |on the Convert To Ounces Pane
  99.         |
  100.         \**********************************************************************/ 
  101.           private class ConvertToListener implements ActionListener{
  102.  
  103.              public void actionPerformed(ActionEvent event){
  104.  
  105.                 //set up variables for the ConvertListener class
  106.                int tons = 0, stones = 0, pounds = 0, ounces = 0, totalOunces = 0;
  107.                final int CONVERT_TONS = 32000, CONVERT_STONES = 224, CONVERT_POUNDS = 16;
  108.                String errorMessage = "You must enter a number.";
  109.                boolean testField;
  110.  
  111.                 //collect, test, and parse integers from each textField
  112.                    //test tonsField
  113.                testField = testInt(tonsField.getText());
  114.  
  115.                if (testField == true)
  116.                   tons = Integer.parseInt(tonsField.getText());
  117.                else
  118.                   JOptionPane.showMessageDialog(null, errorMessage);
  119.  
  120.                     //test stonesField
  121.                testField = testInt(stonesField.getText());
  122.  
  123.                if (testField == true)
  124.                   stones = Integer.parseInt(stonesField.getText());
  125.                else
  126.                   JOptionPane.showMessageDialog(null, errorMessage);
  127.  
  128.                     //test poundsField
  129.                testField = testInt(poundsField.getText());
  130.  
  131.                if (testField == true)
  132.                   pounds = Integer.parseInt(poundsField.getText());
  133.                else
  134.                   JOptionPane.showMessageDialog(null, errorMessage);
  135.  
  136.                     //test ouncesField
  137.                testField = testInt(ouncesField.getText());
  138.  
  139.                if (testField == true)
  140.                   ounces = Integer.parseInt(ouncesField.getText());
  141.                else
  142.                   JOptionPane.showMessageDialog(null, errorMessage);
  143.  
  144.                 //perform the conversion calculation
  145.                totalOunces = tons * CONVERT_TONS + stones * CONVERT_STONES + pounds * CONVERT_POUNDS + ounces;
  146.  
  147.                 //display the result
  148.                resultLabel.setText(resultString + totalOunces);    
  149.             }
  150.  
  151.              //set up a try-catch in the event a letter is entered into a field
  152.              boolean testInt(String test){
  153.                try{
  154.                   Integer.parseInt(test);
  155.                }
  156.                    catch(NumberFormatException exception){
  157.                      return false;
  158.                   }
  159.                return true;
  160.             }
  161.  
  162.  
  163.  
  164.  
  165.          }
  166.          /***************************************************************************\
  167.           |
  168.           |the ClearToListener class is dedicated to the Clear button on 
  169.           |the Convert To Ounces Pane
  170.           |
  171.           \***************************************************************************/
  172.           private class ClearToListener implements ActionListener{
  173.  
  174.               /****************************************************************\
  175.               |
  176.               |this method will restore the default zeros to all text fields
  177.               |
  178.               \****************************************************************/
  179.              public void actionPerformed(ActionEvent event){
  180.                  //restore default values to textFields
  181.                tonsField.setText("0");
  182.                stonesField.setText("0");
  183.                poundsField.setText("0");
  184.                ouncesField.setText("0");
  185.  
  186.             }
  187.          }
  188.          /*******************************************************************************\
  189.           |
  190.           |the ExitToListener class is dedicated to the Exit button on the
  191.           |Convert To Ounces Pane
  192.           |
  193.           \*******************************************************************************/
  194.  
  195.           private class ExitToListener implements ActionListener{
  196.              /***********************************************************\
  197.              |
  198.              |this method will end the program when the user 
  199.              |clicks the exit button
  200.              |
  201.              \***********************************************************/    
  202.              public void actionPerformed(ActionEvent event){
  203.                System.exit(0);
  204.             }
  205.          }
  206.  
  207.       }
  208.  
  209.  
  210.  
  211.  
  212.    }
  213.  
Sep 5 '08 #1
4 2216
r035198x
13,262 MVP
That can't be the error you are getting now with that code. You haven't used this at all in that main method. Your call to addTab however is incorrect. The closest overload for that method takes a String and a Component. You are passing a string as the first parameter (correct) but passing a ConvertToOunces Pane object which is not a Component as the second parameter and that won't compile.
Sep 5 '08 #2
JosAH
11,448 Recognized Expert MVP
That ConvertToOunces Pane is an inner class. Objects of inner class types are
tied to an object of the outer class. You don't have an object of the outer class
so you can't instantiate (new) an object of that inner class in your main method
which runs in a static context (read: no object(s) in scope).

You either make an object of the outer class or make that inner class a static
class, a so called static nested class.

kind regards,

Jos
Sep 5 '08 #3
HxRLxY
23 New Member
Thank you for the help so far. I changed my inner class to be a static class and all seems well, except that in my main method where i try 'pane.addTab' i get a cannot find symbol error. My text book shows that i have the syntax right, but I still can't get it to work.

Here is my revised source code:

Expand|Select|Wrap|Line Numbers
  1. import javax.swing.*;
  2.    import javax.swing.JOptionPane.*;
  3.    import javax.swing.JTabbedPane.*;
  4.    import java.awt.*;
  5.    import java.awt.event.*;
  6.  
  7.     public class WeightConverter extends JPanel{
  8.  
  9.           //main method will instantiate and display GUI
  10.  
  11.        public static void main(String[] args){
  12.  
  13.          JFrame frame = new JFrame("Weight Converter");
  14.          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15.  
  16.          JTabbedPane pane = new JTabbedPane();
  17.          ConvertToOuncesPane panel_1 = new ConvertToOuncesPane();
  18.  
  19.          pane.addTab("Convert", panel_1);
  20.  
  21.          frame.getContentPane().add(pane);
  22.          frame.pack();
  23.          frame.setVisible(true);
  24.       }
  25.       //ConvertToOuncesPane class will create the pane for converting to ounces. 
  26.        static class ConvertToOuncesPane{
  27.  
  28.           //Set up new component identifiers
  29.          JLabel tonsLabel, stonesLabel, poundsLabel, ouncesLabel, resultLabel;
  30.          JTextField tonsField, stonesField, poundsField, ouncesField;
  31.          JButton btnConvert, btnClear, btnExit;
  32.          String resultString = "Total Number of Ounces: ";
  33.  
  34.           /*****************************************************************************\
  35.           |
  36.           |this method will be the primary constructor method for the class
  37.           |
  38.           \*****************************************************************************/
  39.           public ConvertToOuncesPane(){
  40.  
  41.              //set up the labels for the input boxes
  42.             tonsLabel = new JLabel("Enter number of tons:");
  43.             stonesLabel = new JLabel("Enter number of stones:");
  44.             poundsLabel = new JLabel("Enter number of pounds:");
  45.             ouncesLabel = new JLabel("Enter number of pounds:");
  46.             resultLabel = new JLabel(resultString + "---");
  47.  
  48.              //set up the input boxes
  49.             tonsField = new JTextField(10);
  50.             stonesField = new JTextField(10);
  51.             poundsField = new JTextField(10);
  52.             ouncesField = new JTextField(10);
  53.  
  54.              //set up the convert button and add action listener
  55.             btnConvert = new JButton("Convert");
  56.             btnConvert.addActionListener (new ConvertToListener());
  57.  
  58.              //set up the clear button and add action listener
  59.             btnClear = new JButton("Clear");
  60.             btnClear.addActionListener (new ClearToListener());
  61.  
  62.              //set up the exit button and add action listener
  63.             btnExit = new JButton("Exit");
  64.             btnExit.addActionListener (new ExitToListener());
  65.  
  66.              //add components to the pane
  67.             JFrame frame = new JFrame();
  68.             frame.add (tonsLabel);
  69.             frame.add (tonsField);
  70.             frame.add (stonesLabel);
  71.             frame.add (stonesField);
  72.             frame.add (poundsLabel);
  73.             frame.add (poundsField);
  74.             frame.add (ouncesLabel);
  75.             frame.add (ouncesField);
  76.             frame.add (resultLabel);
  77.             frame.add (btnConvert);
  78.             frame.add (btnClear);
  79.             frame.add (btnExit);
  80.  
  81.              //set default values for textFields
  82.             tonsField.setText("0");
  83.             stonesField.setText("0");
  84.             poundsField.setText("0");
  85.             ouncesField.setText("0");
  86.  
  87.              //set up the look of the pane
  88.             frame.setBackground(Color.white);
  89.             frame.setPreferredSize(new Dimension(200, 280));
  90.  
  91.  
  92.  
  93.          }
  94.  
  95.         /**********************************************************************\
  96.         |
  97.         |the ConvertToListener class is dedicated to the convert button 
  98.         |on the Convert To Ounces Pane
  99.         |
  100.         \**********************************************************************/ 
  101.           private class ConvertToListener implements ActionListener{
  102.  
  103.              public void actionPerformed(ActionEvent event){
  104.  
  105.                 //set up variables for the ConvertListener class
  106.                int tons = 0, stones = 0, pounds = 0, ounces = 0, totalOunces = 0;
  107.                final int CONVERT_TONS = 32000, CONVERT_STONES = 224, CONVERT_POUNDS = 16;
  108.                String errorMessage = "You must enter a number.";
  109.                boolean testField;
  110.  
  111.                 //collect, test, and parse integers from each textField
  112.                    //test tonsField
  113.                testField = testInt(tonsField.getText());
  114.  
  115.                if (testField == true)
  116.                   tons = Integer.parseInt(tonsField.getText());
  117.                else
  118.                   JOptionPane.showMessageDialog(null, errorMessage);
  119.  
  120.                     //test stonesField
  121.                testField = testInt(stonesField.getText());
  122.  
  123.                if (testField == true)
  124.                   stones = Integer.parseInt(stonesField.getText());
  125.                else
  126.                   JOptionPane.showMessageDialog(null, errorMessage);
  127.  
  128.                     //test poundsField
  129.                testField = testInt(poundsField.getText());
  130.  
  131.                if (testField == true)
  132.                   pounds = Integer.parseInt(poundsField.getText());
  133.                else
  134.                   JOptionPane.showMessageDialog(null, errorMessage);
  135.  
  136.                     //test ouncesField
  137.                testField = testInt(ouncesField.getText());
  138.  
  139.                if (testField == true)
  140.                   ounces = Integer.parseInt(ouncesField.getText());
  141.                else
  142.                   JOptionPane.showMessageDialog(null, errorMessage);
  143.  
  144.                 //perform the conversion calculation
  145.                totalOunces = tons * CONVERT_TONS + stones * CONVERT_STONES + pounds * CONVERT_POUNDS + ounces;
  146.  
  147.                 //display the result
  148.                resultLabel.setText(resultString + totalOunces);    
  149.             }
  150.  
  151.              //set up a try-catch in the event a letter is entered into a field
  152.              boolean testInt(String test){
  153.                try{
  154.                   Integer.parseInt(test);
  155.                }
  156.                    catch(NumberFormatException exception){
  157.                      return false;
  158.                   }
  159.                return true;
  160.             }
  161.  
  162.  
  163.  
  164.  
  165.          }
  166.          /***************************************************************************\
  167.           |
  168.           |the ClearToListener class is dedicated to the Clear button on 
  169.           |the Convert To Ounces Pane
  170.           |
  171.           \***************************************************************************/
  172.           private class ClearToListener implements ActionListener{
  173.  
  174.               /****************************************************************\
  175.               |
  176.               |this method will restore the default zeros to all text fields
  177.               |
  178.               \****************************************************************/
  179.              public void actionPerformed(ActionEvent event){
  180.                  //restore default values to textFields
  181.                tonsField.setText("0");
  182.                stonesField.setText("0");
  183.                poundsField.setText("0");
  184.                ouncesField.setText("0");
  185.  
  186.             }
  187.          }
  188.          /*******************************************************************************\
  189.           |
  190.           |the ExitToListener class is dedicated to the Exit button on the
  191.           |Convert To Ounces Pane
  192.           |
  193.           \*******************************************************************************/
  194.  
  195.           private class ExitToListener implements ActionListener{
  196.              /***********************************************************\
  197.              |
  198.              |this method will end the program when the user 
  199.              |clicks the exit button
  200.              |
  201.              \***********************************************************/    
  202.              public void actionPerformed(ActionEvent event){
  203.                System.exit(0);
  204.             }
  205.          }
  206.  
  207.       }
  208.  
  209.  
  210.  
  211.  
  212.    }
  213.  
Sep 5 '08 #4
JosAH
11,448 Recognized Expert MVP
Read the API documentation: the addTab method adds a tab which must be a
Component. Your ConvertToOunces Pane class isn't a Component.

kind regards,

Jos
Sep 5 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

2
3078
by: D. Roshani | last post by:
Hello ! I wonder if any one can help me to create a cosomize sorting order (as Macro or added small program in c++ or c# which does this work) in a Access Database contaning one table only words encoded in ISO-8859-1 A a B b C c D d E e É é F f G g H h I i Í í J j 1 2 3 4 5 6 7 8 9 10 11 12 Jh jh K k L l ll M m N n O o P p Q q R r rr S s...
6
4351
by: wukexin | last post by:
Help me, good men. I find mang books that introduce bit "mang header files",they talk too bit,in fact it is my too fool, I don't learn it, I have do a test program, but I have no correct doing result in any way. Who can help me, I thank you very very much. list.cpp(main program) //-------------------------------------------------------------------------- - #pragma hdrstop #pragma argsused
3
2980
by: Mahmood Ahmad | last post by:
Hello, I have written a program that reads three types of records, validates them acording to certain requirements and writes the valid records into a binary file. The invalid records are supposed to be reported on the printer but I have commented those pieces of code and have got those records printed on the screen. I am using Microsoft Visual C++ 6.0 on Microsoft XP (Home) platform. I am facing some problems in getting desire...
3
2672
by: Drewdog | last post by:
I am getting some error messages which I can't figure out their meaning. I have the code setup, I think it's correct but it doesn't work. My goal is to get this program to read from a data file and basically put it into an output file that I can access as a test file. Here is my header file: #include <iostream.h> #include <fstream.h> #include <iomanip.h>
14
4761
by: Protoman | last post by:
Hi!!! I need some help on a project I'm that calculates leap years; I'm getting errors that I have no idea what they mean; here's the code: #include <iostream> #include <cstdlib> using namespace std; class Year { public:
7
2265
by: Naren | last post by:
Hello All, Can any one help me in this file read problem. #include <stdio.h> int main() {
3
2566
by: Zach | last post by:
Hello, Please forgive if this is not the most appropriate newsgroup for this question. Unfortunately I didn't find a newsgroup specific to regular expressions. I have the following regular expression. ^(.+?) uses (?!a spoon)\.$
22
3278
by: Amali | last post by:
I'm newdie in c programming. this is my first project in programming. I have to write a program for a airline reservation. this is what i have done yet. but when it runs it shows the number of seats as 0 and the flight no. is also repeating. If any can tell why is this please help me. #include<stdio.h> #include<ctype.h> #include<conio.h>
0
1434
by: tomwolfstein | last post by:
Hi. I am trying to write a wrapper for the standard VC1 decoder, and I need to resolve a "TypeLoadException" The decoder comes an an executable which I've turned into a .dll. This decoder has about a ton of structures, most of the containing other structures, arrays of structures, and unions of structures. I need help converting the following to managed code: The unmanaged structure is this: typedef struct { vc1_eBlkType eBlkType; /**...
12
2700
by: Kira Yamato | last post by:
I've posted this in another thread, but I suppose I should've started a new thread for it instead. I cannot get the following short program to compile under g++: #include <iostream> #include <fstream> #include <iterator> #include <algorithm>
0
9629
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9465
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10127
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9923
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8954
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7474
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6723
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4031
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.