Static context Problem

i have following method called by cliking a button on an interface.
public void jButton1_mouseClicked(MouseEvent e)
Writen.write(jTextField1);
the method write in class written gives following error here i.e.
"Frame1.java": non-static method write(javax.swing.JTextField) cannot be referenced from a static context at line 62, column 18
could some one tell me where is static context

public void jButton1_mouseClicked(MouseEvent e)
Writen.write(jTextField1);
}Writen is a class, I presume. You are trying to access a method (write) by using the class name instead of an instance of the class. If the write method is not static in Writen, you must create an object of the class and call the methods using that.

Similar Messages

  • RMI: problem with static context

    I'm trying to do my first RMI application. I have a strange problem. That is I get an error says:
    "non-static method authenticate(String userid, String password) cannot be referenced from a static context". The problem is that the context that I call the method is not static. here is the code that I've implementet (or lets say: trying to implement).
         public Session getSession(String userid, String password) {
              Session     session = null;;
              boolean authenticated     = UserManager.authenticate(userid, password);
              if( authenticated ){
                   try{
                        session = new Session();
                        session.setSessionId(s_next_session_id);
                   }catch(java.rmi.RemoteException e){
                        e.printStackTrace();
                        System.err.println(e.toString());
              } else {
                   // throw Exception();
              return (session);
    What am I missing here. The context (getSession()) is not static, neither is my method in UserManager. What is wrong? Can anybody help me.
    Thanks in advance.

    ignore this. I solve the problem

  • Help ! Problem with static context"

    What does it means ? "non-static variable this cannot be referenced from a static context"
    Error on NEW...
    import java.util.*;
    public class Test {
    public static void main (String[] args) {
    Reponse r = new Reponse ();
    r.demander ();
    System.out.println (r.getBP () + " " + r.getMP ());
    class Reponse {
    public void demander () {
    public int getBP () {
    return (nbBP);
    public int getMP () {
    return (nbMP);
    private int nbBP, nbMP;
    }

    georgemc wrote:
    phdk wrote:
    tsith wrote:
    phdk wrote:
    Why is your Reponse class not public?Because that would cause a compiler error?Thanks tsith!
    Maybe I misunderstand your reply.
    I am sure you had no idea what I meant. I'll try to make it clear.
    Is there any reason why it is defined as an inner class?It's not an inner class, it's a top-level class, hence tsith's responseActually, it is defined as an inner class, but the lack of code formatting makes this hard to see:
    import java.util.*;
    public class Test {
        public static void main (String[] args) {
            Reponse r = new Reponse ();
            r.demander ();
            System.out.println (r.getBP () + " " + r.getMP ());
        class Reponse {
            public void demander () {
            public int getBP () {
                return (nbBP);
            public int getMP () {
                return (nbMP);
            private int nbBP, nbMP;
    }Why an inner class? My guess is that the OP doesn't know what he is doing.

  • The Good Old Static Reference Problem

    Hey All,
    I know you are probabely all sick of this question but non-static variable RobotServerStatusConditionLabel cannot be referenced from a static context
    I dont know how to go about fixing this problem, i have read the other feeds on this and more or less understood why the error is happening but cant think of a way to solve it. I am developing a GUI progam in Netbeans The code is shown below.
    The prolem i am having is that i have a thread called ModuleThreadRobot which is in a class called final class ModuleThreadRobot. I need to be able to access the variables in the GUI so that i can update them for the user so for example i want to change the text of a label in the gui:
    LabANTServerProxyGUI.RobotServerStatusConditionLabel.setText("wagamma!!");
    And the error i get is as follows:
    non-static variable RobotServerStatusConditionLabel cannot be referenced from a static context
    So if anyone can help me out here, i more or less get why its happening just don't know a way around it.
    Thanks inadvance,
    Richard
    * LabANTServerProxyGUI.java
    * Created on 26 December 2005, 07:58
    package LabANTServerProxy;
    * @author  Yap
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    public class LabANTServerProxyGUI extends javax.swing.JFrame {
        /** Creates new form LabANTServerProxyGUI */
        public LabANTServerProxyGUI() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            LabANTTabbedPane = new javax.swing.JTabbedPane();
            LabANTSplashPanel = new javax.swing.JPanel();
            Title = new javax.swing.JLabel();
            Author = new javax.swing.JLabel();
            UniversityMark = new javax.swing.JTextArea();
            Copyright = new javax.swing.JTextArea();
            PicturePanel = new javax.swing.JPanel();
            jLabel2 = new javax.swing.JLabel();
            EmailLabel = new javax.swing.JLabel();
            WebAddressLabel = new javax.swing.JLabel();
            ServerControlPanel = new javax.swing.JPanel();
            StepOnePanel = new javax.swing.JPanel();
            RobotServerSettingsPanel = new javax.swing.JPanel();
            ServerIPAddressLabel = new javax.swing.JLabel();
            ServerIPAddressTextField = new javax.swing.JTextField();
            ServerPortLabel = new javax.swing.JLabel();
            ServerPortTextField = new javax.swing.JTextField();
            RobotServerSettingsTextArea = new javax.swing.JTextArea();
            StatusLabel = new javax.swing.JLabel();
            RobotServerStatusConditionLabel = new javax.swing.JLabel();
            RobotServerSettingsConnectButton = new javax.swing.JButton();
            StepTwoPanel = new javax.swing.JPanel();
            DatabaseSettingsPanel = new javax.swing.JPanel();
            DatabaseIPAddressLabel = new javax.swing.JLabel();
            DatabasePortLabel = new javax.swing.JLabel();
            DatabaseIPTextField = new javax.swing.JTextField();
            DatabasePortTextField = new javax.swing.JTextField();
            DatabaseSettingsTextArea = new javax.swing.JTextArea();
            UsernameLabel = new javax.swing.JLabel();
            PasswordLabel = new javax.swing.JLabel();
            UsernameTextField = new javax.swing.JTextField();
            PasswordTextField = new javax.swing.JPasswordField();
            DatabaseSaveButton = new javax.swing.JButton();
            TestStatusPanel = new javax.swing.JPanel();
            TestStatusConditionLabel = new javax.swing.JLabel();
            DatabaseTestButton = new javax.swing.JButton();
            StepThreePanel = new javax.swing.JPanel();
            ServerStatus = new javax.swing.JPanel();
            LabANTServerPortLabel = new javax.swing.JLabel();
            LabANTServerPortTextField = new javax.swing.JTextField();
            ServerStatusTextArea = new javax.swing.JTextArea();
            StartServerButton = new javax.swing.JButton();
            ServerMonitorPane = new javax.swing.JPanel();
            SensorDataScrollPane = new javax.swing.JScrollPane();
            SensorDataTextArea = new javax.swing.JTextArea();
            CommandDataScrollPane = new javax.swing.JScrollPane();
            CommandDataTextArea = new javax.swing.JTextArea();
            ServerMonitorNoteLabel = new javax.swing.JLabel();
            ClientDataPane = new javax.swing.JPanel();
            ClientIPAddressLabel = new javax.swing.JLabel();
            ClientIPAddressConditionLabel = new javax.swing.JLabel();
            LogsPanel = new javax.swing.JPanel();
            LogsTextArea = new javax.swing.JTextArea();
            HelpPanel = new javax.swing.JPanel();
            HelpScrollPane = new javax.swing.JScrollPane();
            HelpTextArea = new javax.swing.JTextArea();
            jPanel5 = new javax.swing.JPanel();
            AboutScrollPane = new javax.swing.JScrollPane();
            AboutTextArea = new javax.swing.JTextArea();
            getContentPane().setLayout(null);
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            LabANTTabbedPane.setFont(new java.awt.Font("Tahoma", 1, 11));
            LabANTSplashPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            LabANTSplashPanel.setFont(new java.awt.Font("MS Sans Serif", 1, 11));
            Title.setFont(new java.awt.Font("Tahoma", 1, 36));
            Title.setText("LabANT Version 1.0");
            LabANTSplashPanel.add(Title, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 20, -1, -1));
            Author.setFont(new java.awt.Font("Tahoma", 0, 18));
            Author.setText("Author: Richard McElligott ");
            LabANTSplashPanel.add(Author, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 60, -1, -1));
            UniversityMark.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
            UniversityMark.setFont(new java.awt.Font("Tahoma", 0, 12));
            UniversityMark.setText("The University of Reading\nActive Robotics Laboratory");
            LabANTSplashPanel.add(UniversityMark, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 440, -1, -1));
            Copyright.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
            Copyright.setFont(new java.awt.Font("Tahoma", 0, 12));
            Copyright.setText("Copyright Richard McElligott");
            LabANTSplashPanel.add(Copyright, new org.netbeans.lib.awtextra.AbsoluteConstraints(710, 470, -1, -1));
            PicturePanel.setLayout(null);
            PicturePanel.setBorder(new javax.swing.border.TitledBorder("Picutre"));
            jLabel2.setIcon(new javax.swing.ImageIcon("C:\\Documents and Settings\\Yap\\My Documents\\My Pictures\\leafcutterant1.jpg"));
            PicturePanel.add(jLabel2);
            jLabel2.setBounds(10, 20, 800, 300);
            LabANTSplashPanel.add(PicturePanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 90, 820, 340));
            EmailLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            EmailLabel.setText("[email protected]");
            LabANTSplashPanel.add(EmailLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(710, 450, -1, -1));
            WebAddressLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            WebAddressLabel.setText("www.arl.reading.ac.uk");
            LabANTSplashPanel.add(WebAddressLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 470, -1, -1));
            LabANTTabbedPane.addTab("LabANT", LabANTSplashPanel);
            ServerControlPanel.setLayout(null);
            ServerControlPanel.setMinimumSize(new java.awt.Dimension(861, 485));
            ServerControlPanel.setPreferredSize(new java.awt.Dimension(861, 485));
            StepOnePanel.setLayout(null);
            StepOnePanel.setBorder(new javax.swing.border.TitledBorder(null, "Step One", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            RobotServerSettingsPanel.setLayout(null);
            RobotServerSettingsPanel.setBorder(new javax.swing.border.TitledBorder(null, "Robot Server Settings", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            ServerIPAddressLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            ServerIPAddressLabel.setText("Server IP Address:");
            RobotServerSettingsPanel.add(ServerIPAddressLabel);
            ServerIPAddressLabel.setBounds(30, 20, 100, 14);
            ServerIPAddressTextField.setFont(new java.awt.Font("Tahoma", 0, 11));
            ServerIPAddressTextField.setText("127.0.0.1");
            RobotServerSettingsPanel.add(ServerIPAddressTextField);
            ServerIPAddressTextField.setBounds(30, 40, 180, 14);
            ServerPortLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            ServerPortLabel.setText("Server Port:");
            RobotServerSettingsPanel.add(ServerPortLabel);
            ServerPortLabel.setBounds(30, 60, 70, 14);
            ServerPortTextField.setFont(new java.awt.Font("Tahoma", 0, 11));
            ServerPortTextField.setText("4444");
            RobotServerSettingsPanel.add(ServerPortTextField);
            ServerPortTextField.setBounds(30, 80, 50, 14);
            RobotServerSettingsTextArea.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
            RobotServerSettingsTextArea.setFont(new java.awt.Font("Tahoma", 0, 12));
            RobotServerSettingsTextArea.setLineWrap(true);
            RobotServerSettingsTextArea.setText("Please supply the settings to connect to the robots wireless rs232 to tcp/ip module. This module recieves a wireless RS232 signal via a transiever on board the robot and one on the modlue and sends this data to a small embeded server to which you must connect. To connect you need to supply the IP Address and Port Number of the module. The Default is IP Address is 127.0.0.1 and Port Number is 4444. The MAC address of the module is:  00-33-44-55-55-66\n");
            RobotServerSettingsTextArea.setWrapStyleWord(true);
            RobotServerSettingsPanel.add(RobotServerSettingsTextArea);
            RobotServerSettingsTextArea.setBounds(390, 20, 440, 110);
            StatusLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
            StatusLabel.setText("Status:");
            RobotServerSettingsPanel.add(StatusLabel);
            StatusLabel.setBounds(30, 110, 50, 14);
            RobotServerStatusConditionLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            RobotServerStatusConditionLabel.setText("Disconnected");
            RobotServerSettingsPanel.add(RobotServerStatusConditionLabel);
            RobotServerStatusConditionLabel.setBounds(80, 110, 290, 14);
            RobotServerSettingsConnectButton.setFont(new java.awt.Font("Tahoma", 1, 11));
            RobotServerSettingsConnectButton.setText("Connect");
            RobotServerSettingsConnectButton.setBorder(new javax.swing.border.EtchedBorder());
            RobotServerSettingsConnectButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    RobotServerSettingsConnectButtonActionPerformed(evt);
            RobotServerSettingsConnectButton.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    RobotServerSettingsConnectButtonMouseReleased(evt);
            RobotServerSettingsPanel.add(RobotServerSettingsConnectButton);
            RobotServerSettingsConnectButton.setBounds(140, 70, 80, 30);
            StepOnePanel.add(RobotServerSettingsPanel);
            RobotServerSettingsPanel.setBounds(10, 20, 850, 140);
            ServerControlPanel.add(StepOnePanel);
            StepOnePanel.setBounds(0, 0, 870, 170);
            StepTwoPanel.setLayout(null);
            StepTwoPanel.setBorder(new javax.swing.border.TitledBorder(null, "Step Two", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            DatabaseSettingsPanel.setLayout(null);
            DatabaseSettingsPanel.setBorder(new javax.swing.border.TitledBorder(null, "Database Settings", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            DatabaseIPAddressLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            DatabaseIPAddressLabel.setText("Database IP Address:");
            DatabaseSettingsPanel.add(DatabaseIPAddressLabel);
            DatabaseIPAddressLabel.setBounds(30, 30, 110, 14);
            DatabasePortLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            DatabasePortLabel.setText("Database Port:");
            DatabaseSettingsPanel.add(DatabasePortLabel);
            DatabasePortLabel.setBounds(30, 70, 80, 14);
            DatabaseIPTextField.setFont(new java.awt.Font("Tahoma", 0, 11));
            DatabaseIPTextField.setText("127.0.0.1");
            DatabaseSettingsPanel.add(DatabaseIPTextField);
            DatabaseIPTextField.setBounds(30, 50, 170, 14);
            DatabasePortTextField.setFont(new java.awt.Font("Tahoma", 0, 11));
            DatabasePortTextField.setText("4443");
            DatabaseSettingsPanel.add(DatabasePortTextField);
            DatabasePortTextField.setBounds(30, 90, 70, 14);
            DatabaseSettingsTextArea.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
            DatabaseSettingsTextArea.setFont(new java.awt.Font("Tahoma", 0, 12));
            DatabaseSettingsTextArea.setLineWrap(true);
            DatabaseSettingsTextArea.setText("Supply settings to connect to the database, which is used for authenthicating clients and checking timetable. You must save before pressing test.");
            DatabaseSettingsTextArea.setWrapStyleWord(true);
            DatabaseSettingsPanel.add(DatabaseSettingsTextArea);
            DatabaseSettingsTextArea.setBounds(630, 20, 210, 90);
            UsernameLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            UsernameLabel.setText("Username:");
            DatabaseSettingsPanel.add(UsernameLabel);
            UsernameLabel.setBounds(250, 30, 60, 14);
            PasswordLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            PasswordLabel.setText("Password: ");
            DatabaseSettingsPanel.add(PasswordLabel);
            PasswordLabel.setBounds(250, 70, 60, 14);
            UsernameTextField.setFont(new java.awt.Font("Tahoma", 0, 11));
            UsernameTextField.setText("Enter Your Username");
            DatabaseSettingsPanel.add(UsernameTextField);
            UsernameTextField.setBounds(250, 50, 170, 14);
            DatabaseSettingsPanel.add(PasswordTextField);
            PasswordTextField.setBounds(250, 90, 170, 17);
            DatabaseSaveButton.setFont(new java.awt.Font("Tahoma", 1, 11));
            DatabaseSaveButton.setText("Save");
            DatabaseSaveButton.setBorder(new javax.swing.border.EtchedBorder());
            DatabaseSettingsPanel.add(DatabaseSaveButton);
            DatabaseSaveButton.setBounds(440, 20, 70, 30);
            TestStatusPanel.setLayout(null);
            TestStatusPanel.setBorder(new javax.swing.border.TitledBorder("Test Status"));
            TestStatusConditionLabel.setText("Disconnected");
            TestStatusPanel.add(TestStatusConditionLabel);
            TestStatusConditionLabel.setBounds(40, 20, 70, 15);
            DatabaseSettingsPanel.add(TestStatusPanel);
            TestStatusPanel.setBounds(440, 60, 150, 50);
            DatabaseTestButton.setFont(new java.awt.Font("Tahoma", 1, 11));
            DatabaseTestButton.setText("Test");
            DatabaseTestButton.setBorder(new javax.swing.border.EtchedBorder());
            DatabaseSettingsPanel.add(DatabaseTestButton);
            DatabaseTestButton.setBounds(520, 20, 70, 30);
            StepTwoPanel.add(DatabaseSettingsPanel);
            DatabaseSettingsPanel.setBounds(10, 20, 850, 130);
            ServerControlPanel.add(StepTwoPanel);
            StepTwoPanel.setBounds(0, 170, 870, 160);
            StepThreePanel.setLayout(null);
            StepThreePanel.setBorder(new javax.swing.border.TitledBorder(null, "Step Three", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            ServerStatus.setLayout(null);
            ServerStatus.setBorder(new javax.swing.border.TitledBorder(null, "Server Status:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            LabANTServerPortLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            LabANTServerPortLabel.setText("LabANT Server Port:");
            ServerStatus.add(LabANTServerPortLabel);
            LabANTServerPortLabel.setBounds(30, 40, 100, 14);
            LabANTServerPortTextField.setFont(new java.awt.Font("Tahoma", 0, 11));
            LabANTServerPortTextField.setText("5000");
            ServerStatus.add(LabANTServerPortTextField);
            LabANTServerPortTextField.setBounds(30, 60, 100, 14);
            ServerStatusTextArea.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
            ServerStatusTextArea.setFont(new java.awt.Font("Tahoma", 0, 12));
            ServerStatusTextArea.setLineWrap(true);
            ServerStatusTextArea.setText("Before starting the server ensure that you have sucessfully completed both step one and step two. Then please set the port number you whish the server to run on. Once the server is started clients can then connect to the server and log on and control the robot via the website client. \nServer Monitor will display live data and logs.\n");
            ServerStatusTextArea.setWrapStyleWord(true);
            ServerStatus.add(ServerStatusTextArea);
            ServerStatusTextArea.setBounds(230, 30, 580, 80);
            StartServerButton.setFont(new java.awt.Font("Tahoma", 1, 11));
            StartServerButton.setText("Start Server");
            StartServerButton.setBorder(new javax.swing.border.EtchedBorder());
            ServerStatus.add(StartServerButton);
            StartServerButton.setBounds(30, 90, 120, 30);
            StepThreePanel.add(ServerStatus);
            ServerStatus.setBounds(10, 20, 850, 130);
            ServerControlPanel.add(StepThreePanel);
            StepThreePanel.setBounds(0, 330, 870, 160);
            LabANTTabbedPane.addTab("Server Control", ServerControlPanel);
            ServerMonitorPane.setLayout(null);
            ServerMonitorPane.setBorder(new javax.swing.border.TitledBorder(null, "Server Monitor:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            SensorDataScrollPane.setBorder(new javax.swing.border.TitledBorder(null, "Sensor Data", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            SensorDataScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            SensorDataTextArea.setFont(new java.awt.Font("Tahoma", 0, 12));
            SensorDataTextArea.setLineWrap(true);
            SensorDataTextArea.setText("There once was a tree a very beautiful tree");
            SensorDataTextArea.setWrapStyleWord(true);
            SensorDataScrollPane.setViewportView(SensorDataTextArea);
            ServerMonitorPane.add(SensorDataScrollPane);
            SensorDataScrollPane.setBounds(10, 20, 470, 330);
            CommandDataScrollPane.setBorder(new javax.swing.border.TitledBorder(null, "Command Data From Client", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            CommandDataScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            CommandDataTextArea.setFont(new java.awt.Font("Tahoma", 0, 12));
            CommandDataTextArea.setLineWrap(true);
            CommandDataTextArea.setText("The only way is up ... you and me babe");
            CommandDataTextArea.setWrapStyleWord(true);
            CommandDataScrollPane.setViewportView(CommandDataTextArea);
            ServerMonitorPane.add(CommandDataScrollPane);
            CommandDataScrollPane.setBounds(490, 20, 380, 330);
            ServerMonitorNoteLabel.setFont(new java.awt.Font("Tahoma", 0, 11));
            ServerMonitorNoteLabel.setText("NOTE: Logs of both Sensor Data and Command Data along with users IP address are saved in log files for later analysis.");
            ServerMonitorPane.add(ServerMonitorNoteLabel);
            ServerMonitorNoteLabel.setBounds(130, 470, 590, 20);
            ClientDataPane.setLayout(null);
            ClientDataPane.setBorder(new javax.swing.border.TitledBorder(null, "Client Data:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            ClientIPAddressLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
            ClientIPAddressLabel.setText("Client IP Address:");
            ClientDataPane.add(ClientIPAddressLabel);
            ClientIPAddressLabel.setBounds(20, 20, 110, 20);
            ClientIPAddressConditionLabel.setFont(new java.awt.Font("Tahoma", 0, 12));
            ClientIPAddressConditionLabel.setText("Unknown");
            ClientDataPane.add(ClientIPAddressConditionLabel);
            ClientIPAddressConditionLabel.setBounds(130, 20, 70, 20);
            ServerMonitorPane.add(ClientDataPane);
            ClientDataPane.setBounds(10, 360, 230, 60);
            LogsPanel.setLayout(null);
            LogsPanel.setBorder(new javax.swing.border.TitledBorder(null, "Logs", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
            LogsTextArea.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
            LogsTextArea.setLineWrap(true);
            LogsTextArea.setText("The logs from Sensor Data, Command Data and Client Details are save in the following files sensor.log, command.log and client.log respectfully. They are saved in the same folder that the server is run in.");
            LogsTextArea.setWrapStyleWord(true);
            LogsPanel.add(LogsTextArea);
            LogsTextArea.setBounds(10, 20, 570, 60);
            ServerMonitorPane.add(LogsPanel);
            LogsPanel.setBounds(260, 370, 600, 90);
            LabANTTabbedPane.addTab("Server Monitor", ServerMonitorPane);
            HelpPanel.setLayout(null);
            HelpPanel.setBorder(new javax.swing.border.TitledBorder("Help"));
            HelpScrollPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            HelpScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            HelpTextArea.setLineWrap(true);
            HelpTextArea.setText("The standard Lorem Ipsum passage, used since the 1500s\n\n\"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n\nSection 1.10.32 of \"de Finibus Bonorum et Malorum\", written by Cicero in 45 BC\n\n\"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?\"\n\n1914 translation by H. Rackham\n\n\"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?\"\n\nSection 1.10.33 of \"de Finibus Bonorum et Malorum\", written by Cicero in 45 BC\n\n\"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.\"\n\n1914 translation by H. Rackham\n\n\"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.\" ");
            HelpTextArea.setWrapStyleWord(true);
            HelpScrollPane.setViewportView(HelpTextArea);
            HelpPanel.add(HelpScrollPane);
            HelpScrollPane.setBounds(50, 60, 770, 310);
            LabANTTabbedPane.addTab("Help", HelpPanel);
            jPanel5.setLayout(null);
            jPanel5.setBorder(new javax.swing.border.TitledBorder("About"));
            jPanel5.setMinimumSize(new java.awt.Dimension(861, 485));
            AboutScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            AboutScrollPane.setAutoscrolls(true);
            AboutScrollPane.setMinimumSize(new java.awt.Dimension(100, 340));
            AboutTextArea.setLineWrap(true);
            AboutTextArea.setText("The standard Lorem Ipsum passage, used since the 1500s\n\n\"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n\nSection 1.10.32 of \"de Finibus Bonorum et Malorum\", written by Cicero in 45 BC\n\n\"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?\"\n\n1914 translation by H. Rackham\n\n\"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          &nbs

    You got flack for not providing - in your own words - the solution to your own problem
    (from which someone might be able to see where you went wrong).
    Also, try not to "break" the forum formatting with those annoyingly long lines,
    see how nice it looks when refactored.
            AboutTextArea.setText("The standard Lorem Ipsum passage, used since the 1500s\n"+
                    "\n\"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor "+
                    "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud "+
                    "exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute "+
                    "irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. "+
                    "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit "+
                    "anim id est laborum.\"\n"+
                    "\nSection 1.10.32 of \"de Finibus Bonorum et Malorum\", written by Cicero in 45 BC\n"+
                    "\n\"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium "+
                    "doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore "+
                    "veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam "+
                    "voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur "+
                    "magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam "+
                    "est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non "+
                    "numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat "+
                    "voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam "+
                    "corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? "+
                    "Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil "+
                    "molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?\"\n"+
                    "\n1914 translation by H. Rackham\n\n\"But I must explain to you how all this mistaken "+
                    "idea of denouncing pleasure and praising pain was born and I will give you a complete "+
                    "account of the system, and expound the actual teachings of the great explorer of the "+
                    "truth, the master-builder of human happiness. No one rejects, dislikes, or avoids "+
                    "pleasure itself, because it is pleasure, but because those who do not know how to "+
                    "pursue pleasure rationally encounter consequences that are extremely painful. "+
                    "Nor again is there anyone who loves or pursues or desires to obtain pain of itself, "+
                    "because it is pain, but because occasionally circumstances occur in which toil and "+
                    "pain can procure him some great pleasure. To take a trivial example, which "+
                    "of us ever undertakes laborious physical exercise, except to obtain some advantage "+
                    "from it? But who has any right to find fault with a man who chooses to enjoy a pleasure "+
                    "that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?\"\n"+
                    "\nSection 1.10.33 of \"de Finibus Bonorum et Malorum\", written by Cicero in 45 BC\n"+
                    "\n\"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis "+
                    "praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias "+
                    "excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia "+
                    "deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum "+
                    "facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi "+
                    "optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, "+
                    "omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem "+
                    "quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et "+
                    "voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic "+
                    "tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur "+
                    "aut perferendis doloribus asperiores repellat.\"\n\n1914 translation by H. Rackham\n"+
                    "\n\"On the other hand, we denounce with righteous indignation and dislike men who "+
                    "are so beguiled and demoralized by the charms of pleasure of the moment, so "+
                    "blinded by desire, that they cannot foresee the pain and trouble that are bound to "+
                    "ensue; and equal blame belongs to those who fail in their duty through weakness "+
                    "of will, which is the same as saying through shrinking from toil and pain. These cases "+
                    "are perfectly simple and easy to distinguish. In a free hour, when our power of choice "+
                    "is untrammelled and when nothing prevents our being able to do what we like best, "+
                    "every pleasure is to be welcomed and every pain avoided. But in certain circumstances "+
                    "and owing to the claims of duty or the obligations of business it will frequently occur that "+
                    "pleasures have to be repudiated and annoyances accepted. The wise man therefore "+
                    "always holds in these matters to this principle of selection: he rejects pleasures to "+
                    "secure other greater pleasures, or else he endures pains to avoid worse pains.\" \n");

  • Non-static variable from a static context

    This is the error i get . If i understand the error correctly it says im using a static variable when i shouldnt be? Or is it the other way round? below the error is the actual code....
    The error...
    Googler.java:27: non-static variable this cannot be referenced from a static context
              submitButton.addActionListener(new ButtonHandler());The code...
              JButton submitButton = new JButton("Submit Query");
              submitButton.addActionListener(new ButtonHandler());

    thanks for the response.
    I have already tried what you said but I tried it again anyway and i get the same error more less...
    Googler.java:28: non-static variable this cannot be referenced from a static context
              ButtonHandler buttonHandler = new ButtonHandler();here is part of my code
    public class Googler
      static JTextField input1, input2;
         public static void main(String[] args)
              JFrame myFrame = new JFrame("Googler v1.0");
              Container c = myFrame.getContentPane();
              JLabel lab1 = new JLabel("Enter Google Query:");
              JLabel lab2 = new JLabel("Enter Unique API Key:");
              input1 = new JTextField(15);
              input2 = new JTextField(15);
              JRadioButton radSearch = new JRadioButton("Search Query");
              JRadioButton radCached = new JRadioButton("Cached Query");
              JButton submitButton = new JButton("Submit Query");
              ButtonHandler buttonHandler = new ButtonHandler();
              submitButton.addActionListener(buttonHandler);
              ButtonGroup group = new ButtonGroup();
              group.add(radSearch);
              group.add(radCached);Ive tried declaring buttonHandler as a static variable and this dosn't work either. I've never had this problem before it must be something silly im missing...?
    Thanks
    Lee

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • Non-static method close() cannot be referenced from a static context

    Friends,
    I am having a little help with some static and not static issues.
    I created a JMenuBar, it's in the file: SlideViewMenu.java
    One of the operations is File->Close and another is File->Exit.
    The listener is in the SlideViewMenu.java file. The listener needs to reference two non-static methods within SlideView.java.
    Here's some of the code:
    SlideViewMenu.java
    public class SlideViewMenu {
        public JMenuBar createMenuBar() {
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
         // All the menu stuff works fine and is taken care of here.
       // Listener for Menu
       class MenuActionListener implements ActionListener {
         public void actionPerformed (ActionEvent actionEvent) {
              String selection = (String)actionEvent.getActionCommand();
             if (selection.equals("Close"))
              SlideViewFrame.close();
             else  SlideViewFrame.exit();
    }SlideView.java
    // Driver class
    public class SlideView {
         public static void main(String[] args) {
              ExitableJFrame f = new SlideViewFrame("SlideView");
                    // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame {
            // some things here, work fine.
         private SlideViewMenu menuBar = new SlideViewMenu();
         public SlideViewFrame(String title) {
         // Set title, layout, and background color
         super(title);
         setJMenuBar(menuBar.createMenuBar());
            // Stuff here works fine.
         // Handles doing stuff once the file has been selected
         public void setFileName(File fullFileName, String simpleName) {
            // Stuff here works fine.     
         // File->Close. clean up everything.
         public void close() {
              setTitle("SlideView");
              textArea.setText("");
              scrollBar.setVisible(false);
              textArea.setVisible(false);
              statsPanel.setVisible(false);
         // File->Exit.     
         public void exit() {
              System.exit(0);
    }The error I'm getting is:
    SlideViewMenu.java:50: non-static method close() cannot be referenced from a static context
    I don't get it?
    Thanks for all help.

    Making close() and exit() static would not solve the problem because close() requires access to nonstatic member variables/functions.
    Fortunately, that is not necessary. The real reason you are having a problem is that you don't have any way in your listener to access the main frame window, which is what the listener trying to control. You made a stab at gaining access by prefixing the function with the class name, but, as the compiler has informed you, that is only valid for static methods. If you think about it, you should see the sense in that, because, what if you had a number of frames and you executed className.close()? Which one would you close? All of them?
    Fortunately, there is an easy way out that ties the listener to the frame.
    SlideViewMenu.java:public class SlideViewMenu
      // Here's where we keep the link to the parent.
      private SlideViewFrame parentFrame;
      // Here's where we link to the parent.
      public JMenuBar createMenuBar(SlideViewFrame linkParentFrame)
        parentFrame = linkParentFrame;
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
        // All the menu stuff works fine and is taken care of here.
      // Listener for Menu --- It is assumed that this is a non-static nested
      // class in SlideViewMenu. All SlideViewMenu variables are accessible from
      // here. If this is not the case, simply add a similar member variable
      //  to this class, initialize it with a constructor parameter, and
      // pass the SlideViewMenu parentFrame when the listener is
      // constructed.
      class MenuActionListener implements ActionListener
        public void actionPerformed (ActionEvent actionEvent)
          String selection = (String)actionEvent.getActionCommand();
          // Use parentFrame instead of class name.
          if (selection.equals("Close"))
              parentFrame.close();
            else
              parentFrame.exit();
    }SlideView.java// Driver class
    public class SlideView
      public static void main(String[] args)
        ExitableJFrame f = new SlideViewFrame("SlideView");
        // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame
      // some things here, work fine.
      private SlideViewMenu menuBar = new SlideViewMenu();
      public SlideViewFrame(String title)
        // Set title, layout, and background color
        super(title);
        //Here's where we set up the link.
        setJMenuBar(menuBar.createMenuBar(this));
      // Stuff here works fine.
      // Handles doing stuff once the file has been selected
      public void setFileName(File fullFileName, String simpleName)
        // Stuff here works fine.     
      // File->Close. clean up everything.
      public void close()
        setTitle("SlideView");
        textArea.setText("");
        scrollBar.setVisible(false);
        textArea.setVisible(false);
        statsPanel.setVisible(false);
      // File->Exit.
      public void exit()
        System.exit(0);
    }

  • Implementing Custom Event - non-static referencing in static context error

    Hi,
    I'm implementing a custom event, and I have problems adding my custom listeners to objects. I can't compile because I'm referencing a non-static method (my custom addListener method ) from a static context (a JFrame which contains static main).
    However, the same error occurs even if I try to add the custom listener to another class without the main function.
    Q1. Is the way I'm adding the listener wrong? Is there a way to resolve the non-static referencing error?
    Q2. From the examples online, I don't see people adding the Class name in front of addListener.
    Refering to the code below, if I remove "Data." in front of addDataUpdatelistener, I get the error:
    cannot resolve symbol method addDataUpdateListener (<anonymous DataUpdateListener>)
    I'm wondering if this is where the error is coming from.
    Below is a simplified version of my code. Thanks in advance!
    Cindy
    //dividers indicate contents are in separate source files
    //DataUpdateEvent Class
    public class DataUpdateEvent extends java.util.EventObject
         public DataUpdateEvent(Object eventSource)
              super(eventSource);
    //DataUpdateListener Interface
    public interface DataUpdateListener extends java.util.EventListener
      public void dataUpdateOccured(DataUpdateEvent event);
    //Data Class: contains data which is updated periodically. Needs to notify Display frame.
    class Data
    //do something to data
    //fire an event to notify listeners data has changed
    fireEvent(new DataUpdateEvent(this));
      private void fireEvent(DataUpdateEvent event)
           // Make a copy of the list and use this list to fire events.
           // This way listeners can be added and removed to and from
           // the original list in response to this event.
           Vector list;
           synchronized(this)
                list = (Vector)listeners.clone();
           for (int i=0; i < list.size(); i++)
                // Get the next listener and cast the object to right listener type.
               DataUpdateListener listener = (DataUpdateListener) list.elementAt(i);
               // Make a call to the method implemented by the listeners
                  // and defined in the listener interface object.
                  listener.dataUpdateOccured(event);
               System.out.println("event fired");
    public synchronized void addDataUpdateListener(DataUpdateListener listener)
         listeners.addElement(listener);
      public synchronized void removeDataUpdateListener(DataUpdateListener listener)
         listeners.removeElement(listener);
    //Display Class: creates a JFrame to display data
    public class Display extends javax.swing.JFrame
         public static void main(String args[])
              //display frame
              new Display().show();
         public Display()
         //ERROR OCCURS HERE:
         // Non-static method addDataUpdateListener (DataUpdateListener) cannot be referenced from a static context
         Data.addDataUpdateListener(new DataUpdateListener()
             public void dataUpdateOccured(DataUpdateEvent e)
                 System.out.println("Event Received!");
    //-----------------------------------------------------------

    Calling
        Data.someMethodName()is referencing a method in the Data class whose signature includes the 'static' modifier and
    might look something like this:
    class Data
        static void someMethodName() {}What you want is to add the listener to an instance of the Data class. It's just like adding
    an ActionListener to a JButton:
        JButton.addActionListener(new ActionListener()    // won't work
        JButton button = new JButton("button");           // instance of JButton
        button.addActionListener(new ActionListener()     // okay
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    public class EventTest extends JFrame
        Data data;
        JLabel label;
        public EventTest()
            label = getLabel();
            data = new Data();
            // add listener to instance ('data') of Data
            data.addDataUpdateListener(new DataUpdateListener()
                public void dataUpdateOccured(DataUpdateEvent e)
                    System.out.println("Event Received!");
                    label.setText("count = " + e.getValue());
            getContentPane().add(label, "South");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(300,200);
            setLocation(200,200);
            setVisible(true);
        private JLabel getLabel()
            label = new JLabel("  ", JLabel.CENTER);
            Dimension d = label.getPreferredSize();
            d.height = 25;
            label.setPreferredSize(d);
            return label;
        public static void main(String[] args)
            new EventTest();
    * DataUpdateEvent Class
    class DataUpdateEvent extends java.util.EventObject
        int value;
        public DataUpdateEvent(Object eventSource, int value)
            super(eventSource);
            this.value = value;
        public int getValue()
            return value;
    * DataUpdateListener Interface
    interface DataUpdateListener extends java.util.EventListener
        public void dataUpdateOccured(DataUpdateEvent event);
    * Data Class: contains data which is updated periodically.
    * Needs to notify Display frame.
    class Data
        Vector listeners;
        int count;
        public Data()
            listeners = new Vector();
            count = 0;
            new Thread(runner).start();
        private void increaseCount()
            count++;
            fireEvent(new DataUpdateEvent(this, count));
        private void fireEvent(DataUpdateEvent event)
            // Make a copy of the list and use this list to fire events.
            // This way listeners can be added and removed to and from
            // the original list in response to this event.
            Vector list;
            synchronized(this)
                list = (Vector)listeners.clone();
            for (int i=0; i < list.size(); i++)
                // Get the next listener and cast the object to right listener type.
                DataUpdateListener listener = (DataUpdateListener) list.elementAt(i);
                // Make a call to the method implemented by the listeners
                // and defined in the listener interface object.
                listener.dataUpdateOccured(event);
            System.out.println("event fired");
        public synchronized void addDataUpdateListener(DataUpdateListener listener)
            listeners.addElement(listener);
        public synchronized void removeDataUpdateListener(DataUpdateListener listener)
            listeners.removeElement(listener);
        private Runnable runner = new Runnable()
            public void run()
                boolean runit = true;
                while(runit)
                    increaseCount();
                    try
                        Thread.sleep(1000);
                    catch(InterruptedException ie)
                        System.err.println("interrupt: " + ie.getMessage());
                    if(count > 100)
                        runit = false;
    }

  • Painting jpeg in java application: non-static method ... static context

    Hi!
    I simply want to show a jpeg within a java application. Showing the jpeg in an applet is no problem (see code below). But I have difficulties to translate this code to a java application. No matter what I try to load the jpeg, I end up with the following error:
    non-static method createImage() cannot be referenced from a static context
    How can I surround it? Thanx in advance for your help!
    Working applet
    import java.applet.*;
    import java.awt.*;
    public class shJpAp extends javax.swing.JApplet {
    Image pic;
    /** Creates a new instance of shJpAp */
    public shJpAp() {
    public void init() {
    pic=getImage(getCodeBase(), "lemmer.jpg");
    prepareImage(pic,this);
    public void paint (Graphics g) {
    g.drawImage(pic,0,0,this);
    Application
    import java.awt.*;
    public class shJp extends javax.swing.JFrame {
    Image pic;
    /** Creates new form shJp */
    public shJp() {
    initComponents();
    //pic = java.awt.Toolkit.getImage("lemmer.jpg");
    ---> pic = java.awt.Toolkit.createImage("lemmer.jpg");
    ---> prepareImage(pic, this);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    pack();
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
    new shJp().show();
    // Variables declaration - do not modify
    // End of variables declaration
    public void paint( Graphics g) {
    g.drawImage(pic, 0,0,this);
    }

    Hi,
    just want to add a solution I found in some textbook (see code below). I hate finding every possible question in the internet, but seldom fitting answers.....
    But again, one little thing pushed me close to my first heart attack: The code below works well when executed by foot (...java showPic...). In the NetBeans 3.6 the frame refuses to show the pic!
    I am looking for an appropiate forum - but if anyone of you can help, it would be very nice ;-)
    import java.awt.*;
    import java.awt.event.*;
    public class showPic extends Frame {
    Image pic;
    public showPic() {
    addWindowListener( new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    pic = getToolkit().getImage("lemmer.jpg");
    setSize(200,100);
    setVisible(true);
    public void paint(Graphics g) {
    if (pic != null) {
    g.drawImage(pic,60,20,this);
    public static void main( String[] args ) {
    new showPic();
    }

  • Static context error, nothing declared static, new instance isn't working

    I'm trying to get the IP address of a user using my applet. Nothing in my code is declared static.
    InetAddress IP = InetAddress.getAddress();I get non-static method getAddress cannot be referenced from a static context.
    I just read on another post with someone having a similar but not identical problem and someone replied saying you need to create a new instance. So I tried this:
    InetAddress IP = new InetAddress();
    //IP.getAddress();With this, I get the error: InetAddress(); is not public in java.net.InetAddress; cannot be accessed from an outside package
    What can I do? It's probably something simple.
    If you need code just ask, there's just alot of code and it might take awhile to recreate it.

    I'm trying to get the IP address of a user using my
    applet. Nothing in my code is declared static.
    InetAddress IP = InetAddress.getAddress();I get non-static method getAddress cannot be
    referenced from a static context.
    I just read on another post with someone having a
    similar but not identical problem and someone replied
    saying you need to create a new instance. So I tried
    this:
    InetAddress IP = new InetAddress();
    //IP.getAddress();With this, I get the error: InetAddress(); is not
    public in java.net.InetAddress; cannot be accessed
    from an outside package
    What can I do? It's probably something simple.
    If you need code just ask, there's just alot of code
    and it might take awhile to recreate it.In your first try the method you attempted to use can only be used in an instant of an InetAddress ie. ip.getAddress(). Therefore the compiler thought you were trying to call a static method that was really an instance method. On your second try you used the contructor of InetAddress which isn't public, so you can't use it. To make an InetAddress use any of the static methods of the InetAddress, which can be found at http://java.sun.com/j2se/1.4.1/docs/api/java/net/InetAddress.html

  • Static Function problem

    Hi, I have been recently working on a program and have come across this error that has stumped me!
    prefsPane.java:101: non-static method updateVar(int) cannot be referenced from a static context
    divLetter = divPane.updateVar(0);
    ^
    prefsPane.java:102: non-static method updateVar(int) cannot be referenced from a static context
    divName = divPane.updateVar(1);
    ^
    // divPane.java Creates a new divPane. DuH!
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    public class divPane extends JPanel {
    protected JLabel letterLabel, nameLabel;
    protected JButton applyButton;
    String newLetter, newName;
    public JTextField letterField, nameField;
         public divPane(String divName, String divLetter) {
              super(new GridBagLayout() );
              // Initalize the JLabels
              letterLabel = new JLabel("Id for Letters: ");
              nameLabel   = new JLabel("Id for Names: ");
              // Initalize the JTextField
              letterField = new JTextField(divLetter, 10);
              nameField   = new JTextField(divName, 10);
              // Add the Constraints for the Panel
              GridBagConstraints c = new GridBagConstraints();
              c.insets = new Insets(15,10,0,0);
              c.gridx   =  0;
              c.gridy   =  0;
              add(letterLabel, c);
              c.insets = new Insets(15,10,0,0);
              c.gridx   =  1;
              c.gridy   =  0;
              add(letterField, c);
              c.insets = new Insets(15,10,0,0);
              c.gridx   =  0;
              c.gridy   =  1;
              add(nameLabel, c);
              c.insets = new Insets(15,10,0,0);
              c.gridx   =  1;
              c.gridy   =  1;
              add(nameField, c);
         }// End Main Constructor          
         public String updateVar(int index) {
           if(index == 0)
             return (String)letterField.getText();
           else if(index == 1)
             return (String)nameField.getText();
           else
              System.out.println("Error!");
             return "Error!";
         }// End updateVar
    }Here is the snippet of code that calls updateVar
    public void doSave()
          JFrame nullframe = new JFrame();
             divLetter = divPane.updateVar(0);
             divName   = divPane.updateVar(1);
             System.out.println(divName);
             System.out.println(divLetter);
    }Note: This is a problem from one of my previous posts. (http://forum.java.sun.com/thread.jsp?forum=31&thread=551160&start=15&range=15&hilite=false&q=)

    Thank you, how might I reference that function without
    making it static.You haven't said if doSave is in the same class or not. If it's in the same class then you are able to call it without another object.
    divLetter = updateVar(0);Look at the other posts if you want to know to to access it from another object.
    /Kaj

  • Cannot use this in a static context

    I have a static method in which I am trying to use a logging class. I get an error that says "Cannot use this in a static context" when I compile the following code.
    Log log = LogFactory.getLog(this.getClass());What's the problem and how do I get around it?

    1) What's the problem.
    The error states the problem concisely. You are trying to use this[b] to get the class. You can't do this in a static method.
    2) How do I get around it...
    Instead of typing this.getClass() you type <CLASS_NAME>.classwhere CLASS_NAME is the name of the class the static method is in.

  • Question about static context when using classes

    hey there.
    i'm pretty new to java an here's my problem:
    public class kreise {
         public static void main (String[] args) {
             //creating the circles
             create a = new create(1,4,3);
             create b = new create(7,2,5);
             System.out.println(a);
             System.out.println(b);
             //diameters...unimportant right now
             getDiameter a_ = new getDiameter(a.radius);
             getDiameter b_ = new getDiameter(b.radius);
             System.out.println(a_);
             System.out.println(b_);
             //moving the circles
             double x = 2;
             double y = 9;
             double z = 3;
             a = create.move();
             System.out.println(a);
    }creating a circle makes use of the class create which looks like this:
    public class create {
        public double k1;
        public double k2;
        public double radius;
        public create(double x,double y,double r) {
            k1 = x;
            k2 = y;
            radius = r;
        public create move() {
            k1 = 1;
            k2 = 1;
            radius = 3;
            return new create (k1,k2,radius);
        public String toString() {
        return "Koordinaten: "+k1+" / "+k2+". Radius: "+radius;
    }now that's all totally fine, but when i try to usw create.move to change the circles coordinates the compiler says that the non-static method move() can't be referenced from a static context. so far i've seen that my main() funktion MUST be static. when declaring the doubles k1, k2, and radius in create() static it works, but then of course when having created the second circle it overwrites the first one.
    i pretty much have the feeling this is very much a standard beginner problem, but searching for the topic never really brought up my problem exactly. thanks in advance!

    You can't access a non-static method from within a static context. So, you have to call move() from outside of the main method. main has to be static because, in short, at least one method has to be static because there haven't been any objects initialized when the program is started. There are more fundamental problems than with just the static context issue.
    I'm confused by your code though. You call create.move(), but this would only be possible if move() was static, and from what I see, it's not. Now that's just one part of it. My second issue is that the logic behind the move() method is very messy. You shouldn't return a newly instantiated object, instead it should just change the fields of the current object. Also as a general rule, instance fields should be private; you have them as public, and this would be problematic because anything can access it.
    Have you heard of getters and setters? That would be what I recommend.
    Now, also, when you are "moving" it, you are basically creating a new circle with completely differently properties; in light of this, I've renamed it change(). Here would be my version of your code:
    public class CircleTester {
        public static void main (String[] args)
             //Bad way to do it, but here's one way around it:
             new CircleTester().moveCircle();
        private void moveCircle()     //really a bad method, but for now, it'll do
            Circle a = new Circle(1,4,3);
            Circle b = new Circle(7,2,5);
            System.out.println(a);
            System.out.println(b);
            //diameters. Don't need to have a new getDiameter class
            double a_ = a.getRadius() * 2;     //Instead of doing * 2 each time, you could have a method that just returns the radius * 2
            double b_ = b.getRadius() * 2;
            System.out.println(a_);
            System.out.println(b_);
            //move the circle
            a.change(2,9,3);
            System.out.println(a);
    public class Circle {
        private double k1;
        private double k2;
        private double radius;
        public Circle(double x,double y,double r)
            k1 = x;
            k2 = y;
            radius = r;
        public void change(int x, int y, int r)
            k1 = x;
            k2 = y;
            radius = r;
        public String toString()
             return "Koordinaten: "+k1+" / "+k2+". Radius: "+radius;
        public double getRadius()
             return radius;
    }On another note, there is already a ellipse class: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/geom/Ellipse2D.html

  • Static Context

    Alright, this problem is a little difficult to explain. It's for an RPG game. Spell is a working class (builds me a new variable)
    public class Setup
    String dats[] = new String[10];
    public void loadDat()
               /*code for opening data file is unimportant, assume it works and is a string in dats[0]*/
         public Spell getSpell(String a)  //This returns a spell based on ID tag
              //this searches through dats[0] for "a" and builds a Spell that it declares as foundspell; assume it works
              return foundspell;
         //This returns an ArrayList of spells (of one type) that the user can cast
         public ArrayList searchSpell(int type, int req)
              ArrayList spells = new ArrayList();
               /*this uses "getSpell()" to search the dats[0] for certain requires; assume it works as intended as puts all the spells into spells*/
              return spells;
    }loadDat() is executed as the start of the program (in another class).
    So, I need it to be non-static because I need the dats[0] to be accessible always (without running it everytime searchSpell() is called). But when I call searchSpell() from another class (that's not always static, its non-static too) it says: "non-static method cannot be referenced by a static context". If i declare everything as static (the methods above). It says hte same error, but points at the variable dats[0].
    Any thoughts?
    Sorry it's so confusing, if anyone has any idea, please tell, I can probably add more details if you think you need to know something I didn't write in.

    I fixed the problem. All I had to do was declare
    dats[] as static.
    static String dats[] = new String[10];
    Umm,
    Yeah, it is an example of a bad designing an there are several reason for this.
    One of them is that we generally use static keywords for member of classes, not for referece variables to any classes.

  • 2 errors: static context & java.lang.String

    I get the following 2 errors when I try and compile my code. What do I need to do in order to fix this problem?
    Any help appreciated.
    C:\>javac DraftD.java
    DraftD.java:54: non-static variable MAXIMUM cannot be referenced from a static context
    if(temp <= MAXIMUM)
    ^
    DraftD.java:54: operator <= cannot be applied to java.lang.String,int
    if(temp <= MAXIMUM)
    ^
    2 errors
    import java.io.*;
    import java.util.*;
    public class DraftD
    final int MAXIMUM = 20;
    public static void main(String[] args) throws IOException
    try
    Runtime program = Runtime.getRuntime();
    Process proc = program.exec("cmd.exe /c C:/ntpq.exe -p >C:/answer.txt");
    try{
    proc.waitFor();
    catch (InterruptedException e){}
    catch(IOException e1)
    int i = 0;
    BufferedReader br = new BufferedReader(new FileReader("C:/answer.txt"));
    String line = "";
    while ((line = br.readLine()) != null)
    i++;
    if(i==3) break;
    br.close();
    if(i==3)
    StringTokenizer st = new StringTokenizer(line," ");
         int k=1;
    while(st.hasMoreTokens())
         String temp = st.nextToken();
    if(k==2){
              String secondToken = temp;
    if(temp <= MAXIMUM)
              {System.out.println("less than Max");}
         k++;
    else System.out.println("less than 3 lines in file");
    System.exit(0);
    }

    You should use Integer.parseInt(temp); to convert temp to an int
    Because MAXIMUM is not static, every DraftD object will have one, that's the way properties work.
    main() however is static, and so there is only one between all the DraftD objects.
    It is a bit harder to explain with main(), but suppose we did this:public class ABC
      public int x;
      public static int getX()
        return x;
    ABC a = new ABC();
    ABC b = new ABC();
    a.x = 1;
    b.x = 2;
    int result = ABC.getX();should result be 1 or 2? it doesn't know which x to get, so the compiler complains.
    if MAXIMUM is a constant, you should make it public static final

Maybe you are looking for

  • Capturing MiniDV, then deinterlacing it?

    Hi. I'm trying to do something very very simply in iMovie HD, but failing miserably. I want to import some DV-PAL-Widescreen MiniDV footage from my digital camcorder, get a nice big uncompressed .dv file on my desktop, deinterlace, then import it bac

  • Time capsule deleted all of my backups

    so i clean installed my laptop and was maunally restoring all the files and i had done all that except for my photo library. and for some reasons when my laptop was backing up it deleted all my old backups and i can't restore my photo library! It ess

  • How to see name of video files in iOS7?

    How to see name of video files in iOS7?

  • Hallo, I need to help with Acrobat 8.0 on Win7Pro 64 bit

    Hallo, I need to help with Acrobat 8.0 on Win7Pro 64 bit. The launguage for this communication is English, isnt it?. Is possible to write Czech?

  • Help me with CL_GUI_ALV_GRID

    Hi There are so many fields in LVC_S_FCAT and LVC_S_LAYO. Anyone can tell me which fields are important and used most frequently. Edited by: Alex Zhang on Aug 20, 2008 5:32 AM