package airlinep;
/**
*
*
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NewClass1 extends JApplet{
JButton b1;
JButton b2;
JLabel lbl;
@Override
public void init()
{
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run(){
guiInit();//throw new UnsupportedOperationException("Not supported yet.");
}
});
} catch (Exception ex) {
System.out.println("could not generate due to "+ex.toString());
}
}
public void start()
{}
public void stop()
{}
public void destroy()
{}
private void guiInit()
{
//setLayout(new FlowLayout());
b1.setText("b1");
b2.setText("b2");
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
lbl.setText(b1.getText()+" was pressed at ");//To change body of generated methods, choose Tools | Templates.
}
});
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
lbl.setText(b2.getText()+" was pressed at ");//To change body of generated methods, choose Tools | Templates.
}
});
getContentPane().add(b1);
getContentPane().add(b2);
getContentPane().add(lbl);
}
}
when the program is run in netbeans the applet window is showing but no gui elements can not be seen like buttons.and in the console i can see that a exception has been caught by the try catch block.why am i getting this exception and what can i do so that this does not occur.
You've got a NullPointerException that you're not seeing because you're not catching exceptions correctly. You must assign objects to your reference variables, including your JButton and JLabel variables, before trying to use them.
In other words, change
JButton b1;
JButton b2;
JLabel lbl;
to
JButton b1 = new JButton("something");
JButton b2 = new JButton("something else");
JLabel lbl = new JLabel("something else entirely");
Also to capture the missed target exception, consider doing:
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
guiInit();
}
});
} catch (InvocationTargetException e) {
e.getTargetException().printStackTrace(); // get the target exception
} catch (InterruptedException e) {
e.printStackTrace();
}