473,395 Members | 1,468 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Help with Non-Static/Static problem

23
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 'ConvertToOunces' 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 2188
r035198x
13,262 8TB
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 ConvertToOuncesPane object which is not a Component as the second parameter and that won't compile.
Sep 5 '08 #2
JosAH
11,448 Expert 8TB
That ConvertToOuncesPane 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
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 Expert 8TB
Read the API documentation: the addTab method adds a tab which must be a
Component. Your ConvertToOuncesPane 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
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...
6
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...
3
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...
3
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...
14
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...
7
by: Naren | last post by:
Hello All, Can any one help me in this file read problem. #include <stdio.h> int main() {
3
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...
22
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...
0
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...
12
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...

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.