Hola buenas estoy aprendiendo java y al hacer una pequeña interfaz de un programa que concatene palabras en Swing y no consigo que funciona, al ejecutar me da un Null pointer exception... a ver si me podeis ayudar. Gracias de antemano.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@SuppressWarnings("serial")
public class Main extends JFrame implements ActionListener{
private int anchoVentana = 300;
private int altoVentana = 400;
private JLabel j;
private JPanel pf1;
private JPanel pf2;
private JPanel pf3;
private JPanel pf4;
private JTextField t1;
private JTextField t2;
private JButton bUno;
private JButton bDos;
private JButton bUnoDos;
private JButton bDosUno;
private void inicializarVentana() {
int anchoPantalla = Toolkit.getDefaultToolkit().getScreenSize().width;
int altoPantalla = Toolkit.getDefaultToolkit().getScreenSize().height;
setSize(anchoVentana, altoVentana);
setLocation(anchoPantalla / 2 - anchoVentana / 2, altoPantalla / 2
- altoVentana / 2);
setTitle("Ejercicio 04");
setLayout(new GridLayout(4,1));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creación de los paneles principales
//Panel1
this.pf1=new JPanel();
pf1.setLayout(new GridLayout(1,1));
this.add(pf1);
//JLabel en panel 1
JLabel j=new JLabel();
pf1.add(j);
//Panel2
this.pf2=new JPanel();
pf2.setLayout(new GridLayout(1,2));
this.add(pf2);
//JTextfields en panel 2
this.t1=new JTextField(); pf2.add(t1);
this.t2=new JTextField(); pf2.add(t2);
// Panel 3
pf3=new JPanel();
pf3.setLayout(new GridLayout(1,2));
this.add(pf3);
// JButtons en panel 3
bUnoDos=new JButton("Uno=>Dos"); pf3.add(bUnoDos);
bUnoDos.addActionListener(this);
bUnoDos.setActionCommand("bUnoDos");
bDosUno=new JButton("Dos=>Uno");pf3.add(bDosUno);
bDosUno.addActionListener(this);
bDosUno.setActionCommand("bDosUno");
// Panel 4
pf4=new JPanel();
pf4.setLayout(new GridLayout(1,2));
this.add(pf4);
//JButtons en panel 4
bUno=new JButton ("Uno"); pf4.add(bUno);
bUno.addActionListener(this);
bUno.setActionCommand("bUno");
bDos= new JButton ("Dos"); pf4.add(bDos);
bDos.addActionListener(this);
bDos.setActionCommand("bDos");
setVisible(true);
}
public Main() {
inicializarVentana();
}
public static void main(String[] args) {
new Main();
}
public void actionPerformed(ActionEvent e) {
//Da NULL Pointer Exception en tiempo de ejecución
switch (e.getActionCommand()) {
case "bUnoDos": j.setText(t1.getText()+t2.getText() );break;
case "bDosUno": j.setText(t2.getText()+t1.getText() );break;
case "bUno": j.setText(t1.getText() );break;
case "bDos": j.setText(t2.getText() );break;
}
}
}