[RESOLVIDO]Problema com this keyword e static

3 respostas
F

Ola!

Nesta parte de um programa em que estou a resolver, que consiste numa pequena janela de Log-in com nome e password, estou com um problema com a this keyword e com o static e non static. Eu nunca percebi muito bem para que nem como e que a this keyword funciona e o que se passa e que onde diz "textField.addActionListener(this);" , aparece-me um erro:

"non-static variable this cannot be referenced from a static context". Como eu resolvo isto?

Obrigado

import javax.swing.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;              
import java.awt.event.*;        
import java.net.URL;
import java.io.IOException;

public class Livraria implements ActionListener
{
	private static void addLabelTextRows(JLabel[] labels,JTextField[] textFields, GridBagLayout gridbag,Container container) 
	{
        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.EAST;
        int numLabels = labels.length;

        for (int i = 0; i < numLabels; i++) 
        {
            c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
            c.fill = GridBagConstraints.NONE;      //reset to default
            c.weightx = 0.0;                       //reset to default
            container.add(labels[i], c);

            c.gridwidth = GridBagConstraints.REMAINDER;     //end row
            c.fill = GridBagConstraints.HORIZONTAL;
            c.weightx = 1.0;
            container.add(textFields[i], c);
        }
    }
    	
    
    protected static final String name = "Nombre";
    protected static final String password = "Clave";
    protected JLabel actionLabel;
    
	public static void main (String[] args)
	{	
    
    // Create frame
		JFrame frame = new JFrame("Login");
		frame.setSize(400, 200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // What to do when the X button is pressed ( Leave ) .
    
    //Textfields  
        JTextField textField = new JTextField(10); // The ten is the size of the box.
        textField.setActionCommand(name);
        textField.addActionListener(this); // <-----AQUI
        
        JPasswordField passwordField = new JPasswordField(10); // The size of the box will be the same as in TextField.
        passwordField.setActionCommand(password);
        
    //Create some labels for the fields.
        
        JLabel textFieldLabel = new JLabel(name + ": ");
        textFieldLabel.setLabelFor(textField);
        JLabel passwordFieldLabel = new JLabel(password + ": ");
        passwordFieldLabel.setLabelFor(passwordField);
        
    //Lay out the text controls and the labels.
        
        JPanel textControlsPane = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();

        textControlsPane.setLayout(gridbag); // Layout of the components of the frame.
        
        JLabel[] labels = {textFieldLabel, passwordFieldLabel};
        JTextField[] textFields = {textField, passwordField};
        addLabelTextRows(labels, textFields, gridbag, textControlsPane);
        
        //c.gridwidth = GridBagConstraints.REMAINDER; //last
        //c.anchor = GridBagConstraints.WEST;
        //c.weightx = 1.0;
        
        textControlsPane.setBorder(BorderFactory.createCompoundBorder( // Create the Lines around the Name and Password.
                                BorderFactory.createTitledBorder("Livraria Ideal Login"), // What it says on the lines
                                BorderFactory.createEmptyBorder(15,15,15,15))); // Size of the lines 

        
        
        JPanel leftPane = new JPanel(new BorderLayout());
        leftPane.add(textControlsPane, BorderLayout.PAGE_START);
        frame.add(leftPane, BorderLayout.LINE_START);
          
          
        // Create and show GUI             
        frame.pack();             
        frame.setVisible(true);
           
	}
	
	public void actionPerformed(ActionEvent e) 
    {
        String prefix = "You typed \"";
        if (name.equals(e.getActionCommand())) 
        {
            JTextField source = (JTextField)e.getSource();
            //actionLabel.setText(prefix + source.getText() + "\"");
            System.out.println(source.getText());
        } 
        else 
        	if (password.equals(e.getActionCommand())) 
        {
            JPasswordField source = (JPasswordField)e.getSource();
            actionLabel.setText(prefix + new String(source.getPassword())+ "\"");
        } 
        
        /*String username = actionLabel.getText();
        System.out.println(username);*/
    }
	
	
}

3 Respostas

gpellizzoni

this se refere à instância, mas o modificador static faz com que o objeto referenciado não dependa de instância. Você não pode usar ambos no mesmo contexto.

http://guj.com.br/java/249865-metodos-estaticos-e-variaveis-de-instancia

matheuslmota
O método main é um método estático. Você não pode chamar "this", que se refere à uma instância, dentro de um método estático. Para contornar esse problema, você pode inicializar seu JTextField dentro de um construtor:
import javax.swing.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;              
import java.awt.event.*;        
import java.net.URL;
import java.io.IOException;

public class Livraria implements ActionListener
{
        private JTextField textField;

        public Livraria()
        {
              textField = new JTextField(10); // The ten is the size of the box.
              textField.setActionCommand(name);
              textField.addActionListener(this); // <-----AQUI
         }

	private static void addLabelTextRows(JLabel[] labels,JTextField[] textFields, GridBagLayout gridbag,Container container) 
	{
        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.EAST;
        int numLabels = labels.length;

        for (int i = 0; i < numLabels; i++) 
        {
            c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
            c.fill = GridBagConstraints.NONE;      //reset to default
            c.weightx = 0.0;                       //reset to default
            container.add(labels[i], c);

            c.gridwidth = GridBagConstraints.REMAINDER;     //end row
            c.fill = GridBagConstraints.HORIZONTAL;
            c.weightx = 1.0;
            container.add(textFields[i], c);
        }
    }
    	
    
    protected static final String name = "Nombre";
    protected static final String password = "Clave";
    protected JLabel actionLabel;
    
	public static void main (String[] args)
	{	
    
    // Create frame
	JFrame frame = new JFrame("Login");
	frame.setSize(400, 200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // What to do when the X button is pressed ( Leave ) .
    
        
        JPasswordField passwordField = new JPasswordField(10); // The size of the box will be the same as in TextField.
        passwordField.setActionCommand(password);
        
    //Create some labels for the fields.
        
        JLabel textFieldLabel = new JLabel(name + ": ");
        textFieldLabel.setLabelFor(textField);
        JLabel passwordFieldLabel = new JLabel(password + ": ");
        passwordFieldLabel.setLabelFor(passwordField);
        
    //Lay out the text controls and the labels.
        
        JPanel textControlsPane = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();

        textControlsPane.setLayout(gridbag); // Layout of the components of the frame.
        
        JLabel[] labels = {textFieldLabel, passwordFieldLabel};
        JTextField[] textFields = {textField, passwordField};
        addLabelTextRows(labels, textFields, gridbag, textControlsPane);
        
        //c.gridwidth = GridBagConstraints.REMAINDER; //last
        //c.anchor = GridBagConstraints.WEST;
        //c.weightx = 1.0;
        
        textControlsPane.setBorder(BorderFactory.createCompoundBorder( // Create the Lines around the Name and Password.
                                BorderFactory.createTitledBorder("Livraria Ideal Login"), // What it says on the lines
                                BorderFactory.createEmptyBorder(15,15,15,15))); // Size of the lines 

        
        
        JPanel leftPane = new JPanel(new BorderLayout());
        leftPane.add(textControlsPane, BorderLayout.PAGE_START);
        frame.add(leftPane, BorderLayout.LINE_START);
          
          
        // Create and show GUI             
        frame.pack();             
        frame.setVisible(true);
           
	}
	
	public void actionPerformed(ActionEvent e) 
    {
        String prefix = "You typed \"";
        if (name.equals(e.getActionCommand())) 
        {
            JTextField source = (JTextField)e.getSource();
            //actionLabel.setText(prefix + source.getText() + "\"");
            System.out.println(source.getText());
        } 
        else 
        	if (password.equals(e.getActionCommand())) 
        {
            JPasswordField source = (JPasswordField)e.getSource();
            actionLabel.setText(prefix + new String(source.getPassword())+ "\"");
        } 
        
        /*String username = actionLabel.getText();
        System.out.println(username);*/
    }
	
	
}
F

já resolvi! obrigado!

Criado 13 de agosto de 2011
Ultima resposta 13 de ago. de 2011
Respostas 3
Participantes 3