I'm trying to make a Java Gui that print the text on a JTextField
into a label.
So, on runtime I'll write something in a JTextField
then I'll press a button that print the content of JTextField
in a label.
But the program give me a java.lang.NullPointerException
. Is there something wrong in ActionListener
method?
Could you help me?
Below the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.util.*;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import java.awt.Rectangle;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.util.EventObject;
import java.awt.event.ActionEvent;
public class MastermindGui1 extends JFrame {
public static JTextField insNome;
public static JLabel welcomeLbl;
private JPanel contentPane;
Container contenuto;
public MastermindGui1() {
JFrame finestra = new JFrame("MASTERMIND");
finestra.setResizable(false);
finestra.setBounds(200,200,300,300);
contenuto = finestra.getContentPane();
contenuto.setBackground(Color.YELLOW);
finestra.getContentPane().setLayout(null);
JTextField insNome = new JTextField();
insNome.setBounds(21, 70, 151, 35);
contenuto.add(insNome);
JLabel welcomeLbl = new JLabel("");
welcomeLbl.setVisible(false);
welcomeLbl.setBounds(58, 138, 180, 74);
welcomeLbl.setBackground(Color.ORANGE);
contenuto.add(welcomeLbl);
JLabel lblNewLabel = new JLabel("INSERISCI IL TUO NOME");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(75, 11, 142, 23);
finestra.getContentPane().add(lblNewLabel);
JButton stampa = new JButton("STAMPA");
stampa.addActionListener(new stampa());
stampa.setBounds(195, 76, 89, 23);
contenuto.add(stampa);
stampa.addActionListener(new stampa());
finestra.setVisible(true);
finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class stampa implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
insNome = (JTextField) e.getSource();
String testo = insNome.getText();
welcomeLbl.setText(testo);
}
}
public static void main(String[] args) {
MastermindGui1 finestra = new MastermindGui1();
}
}