What is a Java NullPointerException? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I created a Java Application and get this Exception:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Executer.<init>(Executer.java:21)
at Executer.main(Executer.java:14
Here is the code:
import javax.swing.*;
import java.awt.*;
public class Executer {
private JLabel lblCommand;
private JTextField txtEnter;
private JButton btNext, btPrevious;
private JPanel panel;
public static void main(String[] args) {
new Executer();
}
public Executer() {
JFrame frame = new JFrame("Execute Script");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
frame.add(panel);
frame.setVisible(true);
MyPanel();
Text();
Buttons();
Fields();
}
public void MyPanel() {
panel = new JPanel();
panel.setLayout(null);
}
public void Text(){
lblCommand = new JLabel("Enter Here");
lblCommand.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblCommand.setFont(styleOne);
panel.add(lblCommand);
}
public void Fields () {
txtEnter = new JTextField();
txtEnter.setBounds(210, 50, 150, 20);
panel.add(txtEnter);
}
public void Buttons() {
btNext = new JButton ("Next");
btNext.setBounds(380,325,100,20);
panel.add(btNext);
btPrevious = new JButton ("Previous");
btPrevious.setBounds(260,325,100,20);
panel.add(btPrevious);
}}
What is a NullPointerException? How would I find out?

You need to instantiate panel before adding it. If you use panel before calling MyPanel(), panel is still null, hence the NullPointerException.
While you're here, give this a glance. http://geosoft.no/development/javastyle.html
Method names in Java should be mixed case starting with a lower case letter, e.g. myPanel() instead of MyPanel(). To most of us, MyPanel() looks like a constructor at first glance because you improperly styled it.
Additionally, MyPanel, Text, Fields, and Buttons should all be private methods, as it would be improper for an external class to call them.

Problem in this line frame.add(panel); Panel is not initialized at that point, move this line MyPanel(); before adding to initialize it.

As others have said, you need to create the JPanel before you try to add it to the JFrame. In fact, you should typically create all components inside the JPanel as well. I suggest that you move the calls to
Text();
Buttons();
Fields();
from the Executer constructor to the MyPanel() method and call MyPanel() before calling frame.add(panel);.
In addition, you do not need to call frame.setVisible(true); twice. Also, you should use a LayoutManager rather than calling panel.setLayout(null);. See the Oracle tutorial for Using Layout Managers.

Yes you are adding panel to the frame before creating object of JPanel. Anyway change your constructor with this:
public Executer() {
JFrame frame = new JFrame("Execute Script");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900, 400);
MyPanel();
Text();
Buttons();
Fields();
frame.add(panel);
frame.setVisible(true);
}
thanks.

Related

How to make a JButtons appear

I want to make a JButton that lies on the NorthPane of the frame, but when I run the program there's no button. Why does it do that?
I'm using IntelliJ IDEA.
BTW I'm posting this question again, cause the first time I didn't get the desired answer.
Here's my code.
package com.company;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
class Fantasyrpglifesim implements JButton {
Fantasyrpglifesim() {
}
public static void main(String[] args) {
MouseInputAdapter();
//Frame//
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.setSize(1500, 1500);
frame.getContentPane();
frame.setVisible(true);
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel northPanel = new JPanel();
mainPanel.add(northPanel,BorderLayout.NORTH );
//frame.setLayout(new FlowLayout());//
//Buttons//
frame.add(BUTTON);
BUTTON.setText("Age up");
northPanel.add(BUTTON);
northPanel.add(BUTTON1);
BUTTON1.setText("Test");
northPanel.add(BUTTON2);
BUTTON2.setText("Test1");
northPanel.add(BUTTON2);
BUTTON2.setText("Test2");
northPanel.add(BUTTON3);
BUTTON3.setText("Test3");
northPanel.add(BUTTON4);
BUTTON4.setText("Test4");
northPanel.add(BUTTON5);
BUTTON5.setText("Test5");
northPanel.add(BUTTON6);
BUTTON6.setText("Test6");
northPanel.add(BUTTON7);
BUTTON7.setText("Test7");
northPanel.add(BUTTON8);
BUTTON8.setText("Test8");
northPanel.add(BUTTON9);
BUTTON9.setText("Test9");
northPanel.add(BUTTON10);
BUTTON10.setText("Test10");
northPanel.add(BUTTON11);
BUTTON11.setText("Test11");
northPanel.add(BUTTON12);
BUTTON12.setText("Test12");
northPanel.add(BUTTON13);
BUTTON13.setText("Test13");
northPanel.setVisible(true);
//panels//
//mainPanel.add(northPanel, BorderLayout.NORTH);//
}
private static void MouseInputAdapter() {
}
}
to add a JButton you have to create a JButton object and add that to the JPanel.
And you need to define it for EVERY button that you want to have.
anywhere. I'm surprised your compiler isn't flagging that
Anyway what you want should look sth like this
JButton testButton = new JButton("test");
northPanel.add(testButton);
First, I want you to check your compiler and IntelliJ cause they're not working if you can run the code you posted.
You cannot implement a JButton unless you have made an interface yourself.
Cause the JButton is not an interface.
No need to set a BorderLayout for your JPanel. FlowLayout will do the job.
Use a for loop to avoid duplicate code.
Learn how to use Swing components.
import javax.swing.*;
import java.awt.*;
class Fantasyrpglifesim {
private static int count = 1;
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton age = new JButton("Age up");
mainPanel.add(age);
for (int x=0; x<14;x++){
JButton button = new JButton();
button.setText("Test"+ count++);
mainPanel.add(button);
}
frame.getContentPane().add(BorderLayout.NORTH,mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1500, 1500);
frame.setVisible(true);
}
}
Is this your desired output?

Why is the GUI not working, is the code correct?

So Im trying to create 3 panels. The first panel has the layout set (e.g. the radio buttons and next button) I`m now adding two new panels which have different background colors. But when I execute the code I get an error of Null point exception. How do I fix that?
Here is the code:
import java.awt.Color;import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.CardLayout;
import javax.swing.*;
public class Wizard {
private JLabel lblPicture;
private JRadioButton btLdap, btKerbegos, btSpnego, btSaml2;
private JButton btNext;
private JPanel panel;
private JPanel panelFirst;
private JPanel panelSecond;
CardLayout c1 = new CardLayout();
public static void main(String[] args) {
new Wizard();
}
public Wizard() {
JFrame frame = new JFrame("Wizard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,360);
frame.setVisible(true);
MyPanel();
RadioButtons();
Button();
Image();
groupButton();
panel.setLayout(c1);
panelFirst.setBackground(Color.BLUE);
panelSecond.setBackground(Color.GREEN);
panel.add(panelFirst,"1");
panel.add(panelSecond,"2");
c1.show(panel,"panel");
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public void MyPanel() {
panel = new JPanel();
panel.setLayout(null);
}
public void RadioButtons() {
btLdap = new JRadioButton ("Ldap");
btLdap.setBounds(60,85,100,20);
panel.add(btLdap);
btKerbegos = new JRadioButton ("Kerbegos");
btKerbegos.setBounds(60,115,100,20);
panel.add(btKerbegos);
btSpnego =new JRadioButton("Spnego");
btSpnego.setBounds(60,145,100,20);
panel.add(btSpnego);
btSaml2 = new JRadioButton("Saml2");
btSaml2.setBounds(60,175,100,20);
panel.add(btSaml2);
}
public void Button() {
btNext = new JButton ("Next");
btNext.setBounds(400,260,100,20);
panel.add(btNext);
btNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
c1.show(panel, "2");
}
});
}
public void Image() {
ImageIcon image = new ImageIcon("image.jpg");
lblPicture = new JLabel(image);
lblPicture.setBounds(200,20, 330, 270);
panel.add(lblPicture);
}
private void groupButton() {
ButtonGroup bg1 = new ButtonGroup( );
bg1.add(btLdap);
bg1.add(btKerbegos);
bg1.add(btSpnego);
bg1.add(btSaml2);
}
}
When I go to run your code I get the null pointer exception you mentioned:
Exception in thread "main" java.lang.NullPointerException
at Wizard.<init>(Wizard.java:35)
at Wizard.main(Wizard.java:20)
So, I looked up the line that produced it, in the constructor for Wizard:
panelFirst.setBackground(Color.BLUE);
I see you are setting a property on panelFirst, which is an instance data member of the Wizard class.
I don't see anywhere where you declared panelFirst = new JPanel();, which is what created your NullPointerException. It also looks like you haven't initialized many of the other variables as well (for instance, panel is the only JPanel I see that has been initialized).
Please look up the constructors for JPanel in the Java API and see how you want to create them for your app. You may also consider using an IDE to generate the GUI code for you.
JPanel API (as of jdk 1.7): http://docs.oracle.com/javase/7/docs/api/javax/swing/JPanel.html
Thanks
panelFirst and panelSecond objects are never created.
panelFirst and panelSecond variable is null it is not declared.
before setting background of panel you need to create it:
panelFirst= new JPanel();
same thing with panelSecond:
panelSecond = new JPanel();
When you have a null pointer exception (also known as NPE): you should try to find an uninitialized variable. When a variable is declared but not initialized its pointer is pointing to null (i.e it is a null pointer!)

JFrame Button Logic error

I've been spending some time relearning java and a peculiar logic error hit me here.
import javax.swing.*;
import java.awt.*;
class Frame
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
Container content = frame.getContentPane();
content.setBackground(Color.blue);
content.add(btn1);
content.add(btn2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//end main
}
I've created 2 JButton objects, and they should be the same size, with different location and text. This of course is not the case, the "FOO" button is exactly where and how I want it to be, but the "BAR" button is the size of the entire frame.
Help!
1) You are attempting to use Absolute LayoutManager via setSize and setLocation etc, but without calling setLayout(null) on the component you are adding the JButtons to. However this is not a best practice in Swing.
When adding to JFrame contentpane default layout is BorderLayout which adds components to is default position of BorderLayout.CENTER.
Have a read on A Visual Guide to Layout Managers
2) Also when using a correct LayoutManager you would omit JFrame#setSize(..) call and replace it with JFrame#pack() before setting the JFrame visible.
3) Also have a read on Concurrency in Swing specifically on The Event Dispatch Thread
which dictates all swing components be created on EDT via SwingUtillities.invokeXXX(..) block:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//create and manipulate swing components here
}
});
4) Also rather use JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); as this will allow any other threads timers etc to carry on execution even after JFrame has been disposed.
add:
frame.getContentPane().setLayout(null);
To your code after the line:
frame.setSize(400, 500);
Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order).In your code the buttons are stacked over the other.That is why you get this Error(as you think it is).
This will solve your problem:-
import javax.swing.*;
import java.awt.*;
class OP3
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
JPanel p = new JPanel(new FlowLayout());
p.add(btn1);
p.add(btn2);
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//end main
}
Just add a panel to the frame and add the buttons to the panel.
import javax.swing.*;
import java.awt.*;
class source
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JPanel panel=new JPanel();//panel added here
panel.setSize(frame.size());
panel.setLocation(0, 0);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
panel.add(btn1);
panel.add(btn2);
Container content = frame.getContentPane();
content.setBackground(Color.blue);
content.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//endmain

frame.add (label, JFrame.TOP) error

i get an error of Exception in thread "main" java.lang.IllegalArgumentException: illegal component position. It works when i do frame.add(label, JFrame.CENTER) but when i change it
it dosnt work.
package com.java;
import javax.swing.*;
import sun.audio.*;
import java.awt.*;
public class PlayClip extends JFrame{
public static void frame(){
JFrame frame = new JFrame("COLLIN");
frame.setSize(1086, 1200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("C:MYFILE");
JLabel label = new JLabel(image);frame.setResizable(false);
frame.add(label, JLabel.BOTTOM);
frame.setVisible(true);
}
public static void main(String[] args){
frame();
}
}
You're using frame.add(label, JLabel.BOTTOM); wrong. The documentation says:
comp - the component to be added
index - the position at which to insert the component, or -1 to append the component to the end
JFrame.CENTER equals 0, by coincidence. That's why it works. TOP and BOTTOM are 1 and 3, respectively. When you use those, it's like getting an index out of bounds error on an array/list.
You should look into using a layout manager because this method isn't for what you think it's for.
This proof of concept probably does what you want:
public static void main(String[] args) {
JFrame frame = new JFrame("COLLIN");
frame.setSize(1086, 1200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("my text", SwingConstants.CENTER);
frame.setResizable(false);
frame.add(label);
frame.setVisible(true);
}
In line frame.add(label, JLabel.BOTTOM); you are assigning an alignment option for frame, not for JLabel. So you should use the constants from JFrame, and not JLabel.
The constants of JLabel are used to align the text inside the label.
Use frame.add(label). That should be enough.

Java Swing Button

I've written this:
JButton saveButton = new JButton(saveAction);
How do I then call it so that it displays within the window? (I've already got the code for the window, I just don't know how to call it so it shows)
saveButton.setVisible(true);
your_window.add(saveButton);
Thats all.
Firstly you should create some ContentPane for window (I guess you mean JFrame). Adding a button directly to window is not a good idea :P Next you can add your button to that pane:
panel.addComponent(button);
The last thing to do is:
frame.setContentPane(panel)
And that's all :P Just in a nutshell ;)
Use something like this
public class MainWindow extends JFrame {
public static void main(String[] args) {
MainWindow frame = new MainWindow();
frame.setVisible(true);
}
public MainWindow() throws IOException {
setTitle("Conveyor");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 851, 515);
contentPane = new JPanel();
JButton refreshButton = new JButton("refresh");
contentPane.add(refreshButton, BorderLayout.EAST);
}
}

Categories

Resources