#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    1
    Rep Power
    0

    Question GUI - JFrame/JButton/JTextField error


    I'm currently trying to learn how to make GUI's and use JTextFields and JButtons. I made this code in hopes it would
    get text from a JTextField and when a button was pressed it would display the text the user typed into the JTextField. However, I have been getting this error :

    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Cannot make a static reference to the non-static method client(String) from the type MainClass

    at MainClass.main(MainClass.java:16)





    Java is telling me that the method client(); has to be static. But when I made the method client(); static.
    I get an error at button1.addActionListener(this); (It says it can't work in a static method). So im kind of stuck... Anyone know how to get this to work ?

    Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    
    public class MainClass extends JFrame implements ActionListener {
    	
    	 JButton button1 = new JButton("button1");
    	 JTextField tfield = new JTextField();
    	
    	 
    	public static void main(String args[]) {
    		client("Enter a message!");
    		
    	}
    	
    	
    	public void client(String message) {
    		JFrame frame = new JFrame();
    		JPanel panel = new JPanel();
    		
    		frame.setSize(350,250);
    		frame.setVisible(true);
    		frame.setLocationRelativeTo(null);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		frame.add(panel);
    		panel.add(tfield);
    		panel.add(button1);
    		button1.addActionListener(this);
    		JLabel Message = new JLabel(message);
    		panel.add(Message);
    	
    		
    	}
    
    
    	public void actionPerformed(ActionEvent e) {
    		if(e.getSource() == button1) {
    			String input = tfield.getText();
    			client(input);
    		}
    	}
    
    
    }
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Feb 2004
    Location
    Mobile, Alabama
    Posts
    4,023
    Rep Power
    1285
    The main method is always in a static context.

    client is an instance method.

IMN logo majestic logo threadwatch logo seochat tools logo