This code is part of a Tic Tac Toe program that I'm making with Java Swing. Why does it return NullPointerException when the for statement to add the buttons is added?
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TicTacToeGui extends JFrame
{
public final static int r = 3;
public final static int c = 3;
TicTacToeGui()
{
JButton[][] button = new JButton[3][3];
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(r, c));
JLabel label = new JLabel("This is a tic tac toe game.");
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
panel.add(button[i][j]);
}
}
this.add(label);
this.add(panel);
this.setSize(400, 400);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String [] args)
{
new TicTacToeGui();
}
}
You never initialize any JButton. When you declare
JButton[][] button = new JButton[3][3];
It just creates an empty 3x3 array of null, and you have to manually go through each spot in your array of arrays and initialize with
button[row][col] = new JButton("");
because button[0][0] is null. You initialize the array but none of the elements in it.
The line JButton[][] button = new JButton[3][3]; doesn't actually initialize the buttons. You need to create new buttons and stick them in here.
Related
When I placed an array into mainJpanel it works correctly. I want to place an array into JScrollPane but it does not work. Please explain why.
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
public Window() {
setLocation( 100,100);
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("FontView");
setVisible(true);
setLayout( new FlowLayout());
JPanel mainPanel = new JPanel();
setContentPane(mainPanel);
Method fontMassive = new Method();
//поехали
JPanel[] jPanels = new JPanel[3];
JLabel[] jLabels = new JLabel[3];
for (int i = 0; i < 3; i++) {
jPanels[i]=new JPanel();
jLabels[i] = new JLabel(fontMassive.getFonts(i));
jPanels[i].add(jLabels[i]);
}
JScrollPane scroll = new JScrollPane();
for (int i = 0; i < 3; i++) {
scroll.add(jPanels[i]);
}
mainPanel.add(scroll);
}
}
placed into mainPanel
placed into scroll
Just another Java programmer 's answer was right, i need to place an array into Panel and then place it into Srcoll.
Thank you guys for the answers.
Hi guys I'm using Eclipse and I'm trying to create a Connect4 Game Grid , which is an JPanel gridArray [6] [7]. I later add the different Panels for buttons and the grid into a main panel and add it into my frame.
My Problem:
I want to fill the gridArray JPanel with Pictures of an empty field(white color) but first of all i want to create a new Panel and insert it into my gridArray through a loop until gridArray has all 42 Panels inside it and is fully filled. I have my Code below but somehow it doesnt work, although my logic should be fine.
I tried it with using a helper Function to create a new JPanel and call the function for each loop in fillGrid();, basically calling it 42 times but it still wont work...
I will gladly appreciate some help!
package connect4;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GridTest extends JFrame {
JFrame mainWindow;
JPanel buttonPanel, mainPanel;
JPanel gridPanel;
JPanel emptyPanel;
JPanel panel1;
ImageIcon emptyBox;
JPanel[][] gridArray;
JLabel emptyLabel;
JButton arrow1,arrow2,arrow3,arrow4,arrow5,arrow6,arrow7;
public GridTest() {
createGameGrid();
fillGrid();
}
public void createGameGrid() {
//creating window and mainpanel
mainWindow = new JFrame("Connect 4");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
//defining top panel with 7 buttons;
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 7));
arrow1 = new JButton("V");
arrow2 = new JButton("V");
arrow3 = new JButton("V");
arrow4 = new JButton("V");
arrow5 = new JButton("V");
arrow6 = new JButton("V");
arrow7 = new JButton("V");
buttonPanel.add(arrow1);
buttonPanel.add(arrow2);
buttonPanel.add(arrow3);
buttonPanel.add(arrow4);
buttonPanel.add(arrow5);
buttonPanel.add(arrow6);
buttonPanel.add(arrow7);
//create Grind Panel
gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(6,7));
mainPanel.add(buttonPanel, BorderLayout.NORTH);
mainPanel.add(gridPanel, BorderLayout.SOUTH);
mainWindow.add(mainPanel);
mainWindow.pack();
mainWindow.setLocationRelativeTo(null);
mainWindow.setVisible(true);
}
private JPanel greateOnePanel(){
//here we need to insert the icon which is in empty box into a newly created panel
//ifirst wanted to insert black panels do ensure it works as intended but it doesnt
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.setSize(50,50);
return panel;
}
//here we need to fill the grid with the panels created above from left to right...
public void fillGrid() {
for(int j = 0; j < 6; j++) {
for (int k = 0; k < 7; k++) {
gridPanel.add(greateOnePanel());
}
}
}
public static void main(String[] args) {
new GridTest();
}
}
i tried it with this method using gridArray, but it throws NullPointer Exeptions and wont fill the grid with simple textlabels "Hallo" (just for testing purposes)
public void fillGrid() {
for(int j = 0; j < 6; j++) {
for (int k = 0; k < 7; k++) {
JLabel label = new JLabel("Hallo");
gridArray[j][k] = new JPanel();
gridArray[j][k].setSize(50, 50);
gridArray[j][k].setBackground(Color.RED);
gridArray[j][k].add(label);
gridPanel.add(gridArray[j][k]);
}
}
}
Here is a short, self contained, code that should help with various aspects of the task.
There is no need for a panel in each cell. The only thing it helped with was setting a BG color. That can be done in a label as long as the background is set to opaque.
This code defines a SquareLabel which overrides getPreferredSize() to return the maximum of preferred width and height as the value of both (usually it is the width).
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class SquareLabelGrid {
int rows = 6;
int cols = 7;
JLabel[][] labelArray = new JLabel[cols][rows];
Font bigFont = new Font(Font.SANS_SERIF, Font.BOLD, 30);
Insets labelInsets;
SquareLabelGrid() {
JPanel gameBoard = new JPanel(new GridLayout(rows, cols));
// a border to make the cell boundaries more clear and add
// some space around the text
Border border = new CompoundBorder(
new LineBorder(Color.BLACK),new EmptyBorder(4,4,4,4));
for (int yy = 0; yy < rows; yy++) {
for (int xx = 0; xx < cols; xx++) {
JLabel l = getColoredSquareLabel(xx, yy);
labelArray[xx][yy] = l;
gameBoard.add(l);
l.setBorder(border);
}
}
JOptionPane.showMessageDialog(null, gameBoard);
}
private JLabel getColoredSquareLabel(int x, int y) {
SquareLabel label = new SquareLabel(
String.format("%1s,%1s", (x+1), (y+1)));
label.setFont(bigFont);
label.setOpaque(true); // so we can see the BG color
label.setBackground(Color.ORANGE); // I prefer orange!
// make the GUI less 'crowded'
label.setBorder(new EmptyBorder(4,4,4,4));
return label;
}
public static void main(String[] args) {
Runnable r = () -> {
new SquareLabelGrid();
};
SwingUtilities.invokeLater(r);
}
}
class SquareLabel extends JLabel {
SquareLabel(String label) {
super(label);
}
/* This will create a square component that accounts for the
size of the String / Icon it contains. No guesswork! */
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int w = d.width;
int h = d.height;
int sz = w > h ? w : h;
return new Dimension(sz, sz);
}
}
The problem is that you have not initialized the grid array .
Otherwise it will throw Null pointer exception.
JPanel[][] gridArray = new JPanel[6][8];
Also set the preferred size of main panel to make the grids visible .
mainPanel.setPreferredSize(new Dimension(400, 200));
Here is what i can see when I run your code with the modifications mentioned here .
Also please execute it from main with following code .
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GridTest();
}
});
}
I was creating a Java Calculator with GUI. I created the JPanel of buttons using arrays, but I notice from the start that when the window appears, the buttons load after 3-4 seconds. I checked everything I could but can't find the problem. Here's the code:
Main
package main;
import ui.Calculator;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setVisible(true);
calculator.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Calculator
package ui;
import javax.swing.*;
import java.awt.*;
public class Calculator extends JFrame {
public Calculator() {
super("Calculator");
setSize(400, 400);
setLocation(400, 400);
setLayout(new BorderLayout());
Buttons buttons = new Buttons();
add(buttons);
}
}
Buttons This is what I think, the root of the problem
package ui;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
/**
* Creates a JPanel with the buttons that is going to be on the Window
*/
class Buttons extends JPanel{
private static JButton[] numbers = new JButton[10];
private static JButton bdot, bsum, bsubstract, bdivide, bmultiply, bequal;
Buttons() {
initializeButtons();
JButton[] buttonNumbers = {numbers[7], numbers[8], numbers[9], bdivide, numbers[4], numbers[5], numbers[6], bmultiply,
numbers[1], numbers[2], numbers[3], bsubstract, numbers[0], bdot, bsum, bequal};
setLayout(new GridLayout(4, 4));
int counter = 0;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
add(buttonNumbers[counter]);
counter ++;
}
}
}
/**
* Function that initialize all the buttons with their respective text
*/
private static void initializeButtons() {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = new JButton("" + i);
}
bdot = new JButton(".");
bsum = new JButton("+");
bsubstract = new JButton("-");
bdivide = new JButton("/");
bmultiply = new JButton("*");
bequal = new JButton("=");
}
}
Note: I know that there are other ways to do this, but I just can't find the problem with this approach, I hope you can help me, thank you.
I want to have a for loop, that can implement and add a specified number of JButtons the one after the other. I was trying to implement it and this is my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ArrayForm extends JFrame implements ActionListener
{
JPanel numPanel = new JPanel();
JPanel opPanel = new JPanel();
JTextField textField = new JTextField(25);
JButton [] buttons = new JButton[10];
JButton [] OPbuttons = new JButton[6];
String num="";
String [] operation = {"+","-","*","/","=","C"};
public static void main(String[] args)
{ArrayForm fobject = new ArrayForm();}
public ArrayForm()
{
setLayout(new FlowLayout());
setSize(400,300);
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
numPanel.setPreferredSize(new Dimension(180,150));
numPanel.setLayout(new FlowLayout());
opPanel.setPreferredSize(new Dimension(200,70));
opPanel.setLayout(new FlowLayout());
for (int i = 0; i<10; i++)
{
//The code in here
}
for (int i = 0; i<6; i++)
{
//The code in here
}
add(textField);
this.textField.setEditable(false);
add(numPanel);
add(opPanel);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
}
}
Can you please help me with for loop part? where the first one is buttons array, and the second one is for OPbuttons array.
Your for loop part might be as follows:
for (int i = 0; i<10; i++)
{
buttons[i] = new JButton(""+i);
numPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
for (int i = 0; i<6; i++)
{
OPbuttons[i] = new JButton(operation[i]);
opPanel.add(OPbuttons[i]);
OPbuttons[i].addActionListener(this);
}
What i have understood, is that you are trying to add the buttons of a calculator automatically, within two different panels...
NB: don't forget to add the code for your Action Listener.
So I'm new to Java and im definitely new to Swing.
I've got a 80 X 80 array thats going to be used by a maze. I need my gui to have 80 X 80 buttons so they can be tied to the values in my array.
I cant figure out why I'm only getting five or six large buttons from this code. If anyone can tell me how I can get this to work then thank you in advance because I'm stumped.
Just run it and you'll see what I mean...also I guess I've not figured out how to change the color of the buttons and I changed the background color instead.
Heres my code:
public static void draw() {
JFrame f = new JFrame();
f.setTitle("Maze");
f.setSize(800, 800);
f.setVisible(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel c = (JPanel)f.getContentPane();
GridLayout gridLayout = new GridLayout();
c.setLayout(gridLayout);
for(int i =0;i<80;i++){
for(int j =0;j<80;j++){
JButton b = new JButton();
c.add(b, i,j);
b.setSize(10, 10);
b.setOpaque(true);
b.setBackground(Color.red);
}
}
}
}
80 * 10 > f.setSize(800, 800); and your code is not possible to fit in FullHd monitor
use f.pack() instead of f.setSize(800, 800);
f.pack() and f.setVisible(true); (could be a main issue) should be last code lines in non_static and renamed to !public void DrawMe() {!, because draw() is reserved word for/in Java API
c.add(b, i,j); should be last code line too (logical ordering),
c.add(b, i,j); set row and columns for GridLayout instead of injecting the JButton to virtual grid in GridLayout
make me some sense (starting with the numbers of elements)
from
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DrawMe {
private JFrame frame = new JFrame();
private JPanel c = new JPanel();
private static final int column = 10;
private static final int row = 10;
public DrawMe() {
c.setLayout(new GridLayout(row, column));
for (int i = 0; i < column; i++) {
for (int j = 0; j < row; j++) {
JButton b = new JButton((i + 1) + " " + (j + 1));
c.add(b);
}
}
frame.add(c);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DrawMe();
}
});
}
}