Why does calling a JPanel from other class give NullPointerException error? - java

I am a newbie at Java GUI,and I'm trying to make my first visual game.A window including two buttons pops up when we run the program,and if you click on one of them,the game starts.At first,I had created a class extending JPanel so my first panel would be created and I would create an object of the class and add it to the JFrame.But I needed to change the panel when the buttons would be clicked,so I created a new JPanel object JPanel in my main game class.
Because the second JPanel was created in a different way,I made my first JPanel into a similar JPanel and put getter and setter to my frame class.But the code gives me NullPointerException error.
Here are my classes:
public class Frame {
//The constructor method for frame.
private static JPanel panel;
public Frame () {
JFrame frame = new JFrame();
frame.add(panel); //Adding the panel of the game to the frame.
frame.setTitle("Halma Game"); //The title of the window popped up when the program runs.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static JPanel getPanel() {
return panel;
}
public static void setPanel(JPanel panel) {
Frame.panel = panel;
}
}
public class MenuPanel extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton playButton;
private JButton recordButton;
private JLabel label;
private JPanel panel = new JPanel();
public MenuPanel() {
panel.setBorder(BorderFactory.createEmptyBorder(300,400,300,400));
panel.setLayout(new GridLayout(0,1));
panel.setBackground(Color.decode("255128255"));
playButton = new JButton("New Game");
playButton.setFocusable(false);
playButton.setBackground(Color.PINK);
playButton.setFont(new Font("Ariel",Font.ITALIC,25));
playButton.addActionListener(this); //??? //Mohreha ro ye abstact beheshon bezani khoobe
panel.add(playButton);
recordButton = new JButton("HighScores");
recordButton.setFocusable(false);
recordButton.setBackground(Color.pink);
playButton.setFont(new Font("Ariel",Font.ITALIC,25));
panel.add(recordButton);
label = new JLabel();
}
#Override
public void actionPerformed(ActionEvent e) {
GamePanel game = new GamePanel();
game.start();
}
}
I haven't yet tried the second JPanel on this code,but this one doesn't seem to work.

hi Elena your panel has not been instantiated yet
private static JPanel panel;
when u call
frame.add(panel); //Adding the panel of the game to the frame.

Related

How to prevent additional JFrames when that class is being extended by other classes

I am making a buzzlike game in which the main problem is when the class, where i create the JFrame and panels, is being extended from other classes because by creating an item of that class, i have +1 frame. So i have additional frames i dont want. The code is this:
public static void main(String[] args) {
GameStart game;
game = new GameStart();
game.gReady();
}
public class GameStart extends JFrame{
protected JPanel panel, headline;
protected BorderLayout border;
protected GridLayout grid, head;
protected JLabel question;
protected JButton[] button;
protected JLabel label;
protected JLabel empty;
public GameStart(){
setSize(500,400);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
panel = new JPanel();
headline = new JPanel();
question = new JLabel();
button = new JButton[4];
for(int i=0;i<4;i++){
button[i] = new JButton();
panel.add(button[i]);
}
label = new JLabel();
empty = new JLabel();
border = new BorderLayout();
grid = new GridLayout(4,1);
head = new GridLayout(1,0);
headline.add(question);
headline.setLayout(head);
setLayout(border);
panel.setLayout(grid);
add(panel, BorderLayout.WEST);
add(headline, BorderLayout.PAGE_START);
panel.setVisible(true);
headline.setVisible(true);
setVisible(true);
}
This is the problematic class as i tried to find out
public void gReady(){
GameMenu game;
game = new GameMenu();
game.languageMenu();
}
The languageMenu() can even be empty but GameMenu() needs to extend GameStart(). Is there any way to prevent other "child" classes from creating extra frames?
public class GameMenu extends GameStart {
public GameMenu(){}
public void languageMenu(){}
}
Because you call setVisable in the constructor of GameStart so it pops up when you create it.
Remove it from there and call it only when you want to show that JFrame.
Also, why do you extend it with GameMenu? just create different JFrame

Java GUI - buttons will not add to panel

Hello I am having a problem adding buttons to my GUI, I try to use BorderLayout to add the buttons but it does not show when I run. Since using BorderLayout my choice of background color reverts to white as well. Can anyone please help?
import javax.swing.*;
import java.awt.*;
public class BlackjackGUI{
private JFrame frame;
private JPanel panel;
private JButton newGameBtn, dealBtn, hitBtn, standBtn;
private JLabel playerMoneyLbl;
private JLabel playerCard1Lbl, playerCard2Lbl, playerCard3Lbl,
playerCard4Lbl, playerCard5Lbl, playerCard6Lbl, playerCard7Lbl;
private JLabel dealerCard1Lbl, dealerCard2Lbl, dealerCard3Lbl, dealerCard4Lbl,
dealerCard5Lbl, dealerCard6Lbl, dealerCard7Lbl;
private JLabel playerCardValueLbl, dealerCardValueLbl;
private JTextField betInputBox;
public BlackjackGUI(){
createForm();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createForm() {
JFrame frame = new JFrame("Blackjack");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200,800);
frame.setVisible(true);
JPanel panel = new JPanel();
Color c = new Color(0, 100, 0);
panel.setBackground(c);
panel.setLayout(new BorderLayout());
}
public void addButtons() {
newGameBtn = new JButton("New Game");
panel.add(newGameBtn, BorderLayout.NORTH);
}
public static void main(String[] args) {
new BlackjackGUI();
}
}

How to change CardLayout panels from a separate panel?

My software layout is kinda wizard-base. So the base panel is divided into two JPanels. One left panel which never changes. And one right panel that works with CardLayout. It has many sub-panels and show each one of them by a method.
I can easily go from one inner panel to another one. But I want to have a button in left panel and change panels of the right side.
Here is a sample code which you can run it:
BASE:
public class Base {
JFrame frame = new JFrame("Panel");
BorderLayout bl = new BorderLayout();
public Base(){
frame.setLayout(bl);
frame.setSize(800, 600);
frame.add(new LeftBar(), BorderLayout.WEST);
frame.add(new MainPanel(), BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
new Base();
}
}
Left side
public class LeftBar extends JPanel{
JButton button;
MainPanel mainPanel = new MainPanel();
public LeftBar(){
setPreferredSize(new Dimension(200, 40));
setLayout(new BorderLayout());
setBackground(Color.black);
button = new JButton("Show Second Page");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
mainPanel.showPanel("secondPage");
}
});
add(button, BorderLayout.NORTH);
}
}
Right Side
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel(){
FirstPage firstPage = new FirstPage(this);
SecondPage secondPage = new SecondPage(this);
setLayout(new GridLayout(0,1));
panelHolder.add(firstPage, "firstPage");
panelHolder.add(secondPage, "secondPage");
cl.show(panelHolder, "firstPage");
add(panelHolder);
}
public void showPanel(String panelIdentifier){
cl.show(panelHolder, panelIdentifier);
}
}
Inner panels for right side:
public class FirstPage extends JPanel {
MainPanel mainPanel;
JButton button;
public FirstPage(MainPanel mainPanel) {
this.mainPanel = mainPanel;
setBackground(Color.GRAY);
button = new JButton("Show page");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
mainPanel.showPanel("secondPage");
}
});
add(button);
}
}
public class SecondPage extends JPanel{
MainPanel mainPanel;
JButton button;
public SecondPage(MainPanel mainPanel){
this.mainPanel = mainPanel;
setBackground(Color.white);
add(new JLabel("This is second page"));
}
}
And this is a picture to give you the idea:
As I explained, I can travel "from first" page to "second page" by using this method: mainPanel.showPanel("secondPage"); or mainPanel.showPanel("firstPage");.
But I also have a JButton in the left bar, which I call the same method to show the second panel of the CardLayout. But it does not work. It doesnt give any error though.
Any idea how to change these CardLayout panels from outside of panels?
The problem is that LeftBar has mainPanel member that is initialized to a new instance of MainPanel. So you have two instances of MainPanel, one allocated in Base and added to the frame, the other one allocated in LeftBar.
So LeftBar executes mainPanel.showPanel("secondPage"); on a second instance of MainPanel which is not even a part of a visual hierarchy. To fix this just pass an existing instance of MainPanel to the constructor of LeftBar. You already do this in FirstPage and SecondPage.

Button and textfield don't show up in Java

For school I had to make a JFrame and within that One button and Two textfields. Whatever you put in Textfield one have to get into textfield two when the button is pressed. I got the code to the point I should see the textfields and the button when i run the program. For whatever reason it doesn't.
My come so far:
package helloworld;
import javax.swing.*;
import java.awt.event.*;
public class HelloWorld extends JFrame {
public static void main(String[] args) {
JFrame frame = new HelloWorld();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hello World Button App");
JPanel panel = new JPanel();
frame.setContentPane(panel);
fram.setVisible(true);
}
}
class panel extends JPanel {
public JButton btn1 = new JButton("Klick!");
public JTextField txt1 = new JTextField(10);
public JTextField txt2 = new JTextField(10);
public panel() {
add(btn1);
add(txt1);
add(txt2);
}
}
I am not yet allowed to post images but I will provide a link to the picture down here
I am sorry if this question allready exests but i couldnt's find a similar question.
I am new to programming so please dont yell at me when I forgot something or wrote something wrong in it!
Here i have modified your code a bit, but did in a similar way.
I won't extend JFrame until and unless i don't want to do something creative, but you always CAN.
You had already extended JFrame , so no worth of calling methods with frame.foo()
but simply foo() , and most important JFrame frame = new HelloWorld() , will make no sense, if you have already extended you class with JFrame:
import javax.swing.*;
public class HelloWorld extends JFrame{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new HelloWorld().setVisible(true);
}
});
}
public HelloWorld()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Hello World Button App");
panel pan= new panel();
add(pan.panel);
pack();
setVisible(true);
}
}
class panel {
private JButton btn1 = new JButton("Klick!");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
JPanel panel;
public panel() {
panel = new JPanel();
panel.add(btn1);
panel.add(txt1);
panel.add(txt2);
}
}
Also, you can also extend your panel class with JPanel :
public HelloWorld()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Hello World Button App");
panel pan= new panel();
add(pan);
pack();
setVisible(true);
}
}
class panel extends JPanel {
private JButton btn1 = new JButton("Klick!");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
public panel() {
add(btn1);
add(txt1);
add(txt2);
}
}
That is because your class name is panel not JPanel
Modify this:
panel panel = new panel();
frame.setContentPane(panel);
frame.setVisible(true);
You should try to use names for your Class that are not so confusing, and try to declare them with uppercase.
Example:
Class Panel extends JPanel {}
Object:
Panel panel = new Panel()
Here you can clearly read which one is the class name and which is the object (instance of that class) of that class.
You declared a class called panel that you are not using anywhere. Please replace the line bwlow:
JPanel panel = new JPanel();
with:
SomePanel panel = new SomePanel();
Then, your class panel becomes SomePanel to follow correct class naming.
Some thoughts to help you:
Name your classes following the Java style
Don't use public fields
Set layouts on your panels. This time it worked for you as the default is FlowLayout.

Add Jpanel to Jframe NetBeans

Hi all, I was in a development of my college mini project. It was a Library Management system , which i should do in Java swing using Net-beans IDE. First I was doing manual coding. It takes time.
In manual coding I create single JFrame with Menu bar and and items, on all action performed I wrote codes for all Jpanels. It made the file and code huge. and confusing too.
Now I need your help.
I have created a Main JFrame with Menu
A JPanel - ADD Book
another Jpanel - On add book success (demo! , for Actions happening in ADD Book )
I had made action listener
addBook addbk = new addBook();
this.getContentPane().add(addbk);
wrote this code.
I doesn't make sense.
Friends, As a new to java, What i need to study is
1.) How cal and Show an external Jpanel an action performed
2.) How to show another JPanel to same root JFrame if any event has occurred in external JPanel.
In sort, something like Iframe in HTML
Thank you all.
http://compilr.com/abelkbil/openlib/OpenLibMainGUI.java
http://compilr.com/abelkbil/openlib/addBook.java
http://compilr.com/abelkbil/openlib/bookAdded.java
CardLayout, is exactly what you need for this situation. And do learn Java Naming Conventions and stick to them, as you are a beginner, so to be on the right track from the start is always GOOD.
Here is one example, that you can look at :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel panel2;
private MyPanel panel3;
private JComboBox choiceBox;
private String[] choices = {
"Panel 1",
"Panel 2",
"Panel 3"
};
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
choiceBox = new JComboBox(choices);
panel1 = new MyPanel(contentPane
, Color.RED.darker().darker(), this);
panel2 = new MyPanel(contentPane
, Color.GREEN.darker().darker(), this);
panel3 = new MyPanel(contentPane
, Color.DARK_GRAY, this);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
contentPane.add(panel3, "Panel 3");
frame.getContentPane().add(choiceBox, BorderLayout.PAGE_START);
frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JComboBox getChoiceBox()
{
return choiceBox;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
private Color backgroundColour;
private JComboBox choiceBox;
public MyPanel(JPanel panel, Color c, CardLayoutExample cle)
{
contentPane = panel;
backgroundColour = c;
choiceBox = cle.getChoiceBox();
setOpaque(true);
setBackground(backgroundColour);
//construct components
jcomp1 = new JButton ("Show New Panel");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String changeToPanel = (String) choiceBox.getSelectedItem();
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, changeToPanel);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
Else you can have a look at this example also.

Categories

Resources