GUI not displaying content till resized or minimised - java

okay ... my question is rather straight forward so I doubt ill need to add any code but I will if need be.
Whenever I create a GUI frame and add a couple of panels to it and run my application, the contents are not displayed until I either re-size the window or minimize it on the toolbar then restore it. What could be the cause of that and how can I solve it?
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public final class Calculator extends JFrame
{
//initialise various variables for use within the program
//BUTTONS
private final JButton additionButton = new JButton("+");
private final JButton subtractionButton = new JButton("-");
private final JButton divisionButton = new JButton("/");
private final JButton multiplicationButton = new JButton("*");
//PANELS
private JPanel operatorPanel;
private JPanel operandPanel;
//LABELS
private JLabel operationLabel;
//constructor to initialise the frame and add components into it
public Calculator()
{
super("Clancy's Calculator");
setLayout(new BorderLayout(5, 10));
setSize(370, 200);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
//create a message label to display the operation that has just taken place
operationLabel = new JLabel("YOU HAVE PERFORMED SOME OPERATION",SwingConstants.CENTER);
add(getOperatorPanel(), BorderLayout.NORTH);
add(getOperandPanel(), BorderLayout.CENTER);
add(operationLabel, BorderLayout.SOUTH);
}
//setter method for the operator panel
public void setOperatorPanel()
{
operatorPanel = new JPanel();
operatorPanel.setLayout(new FlowLayout());
operatorPanel.add(additionButton);
operatorPanel.add(subtractionButton);
operatorPanel.add(multiplicationButton);
operatorPanel.add(divisionButton);
}
//getter method for the operator panel
public JPanel getOperatorPanel()
{
setOperatorPanel();
return operatorPanel;
}
//setter method for operands panel
public void setOperandPanel()
{
operandPanel = new JPanel();
operandPanel.setLayout(new GridLayout(3, 2, 5, 5));
//LABELS
JLabel operandOneLabel = new JLabel("Enter the first Operand: ");
JLabel operandTwoLabel = new JLabel("Enter the second Operand: ");
JLabel answerLabel = new JLabel("ANSWER: ");
//TEXT FIELDS
JTextField operandOneText = new JTextField(); //retrieves one operand
JTextField operandTwoText = new JTextField(); //retrieves another operand
JTextField answerText = new JTextField(); //displays answer
answerText.setEditable(false); //ensure the answer field is not editable
operandPanel.add(operandOneLabel);
operandPanel.add(operandOneText);
operandPanel.add(operandTwoLabel);
operandPanel.add(operandTwoText);
operandPanel.add(answerLabel);
operandPanel.add(answerText);
}
//getter method for operand panel
public JPanel getOperandPanel()
{
setOperandPanel();
return operandPanel;
}
/** main method */
public static void main(String[] args)
{
new Calculator();
}
}

I notice you're programatically setting a new layout manager. Whenever you add, remove or change a java gui, you need to call invalidate() or revalidate() to make java re-create the GUI. See if calling invalidate() before setVisible(true) fixes the problem

Related

JTextField not fillling up column as expected?

Learning to use MigLayout. I am trying to make a very simple form that is two columns, a label, a text input, repeat, until a submit button on the bottom that should span both columns. However it does not seem to be working as expected. The text fields are not spreading and neither is the button. It looks like this
Here is my code -
package com.mypackage;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import net.miginfocom.swing.MigLayout;
public class DiceOddCalculator extends JFrame {
public DiceOddCalculator(String title) {
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setTitle(title);
//Layout and panel to house components
MigLayout layout = new MigLayout("wrap 2, debug");
JPanel panel = new JPanel(layout);
//Components
JLabel maxDiceLabel = new JLabel("Max value of die");
JTextField maxDiceInput = new JTextField();
JLabel protectionCriteriaLabel = new JLabel("Die protection Criteria:");
JTextField protectionCriteriaInput = new JTextField("");
JLabel numOfDiceLabel = new JLabel("Number of dice:");
JTextField numOfDiceInput = new JTextField("");
JButton addDice = new JButton("Add dice");
//add to panel
panel.add(maxDiceLabel);
panel.add(maxDiceInput);
panel.add(protectionCriteriaLabel);
panel.add(protectionCriteriaInput);
panel.add(numOfDiceLabel);
panel.add(numOfDiceInput);
panel.add(addDice, "span");
//Turn window on
this.setContentPane(panel);
this.setVisible(true);
}
public static void main(String[] args) {
DiceOddCalculator f = new DiceOddCalculator("Dice Odds Simulator");
}
}
What needs to change in my code so that the JTextField and Button are the appropriate widths?
I figured out it had to do with how I was constructing MigLayout. Using
MigLayout layout = new MigLayout("wrap 2, debug", "[fill, grow]", "") made the component stretch across its column as I was expecting.

How can I add new jpanel on already existing in this example?

Stupid question, but I cant seem to find answer, and when I do it doesn't work. So i want to add new JPanel on already existing JPanel. Sometimes when i add it it just opens a new window when I run it, other times nothing happens. Anyways here is the code:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args)
{
new Main().setVisible(true);
}
private Main()
{
super("Vending machine");
JPanel p = new JPanel();
JLabel title = new JLabel("Vending machine: ");
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("5");
JLabel label1 = new JLabel("Enter code: ");
JTextField text1= new JTextField(3);
JButton ok= new JButton("OK");
JButton button4 = new JButton("Return change");
JLabel label2 = new JLabel("Result is: ");
JTextField text2= new JTextField(3);
JLabel label3 = new JLabel("Current: ");
JTextField text3= new JTextField(3);
title.setBounds(200,5,250,80);
title.setFont (title.getFont ().deriveFont (22.0f));
p.add(title);
p.setLayout(null);
button1.setBounds(530,46,120,60);
p.add(button1);
button2.setBounds(530,172,120,60);
p.add(button2);
button3.setBounds(530,298,120,60);
p.add(button3);
label1.setBounds(555,414,120,60);
p.add(label1);
text1.setBounds(530,454,120,30);
p.add(text1);
ok.setBounds(530,550,120,60);
p.add(ok);
button4.setBounds(360,550,120,60);
p.add(button4);
label2.setBounds(230,530,120,60);
p.add(label2);
text2.setBounds(200,575,120,30);
p.add(text2);
label3.setBounds(50,530,120,60);
p.add(label3);
text3.setBounds(38,575,120,30);
p.add(text3);
getContentPane().add(p);
setSize(700,700);
setVisible(true);
}
}
I want to add new JPanel on this place: vending machine:
Thank you!
Even if you could do this, it will give you harm for every time you want another changes on this frame.
Instead of locating a JPanel into another JPanel, use layouts.
You shouldnt use static variables and a null layout.
Use appropriate layout managers. Maybe the main panel uses a BorderLayout. Then you add your main component to the CENTER and a second panel to the EAST. The second panel can also use a BorderLayout. You can then add the two components to the NORTH, CENTER or SOUTH as you require.

How can I get the contents of my GUI to look a certain way? (Java)

So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:

How can I properly align my labels?

More help needed with this little project of mine again, this time trying to get two labels that are inside a panel in certain positions. Those positions being one on the left and then a separation of spaces (like a tab) and then the second label to make way for entries being added below them when a button is pressed which I am also unsure how to start.
I've uploaded an image of the current program running :
As you can see I have two buttons (may change to one at some point) and then a separate results panel with currently two labels inside that I want to move. I want 'Name' to be on the left side and 'Grade' slightly more to the right (separated by about a tabs worth of space). I'm also unsure what the two little lines are so if someone could explain that to me it would be great.
Where I plan to go with this is then for a button entry to lead to a name entry being entered below these labels and a grade entry being entered below these labels which keeps updating with each button press. If anyone could guide me in the right direction for this it would be great. I have provided the code for the panel below.
Thanks for taking the time to read this!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
//Bottom Panel
JPanel GradePanel = new JPanel();
GradePanel.setBorder(BorderFactory.createTitledBorder("Students/Results"));
GradePanel.setOpaque(false);
GradePanel.setPreferredSize(new Dimension(0 , 100));
GradePanel.add(resultField);
resultField.setAlignmentX(LEFT_ALIGNMENT);
GradePanel.add(nameResult);
GradePanel.add(gradeResult);
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(GradePanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and then the driver class:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
Take time to read this the most flexible Layout Manager that commonly used by programmer :)
https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
Btw I separate your class Bottom Panel It's a little bit confused while reading it. Much better try the Nested Classes to look your code clean and easy to read.
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
GridBagConstraints nameResultConstraints = new GridBagConstraints();//Constraints
GridBagConstraints gradeResultConstraints = new GridBagConstraints();//Constraints
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
myBottomPanel mybottompanel = new myBottomPanel();//Object
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(mybottompanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class myBottomPanel extends JPanel{
public myBottomPanel()
{
this.setLayout(new GridBagLayout());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Constraints
GridBagConstraints nameResultConstraints = new GridBagConstraints();
GridBagConstraints gradeResultConstraints = new GridBagConstraints();
//Bottom Panel
setBorder(BorderFactory.createTitledBorder("Students/Results"));
setOpaque(false);
setPreferredSize(new Dimension(0 , 100));
nameResultConstraints.anchor = GridBagConstraints.LINE_START;
nameResultConstraints.weightx = 0.5;
nameResultConstraints.weighty = 0.5;
add(nameResult,nameResultConstraints);
add(gradeResult);
}
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and here is your Frame.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
OUTPUT
Hope this helps. :)
If you want data displayed in a column then you need to use an appropriate layout manager to achieve the effect you want.
Maybe you can use a GridBagLayout. You can have columns and spaces between the columns, but you need to use the appropriate constraints. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.
However, the easier option would be to use a JTable which is a component designed for display data in rows/columns. Again check out the Swing tutorial on How to Use Tables.

Java - Tic Tac Toe Swing game - Errors

I am making a tic tac toe game in Java and made the gui and wanted to run it to test it but am getting a few errors. I am not sure why and was hoping that someone could explain why those errors are coming up and what i should do to fix them. The errors that I am getting are as follows: Exception in thread "main" java.lang.NullPointerException
at TicTacToeSwing.(TicTacToeSwing.java:84)
at TicTacToeSwing.main(TicTacToeSwing.java:180)
Here is my code: (please note: I have not done the calculations yet because I wanted to get the gui going first) If you know of a better practice that I should consider doing, by all means, let me know.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//Tic Tac Toe
public class TicTacToeSwing extends JFrame
implements ActionListener {
//JButtons
//private JButton button1 = new JButton("");
private JButton jbtnTicTacToe1;
private JButton jbtnTicTacToe2;
private JButton jbtnTicTacToe3;
private JButton jbtnTicTacToe4;
private JButton jbtnTicTacToe5;
private JButton jbtnTicTacToe6;
private JButton jbtnTicTacToe7;
private JButton jbtnTicTacToe8;
private JButton jbtnTicTacToe9;
private JButton jbtnExit;
private JButton jbtnReset;
//JFrame window = new JFrame("Tic-Tac-Toe Swing ");
private JFrame window = new JFrame("Tic-Tac-Toe");
//labels
private JLabel jlblPlayerX = new JLabel ("X");
private JLabel jlblPlayerO = new JLabel ("O");
//text fields
JTextField jtfName = new JTextField(20);
private JTextField jtfPlayerX = new JTextField("X");
private JTextField jtfPlayerO = new JTextField("O");
//Panels
JPanel jpnlMain = new JPanel ();
JPanel jpnlFamily = new JPanel();
JPanel jpnlNorth = new JPanel();
JPanel jpnlSouth = new JPanel();
JPanel jpnlCenter = new JPanel();
JPanel jpnlTop = new JPanel();
JPanel jpnlBottom = new JPanel();
//Class Constructor
public TicTacToeSwing () {
//Prepare JFrame/Window
super ("Tic Tac Toe");
setSize(400,400);
setTitle("Tic Tac Toe Swing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set the layouts for 3 rows and 3 columns
jpnlMain.setLayout(new BorderLayout(3,3));
jpnlCenter.setLayout(new GridLayout());
jpnlSouth.setLayout(new GridLayout());
jpnlTop.setLayout(new BorderLayout());
jpnlBottom.setLayout(new BorderLayout());
//Center Panel
jpnlCenter.add(jlblPlayerX);
jpnlCenter.add(jlblPlayerO);
//identify each JButton
jbtnReset.setActionCommand("Reset");
jbtnExit.setActionCommand("Exit");
//register JButton for event handling by using the THIS keyword - THIS class will handle the events
jbtnReset.addActionListener(this);
jbtnExit.addActionListener(this);
/*Add Buttons To The Window*/
window.add(jbtnTicTacToe1);
window.add(jbtnTicTacToe2);
window.add(jbtnTicTacToe3);
window.add(jbtnTicTacToe4);
window.add(jbtnTicTacToe5);
window.add(jbtnTicTacToe6);
window.add(jbtnTicTacToe7);
window.add(jbtnTicTacToe8);
window.add(jbtnTicTacToe9);
/*Add The Action Listener To The Buttons
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
button7.addActionListener(this);
button8.addActionListener(this);
button9.addActionListener(this);
*/
jbtnTicTacToe1.addActionListener(this);
jbtnTicTacToe2.addActionListener(this);
jbtnTicTacToe3.addActionListener(this);
jbtnTicTacToe4.addActionListener(this);
jbtnTicTacToe5.addActionListener(this);
jbtnTicTacToe6.addActionListener(this);
jbtnTicTacToe7.addActionListener(this);
jbtnTicTacToe8.addActionListener(this);
jbtnTicTacToe9.addActionListener(this);
//South Button Panel
jpnlSouth.add(jbtnReset);
jpnlSouth.add(jbtnExit);
/* Instantiate JButtons, put into a method for efficiency
jbtn1 = instantiateJButton("1", Color.PINK);
jbtn2 = instantiateJButton("2", Color.PINK);
jbtn3 = instantiateJButton("3", Color.PINK);
jbtn4 = instantiateJButton("4", Color.PINK);
jbtn5 = instantiateJButton("5", Color.PINK);
jbtn6 = instantiateJButton("6", Color.PINK);
jbtn7 = instantiateJButton("7", Color.PINK);
jbtn8 = instantiateJButton("8", Color.PINK);
jbtn9 = instantiateJButton("9", Color.PINK);
*/
//Finalize screen layout and publish to the display
jpnlMain.add(jpnlCenter, BorderLayout.NORTH);
jpnlMain.add(jpnlSouth, BorderLayout.CENTER);
//Prepare the container
Container ca = getContentPane();
ca.setBackground (Color.LIGHT_GRAY);
ca.add(jpnlMain);
setContentPane (ca);
setVisible(true);
//end constructor
}
//CLASS EVENT HANDLER
public void actionPerformed(java.awt.event.ActionEvent e)
{
//find out which JButton was pressed by using the Action Command
String sActionCommand = e.getActionCommand();
//EXIT JButton
if (sActionCommand == "Exit")
{
System.exit(0);
}
//RESET JButton
else if (sActionCommand == "Reset")
{
jtfPlayerX.setText("");
jtfPlayerO.setText("");
}
} //end ACTIONPERFORMED (java.awt.event.ActionEvent e)
/**
* #param args
*/
public static void main(String[] args) {
//EXECUTION STARTING POINT
TicTacToeSwing TicTacToeSwing = new TicTacToeSwing();
//TicTacToeSwing TicTacToeObject = new TicTacToeSwing();
}//end main(String[] args)
}//end TicTacToeSwing class
The stacktrace has useful information about what is causing the NPE (jbtnReset which appears on line 84). Therefore you need to initialize jbtnReset:
JButton jbtnReset = new JButton("Reset");
In fact the same applys to all the jbtnTicTacToeX buttons as well as jbtnExit.
Side issues:
Use String#equals to compare String content. The == operator compares String content.
if (sActionCommand == "Exit") {
should be
if (sActionCommand.equals("Exit")) {
This checks the action command for any component with this String so you want to check the specific source object instead:
if (e.getSource() == jbtnExit) {
If you look at the stack trace, places like TicTacToeSwing.java:84 show you where the errors are occuring. TicTacToeSwing.java is the file, and :84 means line number 84.
Where you have:
private JButton jbtnExit;
private JButton jbtnReset;
Try:
private JButton jbtnExit = new JButton("Exit");
private JButton jbtnReset = new JButton("Reset");

Categories

Resources