NullPointerException in "AWT-EventQueue-0" java.lang - java

Hey all I am making a flight booking system and having this error when I click a seat for booking "AWT-EventQueue-0" java.lang.NullPointerException I think there is a mistake with my 2D Object initialization...
PS: is there a way I can get rid of the final in front of Seats[][] seats = new Seats[4][5];
Here is my Seats Class:
public class Seats {
private int row_number;
private boolean booked;
private Passenger myPassenger;
private String seat_name;
private String type;
private int column_number;
private long booking_nr;
public Seats(){
myPassenger = new Passenger();
booked = false;
}
public boolean isBooked() {
return booked;
}
public void setBooked(boolean booked) {
this.booked = booked;
}
}
and below is my GUI:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Book_GUI extends JFrame {
//private EconomyClass eco;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Book_GUI frame = new Book_GUI();
frame.setTitle("Economy Class");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Book_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
int left = 3;
int middle = 3;
int right = 4;
String[] singleRowAll = new String [left+middle+right];
for(int i = 1;i<singleRowAll.length;i++){singleRowAll[i] = "";}
singleRowAll[0] = "Window";
singleRowAll[left-1] = "Aisle";
singleRowAll[left] = "Aisle";
singleRowAll[left+middle-1] = "Aisle";
singleRowAll[left+middle] = "Aisle";
singleRowAll[left+middle+right-1] = "Window";
//eco = new EconomyClass(4,5,3,3,4);
final Seats[][] seats = new Seats[4][10];
for ( int i = 0; i < 4; i++) {
char c= 'A';
for ( int j = 0; j < 10; j++) {
final int x = i;
final int z = j;
final JButton btnBookFlight = new JButton(" " + (i+1) + c++ + " " + singleRowAll[j] );
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(seats[x][z].isBooked()){btnBookFlight.setBackground(Color.GREEN);}
seats[x][z].setBooked(true);
//JButton button = (JButton)arg0.getSource();
//button.setBackground(Color.RED);
// btnBookFlight.setBackground(Color.RED);
btnBookFlight.setOpaque(true);
}
});
contentPane.add(btnBookFlight);
}
}
contentPane.setLayout(new GridLayout(4, 10));
pack();
}
}
Thank you for reading and for your time!

You are not initializing the Seats[][] array. Try replacing the Constructor of Book_GUI.java with:
public Seats[][] seats = new Seats[4][10];
public Book_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
int left = 3;
int middle = 3;
int right = 4;
String[] singleRowAll = new String[left + middle + right];
for (int i = 1; i < singleRowAll.length; i++) {
singleRowAll[i] = "";
}
singleRowAll[0] = "Window";
singleRowAll[left - 1] = "Aisle";
singleRowAll[left] = "Aisle";
singleRowAll[left + middle - 1] = "Aisle";
singleRowAll[left + middle] = "Aisle";
singleRowAll[left + middle + right - 1] = "Window";
// eco = new EconomyClass(4,5,3,3,4);
//Delete this line:
//final Seats[][] seats = new Seats[4][5];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 5; j++) {
seats[i][j] = new Seats();
}
}
for (int i = 0; i < 4; i++) {
char c = 'A';
for (int j = 0; j < 10; j++) {
final int x = i;
final int z = j;
final JButton btnBookFlight = new JButton(" " + (i + 1) + c++
+ " " + singleRowAll[j]);
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (seats[x][z].isBooked()) {
btnBookFlight.setBackground(Color.GREEN);
}
seats[x][z].setBooked(true);
// JButton button = (JButton)arg0.getSource();
// button.setBackground(Color.RED);
// btnBookFlight.setBackground(Color.RED);
btnBookFlight.setOpaque(true);
}
});
contentPane.add(btnBookFlight);
}
}
contentPane.setLayout(new GridLayout(4, 10));
pack();
}
This should help :)

You are creating a new seat array, using new Seats[4][5], but that simply makes an empty array of references. you need to actually create a new seat that goes in each place in the array.

Related

How to make a method that disables JButton?

I am trying to make a method that disables JButtons.
The JButtons are in an array in the form of a grid, JButton [int][int] and the integers are supposed to be coordinates.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class BS {
public static JFrame f = new JFrame("BS");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
initializeGui();
}
});
}
static void initializeGui() {
JPanel gui = new JPanel(new BorderLayout(3,1));
//This is the array of the JButtons in the form of a grid
final JButton[][] coordinates = new JButton[15][15];
JPanel field;
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
field = new JPanel(new GridLayout(0, 15));
field.setBorder(new CompoundBorder(new EmptyBorder(15,15,15,15),new LineBorder(Color.BLACK)));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(field);
gui.add(boardConstrain);
//The making of the grid
for (int ii = 0; ii < coordinates.length; ii++) {
for (int jj = 0; jj < coordinates[ii].length; jj++) {
JButton b = new JButton();
ImageIcon icon = new ImageIcon(
new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
b.setIcon(icon);
coordinates[jj][ii] = b;
field.add(coordinates[jj][ii]);
}
}
f.add(gui);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
}
I did some changes in your code:
public static JFrame f = new JFrame("BS"); JFrame shouldn't be static and should have a more meaningful name (like frame for example).
final JButton[][] coordinates = new JButton[15][15]; moved this array as a class member and made it non final and also changed the name to buttons as it's easier to know what it is (coordinates to me, sounds more like an array of Point or int)
After that I added an ActionListener, see How to use Actions tutorial.
private ActionListener listener = e -> {
//Loops through the whole array in both dimensions
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) { //Find the JButton that was clicked
if (isStartButton) { //startButton is a boolean variable that tells us if this is the first button clicked or not
startXCoord = i;
startYCoord = j;
} else {
endXCoord = i;
endYCoord = j;
disableButtons(); //Only when we have clicked twice we disable all the buttons in between
}
isStartButton = !isStartButton; //In every button click we change the value of this variable
break; //No need to keep looking if we found our clicked button. Add another one with a condition to skip the outer loop.
}
}
}
};
And a method called disableButtons() which disables all the buttons between the 2 clicked buttons:
private void disableButtons() {
compareCoords(); //This method checks if first button clicked is after 2nd one.
for (int i = startXCoord; i <= endXCoord; i++) {
for (int j = startYCoord; j <= endYCoord; j++) {
buttons[i][j].setEnabled(false); //We disable all buttons in between
}
}
}
At the end our code ends like this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class DisableButtonsInBetween {
private JFrame frame = new JFrame(getClass().getSimpleName());
private JButton[][] buttons;
private int startXCoord = -1;
private int startYCoord = -1;
private int endXCoord = -1;
private int endYCoord = -1;
private boolean isStartButton = true;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisableButtonsInBetween().initializeGui();
}
});
}
void initializeGui() {
JPanel gui = new JPanel(new BorderLayout(3, 1));
// This is the array of the JButtons in the form of a grid
JPanel pane;
buttons = new JButton[15][15];
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
pane = new JPanel(new GridLayout(0, 15));
pane.setBorder(new CompoundBorder(new EmptyBorder(15, 15, 15, 15), new LineBorder(Color.BLACK)));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(pane);
gui.add(boardConstrain);
// The making of the grid
for (int ii = 0; ii < buttons.length; ii++) {
for (int jj = 0; jj < buttons[ii].length; jj++) {
buttons[jj][ii] = new JButton();
ImageIcon icon = new ImageIcon(new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
buttons[jj][ii].setIcon(icon);
buttons[jj][ii].addActionListener(listener);
pane.add(buttons[jj][ii]);
}
}
frame.add(gui);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
}
//The ActionListener is what gets called when you click a JButton
private ActionListener listener = e -> {
//These for loops are done to identify which button was clicked.
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) {
if (isStartButton) {
//We save the coords of the 1st button clicked
startXCoord = i;
startYCoord = j;
} else {
//We save the coords of the 2nd button clicked and call the disableButtons method
endXCoord = i;
endYCoord = j;
disableButtons();
}
isStartButton = !isStartButton;
break;
}
}
}
};
//This method disables all the buttons between the 2 that were clicked
private void disableButtons() {
compareCoords();
for (int i = startXCoord; i <= endXCoord; i++) {
for (int j = startYCoord; j <= endYCoord; j++) {
buttons[i][j].setEnabled(false);
}
}
}
//This method compares the coords if the 2nd button was before (in its coords) than the 1st one it switched their coords
private void compareCoords() {
if (endXCoord < startXCoord) {
int aux = startXCoord;
startXCoord = endXCoord;
endXCoord = aux;
}
if (endYCoord < startYCoord) {
int aux = startYCoord;
startYCoord = endYCoord;
endYCoord = aux;
}
}
}
I hope this is what you were trying to do... if not please clarify.
I do not have the arrow operator, " -> ". I think it requires a higher Java. Is there a way to replace this?
For Java 7 and lower use this for the ActionListener:
private ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) {
if (isStartButton) {
startXCoord = i;
startYCoord = j;
} else {
endXCoord = i;
endYCoord = j;
disableButtons();
}
isStartButton = !isStartButton;
break;
}
}
}
}
};

Java MVC Pattern on a JTabbedPane

I've been trying to follow an MVC pattern on my code and I was creating a system in which I have a JTabbedPane with Jbuttons inside the panel on my View, The content's info in the Model, and a the actionlisteners on my Controller.
The problem I've been having is that I've been trying to put an actionlistener on my Jbuttons but it seems to be only working on my last tab (let's say i have 4 tabs, only the 4th tab with jbuttons work)
Oh, and I should say that I've been using Jbutton arrays
Note that I've been only using only one Jbutton array to place on my panel.
how should this work? I need a sample code for reference.
here is my sample View class
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class View extends JFrame
{
private static final int HEIGHT = 700;
private static final int WIDTH = 700;
private JTabbedPane tabPane = new JTabbedPane();
private JComponent tab1 = makePanel("1");
private JComponent tab2 = makePanel("2");
private JComponent tab3 = makePanel("3");
private JComponent tab4 = makePanel("4");
private JButton[] button;
private String[] buttonlabel;
public View()
{
setLayout(null);
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setResizable(false);
setVisible(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
tabPane.addTab("firstTab", tab1);
tabPane.addTab("secondTab", tab2);
tabPane.addTab("thirdTab", tab3);
tabPane.addTab("fourtTab", tab4);
add(tabPane);
tabPane.setBounds(20, 20, 400, 400);
}
protected JComponent makePanel(String input)
{
JPanel panel = new JPanel(false);
panel.setLayout(null);
if(input == "1")
{
button = new JButton[4];
buttonlabel = new String[]
{
"1button1",
"2button1",
"3button1",
"4button1"
};
for(int x = 0; x < 4; x++)
{
button[x] = new JButton(buttonlabel[x]);
panel.add(button[x]);
}
int yCord = 20;
for(int x = 0; x < 4; x += 2)
{
int xCord = 20;
for(int y = x; y < (x + 2); y++)
{
button[y].setBounds(xCord, yCord, 100, 100);
xCord += 120;
}
yCord += 120;
}
}
else if(input == "2")
{
button = new JButton[4];
buttonlabel = new String[]
{
"1button2",
"2button2",
"3button2",
"4button2"
};
for(int x = 0; x < 4; x++)
{
button[x] = new JButton(buttonlabel[x]);
panel.add(button[x]);
}
int yCord = 20;
for(int x = 0; x < 4; x += 2)
{
int xCord = 20;
for(int y = x; y < (x + 2) && y < 5; y++)
{
button[y].setBounds(xCord, yCord, 100, 100);
xCord += 120;
}
yCord += 120;
}
}
else if(input == "3")
{
button = new JButton[4];
buttonlabel = new String[]
{
"1button3",
"2button3",
"3button3",
"4button3"
};
for(int x = 0; x < 4; x++)
{
button[x] = new JButton(buttonlabel[x]);
panel.add(button[x]);
}
int yCord = 20;
for(int x = 0; x < 4; x += 2)
{
int xCord = 20;
for(int y = x; y < (x + 2) && y < 5; y++)
{
button[y].setBounds(xCord, yCord, 100, 100);
xCord += 120;
}
yCord += 120;
}
}
else if(input == "4")
{
button = new JButton[4];
buttonlabel = new String[]
{
"1button4",
"2button4",
"3button4",
"4button4"
};
for(int x = 0; x < 4; x++)
{
button[x] = new JButton(buttonlabel[x]);
panel.add(button[x]);
}
int yCord = 20;
for(int x = 0; x < 4; x += 2)
{
int xCord = 20;
for(int y = x; y < (x + 2) && y < 5; y++)
{
button[y].setBounds(xCord, yCord, 100, 100);
xCord += 120;
}
yCord += 120;
}
}
return panel;
}
public void buttonListener(ActionListener buttonL)
{
for(int x = 0; x < button.length; x++)
{
button[x].addActionListener(buttonL);
}
}
public static void main(String args[])
{
View view = new View();
Controller control = new Controller(view);
view.setVisible(true);
}
}
here is my sample Controller class
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller
{
View view = new View();
public Controller(View view)
{
this.view = view;
this.view.buttonListener(new ButtonListener());
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("BUTTON WORKS!");
}
}
}
You're re-filling the button array with each creation of a JTabbedPane, and in doing so, the references for all the previous buttons have been discarded from the array and only the last remains.
I suggest that you create a class for the panel of the JTabbedPane and allow it to be injected from the control. Keep it simple.
One example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class View2 extends JPanel {
private static final long serialVersionUID = 1L;
private static final String[] TAB_NAMES = {"First Tab", "Second Tab", "Third Tab", "Fourth Tab"};
private static final int PREF_W = 400;
private static final int PREF_H = 150;
private JTabbedPane tabbedPane = new JTabbedPane();
private List<MyTab> myTabs = new ArrayList<>();
private Controller2 controller2;
public View2() {
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
add(tabbedPane, BorderLayout.CENTER);
for (int i = 0; i < TAB_NAMES.length; i++) {
int tabNumber = i + 1;
MyTab myTab = new MyTab(TAB_NAMES[i], tabNumber);
tabbedPane.add(myTab.getTabName(), myTab);
myTabs.add(myTab);
}
}
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
public Controller2 getController2() {
return controller2;
}
public void setController2(Controller2 controller2) {
this.controller2 = controller2;
for (MyTab myTab : myTabs) {
myTab.setController2(controller2);
}
}
private static void createAndShowGui() {
View2 viewPanel = new View2();
new Controller2(viewPanel);
JFrame frame = new JFrame("View2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(viewPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyTab extends JPanel {
private static final long serialVersionUID = 1L;
private static final int BUTTON_COUNT = 4;
private String tabName;
private int tabNumber;
private List<JButton> buttons = new ArrayList<>();
private Controller2 controller2;
public MyTab(String tabName, int tabNumber) {
this.tabName = tabName;
this.tabNumber = tabNumber;
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new GridLayout(2, 2, 4, 4));
for (int i = 0; i < BUTTON_COUNT; i++) {
String title = (i + 1) + " Button " + tabNumber;
JButton button = new JButton(title);
button.addActionListener(e -> {
if (controller2 != null) {
controller2.buttonAction(e);
}
});
add(button);
buttons.add(button);
}
}
public void setController2(Controller2 controller2) {
this.controller2 = controller2;
}
public String getTabName() {
return tabName;
}
public int getTabNumber() {
return tabNumber;
}
public List<JButton> getButtons() {
return buttons;
}
}
class Controller2 {
private View2 view;
public Controller2(View2 view) {
this.view = view;
view.setController2(this);
}
public void buttonAction(ActionEvent e) {
System.out.println("Button pressed! " + e.getActionCommand());
}
public View2 getView() {
return view;
}
}
This example uses a simple anonymous inner class ActionListener in the view to call a controller method.

Java Chessboard pieces not displaying corrrectly

I am making a chess game for a class I have and the chess piece is not displaying correctly.
This is my code:
package SucksLego;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import SucksLego.CheesBoard.CaseEchiquier;
import lejos.nxt.ColorSensor.Color;
public class ChessBoard2 extends JFrame{
private Container contents;
private JButton [][] squares = new JButton [8][8];
private int row = 7;
private int col = 1;
private ImageIcon piece = new ImageIcon ("chess-pawn-f.png");
public ChessBoard2 (){
super("Board");
contents = getContentPane();
contents.setLayout(new GridLayout (8,8));
ButtonHandler buttonHandler = new ButtonHandler();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
squares[i][j] = new JButton();
if((i+j) % 2 != 0){
squares[i][j].setBackground(getBackground().BLACK);
}
contents.add(squares [i][j]);
squares[i][j].addActionListener(buttonHandler);
}
}
squares [row][col].setIcon (piece);
setSize(500,500);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
private boolean isValidMove(int i, int j){
System.out.println("I: " + i + " J: " + j);
return true;
}
private void processClick (int i, int j){
if(isValidMove(i,j) == false){
return;
}
squares[row][col].setIcon(null);
squares[i][j].setIcon(piece);
row=i;
col=j;
}
private class ButtonHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if(source == squares[i][j]){
processClick(i,j);
return;
}
}
}
}
}
public static void main(String[] args) {
ChessBoard2 chess = new ChessBoard2();
}
}
The dimension of the icon is 60 x 60.
The icon is being displayed as a very small stip:
You are not getting the image, change your code and add below code to your ChessBoard2() constructor under super("Board");
try{
URL resource = ChessBoard2.class.getClassLoader().getResource("chess-pawn-f.png");
img = ImageIO.read(resource);
piece = new ImageIcon(img);
}
catch (IOException e)
{
e.printStackTrace();
}

adjust JTextField with JComboBox

Please some one can told me why I don't have the JTextField in the same line with my JComboBox ?
I need to have like that:
myJComboBox1 JTextField1
JTextField2
myJComboBox2 JTextField1
JTextField2
following this example
public class DisplayPanel extends JFrame {
private JComboBox[] box;
JTextField[] field1, field2;
public DisplayPanel(){
super(BorderLayoutTest.class.getName());
setTitle("Simulation");
setSize(1000,500);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createComponents();
initComponents();
}
private void createComponents(){
box = new JComboBox[3];
field1 = new JTextField[4];
field2 = new JTextField[5];
}
private void initComponents(){
setLayout(new GridLayout(0, 2));
for(int i = 0; i < 3; i++) {
JPanel panel = new JPanel(new BorderLayout());
box[i] =new JComboBox<>(new String[] { "field1", "field2"});
panel.add(box[i], BorderLayout.NORTH);
add(panel);
add(createPanelWithTextFields(panel));
box[i].setSelectedIndex(-1);
box[i].addActionListener(new CustomActionListener(box[i]));
}
}
private Component createPanelWithTextFields(JPanel panel) {
//need to keep the same layout as JComboBox
panel.setLayout(new GridLayout(0, 1));
for(int x=0; x<4; x++){
field1[x] = new JTextField("field1 Name " + (x+1));
field1[x].setVisible(false);
panel.add(field1[x]);
}
for(int x=0; x<5; x++){
field2[x] = new JTextField("field2 Name " + (x+1));
field2[x].setVisible(false);
panel.add(field2[x]);
}
return panel;
}
class CustomActionListener implements ActionListener {
JComboBox b;
public CustomActionListener(JComboBox u) {
super();
this.b = u;
}
public void actionPerformed(ActionEvent e) {
int numChosen = b.getSelectedIndex() + 1;
switch (numChosen){
case 1:
for(int x=0; x<4; x++)
field1[x].setVisible(true);
break;
case 2:
for(int x=0; x<5; x++)
field2[x].setVisible(true);
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
new DisplayPanel().setVisible(true);
}
});
}
you are assigning new textfield to textfield array.but it contain only 4 textfields.but you call assigning more than 4 times.so what happening is last rextfield references get reassigning and you can't use them again.at the end of the the loop your field array contain reference to textfields of last panel.and that's why your see textfields on last panel even you select from combobox1.
how to fix ?
change this
field1 = new JTextField[4];
to this
field1 = new JTextField[4 * 3];
and then you don't need to reassign jtextfields .you have 3 panels and you have 4 textfields for each panel.
same for field2
here is an example .
public class DisplayPanel extends JFrame {
private JComboBox[] box;
JTextField[] field1, field2;
Color col[] = {Color.red, Color.GREEN, Color.blue};
int i = 0;
int counter = 0;
private int boxcount;
int field1counter = 0;
int field2counter = 0;
public DisplayPanel() {
//super(BorderLayoutTest.class.getName());
setTitle("Simulation");
setSize(1000, 500);
//setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createComponents();
initComponents();
}
private void createComponents() {
boxcount = 3;
box = new JComboBox[1 * boxcount];
field1 = new JTextField[4 * boxcount];
field2 = new JTextField[5 * boxcount];
}
private void initComponents() {
setLayout(new GridLayout(0, 2));
for (int i = 0; i < 3; i++) {
JPanel panel = new JPanel(new BorderLayout());
box[i] = new JComboBox<>(new String[]{"field1", "field2"});
panel.add(box[i], BorderLayout.NORTH);
add(panel);
add(createPanelWithTextFields(panel));
box[i].setSelectedIndex(-1);
box[i].addActionListener(new CustomActionListener());
}
}
private Component createPanelWithTextFields(JPanel panelc) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.setBackground(col[i]);
System.out.println("......................");
for (int x = 0; x < 4; x++) {
System.out.println("iterating .." + (field1counter) + " counter " + counter);
field1[field1counter] = new JTextField("field1 Name " + (x + 1));
field1[field1counter].setVisible(false);
panel.add(field1[field1counter]);
field1counter++;
}
for (int x = 0; x < 5; x++) {
field2[field2counter] = new JTextField("field2 Name " + (x + 1));
field2[field2counter].setVisible(false);
panel.add(field2[field2counter]);
field2counter++;
}
i++;
counter++;
return panel;
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox b = (JComboBox) e.getSource();
int comboidenty = 0;
for (int k = 0; k < box.length; k++) {
if (box[k] == b) {
break;
}
comboidenty++;
}
System.out.println(((JPanel) (b.getParent())).getBackground());
int numChosen = b.getSelectedIndex() + 1;
System.out.println("hi " + comboidenty);
switch (numChosen) {
case 1:
for (int x = 0; x < 4; x++) {
System.out.println("field1 " + (comboidenty * 4 + x));
field1[comboidenty * 4 + x].setVisible(true);
}
break;
case 2:
for (int x = 0; x < 5; x++) {
System.out.println("field2 " + (comboidenty * 5 + x));
field2[comboidenty * 5 + x].setVisible(true);
}
break;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DisplayPanel().setVisible(true);
}
});
}
}

How to use JCheckbox array in JPanel array

I used the code from Hovercraft Full Of Eels and manipulated it a little to get the numbering as I wanted. It looks good now and I can read the status but I can't figure out how to manipulate the individual checkboxes with my buttons on the form. Can someone help?
package and.lotto;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class NewLotto extends JPanel {
public static final int GRID_PANEL_ROWS = 3;
public static final int GRID_PANEL_COLS = 4;
public static final int PANELS = 12;
public static final int BOXES = 12;
private static final int GAP = 1;
private CheckBoxGrid[] checkBoxGrid = new CheckBoxGrid[PANELS];
public NewLotto() {
setLayout(new GridLayout(GRID_PANEL_ROWS, GRID_PANEL_COLS, GAP, GAP));
for (int rows = 0; rows < BOXES; rows++) {
checkBoxGrid[rows] = new CheckBoxGrid(rows,0);
add(checkBoxGrid[rows]);
}
}
private static void createAndShowGui() {
NewLotto mainPanel = new NewLotto();
ButtonPanel buttons = new ButtonPanel();
JFrame frame = new JFrame("Lotto");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(buttons,BorderLayout.NORTH);
frame.add(mainPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel {
JButton generate;
JButton clear;
private ActionListener actionListener = new MyButtonListener();
public ButtonPanel(){
generate = new JButton("Generate numbers");
generate.addActionListener(actionListener);
clear = new JButton("Clear All");
clear.addActionListener(actionListener);
add(generate);
add(clear);
}
private class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Testing");
}
}
}
#SuppressWarnings("serial")
class CheckBoxGrid extends JPanel {
private static final int CHECK_BOXES = 35;
private static final int CHECK_BOX_COLS = 6;
private static final int CHECK_BOX_ROWS = 6;
private static final int GAP = -5;
private JCheckBox[] checkBoxes = new JCheckBox[CHECK_BOXES];
private int gridIndex;
private ItemListener itemListener = new MyCheckBoxListener();
private int row;
private int col;
public CheckBoxGrid(int row, int col) {
this.row = row;
this.col = col;
gridIndex = row + col + 1;
setBorder(BorderFactory.createTitledBorder(String.valueOf(gridIndex)));
setLayout(new GridLayout(CHECK_BOX_ROWS, CHECK_BOX_COLS, GAP, GAP));
for (int cbRow = 0; cbRow < checkBoxes.length; cbRow++) {
JCheckBox checkBox = new JCheckBox();
checkBox.addItemListener(itemListener);
add(checkBox);
checkBox.setRolloverEnabled(false);
checkBox.setRequestFocusEnabled(false);
checkBoxes[cbRow] = checkBox;
}
checkBoxes[0].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red01.png")));
checkBoxes[0].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red01sel.png")));
checkBoxes[1].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red02.png")));
checkBoxes[1].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red02sel.png")));
checkBoxes[2].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red03.png")));
checkBoxes[2].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red03sel.png")));
checkBoxes[3].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red04.png")));
checkBoxes[3].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red04sel.png")));
checkBoxes[4].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red05.png")));
checkBoxes[4].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red05sel.png")));
checkBoxes[5].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red06.png")));
checkBoxes[5].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red06sel.png")));
checkBoxes[6].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red07.png")));
checkBoxes[6].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red07sel.png")));
checkBoxes[7].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red08.png")));
checkBoxes[7].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red08sel.png")));
checkBoxes[8].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red09.png")));
checkBoxes[8].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red09sel.png")));
checkBoxes[9].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red10.png")));
checkBoxes[9].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red10sel.png")));
checkBoxes[10].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red11.png")));
checkBoxes[10].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red11sel.png")));
checkBoxes[11].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red12.png")));
checkBoxes[11].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red12sel.png")));
checkBoxes[12].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red13.png")));
checkBoxes[12].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red13sel.png")));
checkBoxes[13].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red14.png")));
checkBoxes[13].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red14sel.png")));
checkBoxes[14].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red15.png")));
checkBoxes[14].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red15sel.png")));
checkBoxes[15].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red16.png")));
checkBoxes[15].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red16sel.png")));
checkBoxes[16].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red17.png")));
checkBoxes[16].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red17sel.png")));
checkBoxes[17].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red18.png")));
checkBoxes[17].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red18sel.png")));
checkBoxes[18].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red19.png")));
checkBoxes[18].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red19sel.png")));
checkBoxes[19].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red20.png")));
checkBoxes[19].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red20sel.png")));
checkBoxes[20].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red21.png")));
checkBoxes[20].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red21sel.png")));
checkBoxes[21].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red22.png")));
checkBoxes[21].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red22sel.png")));
checkBoxes[22].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red23.png")));
checkBoxes[22].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red23sel.png")));
checkBoxes[23].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red24.png")));
checkBoxes[23].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red24sel.png")));
checkBoxes[24].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red25.png")));
checkBoxes[24].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red25sel.png")));
checkBoxes[25].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red26.png")));
checkBoxes[25].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red26sel.png")));
checkBoxes[26].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red27.png")));
checkBoxes[26].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red27sel.png")));
checkBoxes[27].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red28.png")));
checkBoxes[27].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red28sel.png")));
checkBoxes[28].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red29.png")));
checkBoxes[28].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red29sel.png")));
checkBoxes[29].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red30.png")));
checkBoxes[29].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red30sel.png")));
checkBoxes[30].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red31.png")));
checkBoxes[30].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red31sel.png")));
checkBoxes[31].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red32.png")));
checkBoxes[31].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red32sel.png")));
checkBoxes[32].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red33.png")));
checkBoxes[32].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red33sel.png")));
checkBoxes[33].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red34.png")));
checkBoxes[33].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red34sel.png")));
checkBoxes[34].setIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red35.png")));
checkBoxes[34].setSelectedIcon(new ImageIcon(NewLotto.class.getResource("/and/lotto/img/red35sel.png")));
}
private class MyCheckBoxListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent itemEvt) {
JCheckBox source = (JCheckBox) itemEvt.getSource();
boolean selected = source.isSelected();
int cbRow = -1;
for (int r = 0; r < checkBoxes.length; r++) {
if (source.equals(checkBoxes[r])) {
cbRow = r;
}
}
String text = String.format("Grid %d, selected: %b, at %d",
(row + col + 1), selected, cbRow);
System.out.println(text);
}
}
}
Here is the original question:
I am trying to create a layout with an array of 12 JPanels each containing an array of 35 JCheckboxes. The problem I am having is that although the panels and checkboxes all display fine on the form, I have no way of accessing the properties of the individual checkboxes.
Here is part of the code I use:
JPanel panel_south = new JPanel();
contentPane.add(panel_south, BorderLayout.SOUTH);
panel_south.setLayout(new GridLayout(3, 4, 1, 1));
for(Integer i =0; i<12;i++){
Integer title = i+1;
EtchedBorder border = new EtchedBorder(EtchedBorder.LOWERED, null, null);
TitledBorder titled = new TitledBorder(border,title.toString());
row[i] = new JPanel();
row[i].setBorder(titled);
row[i].setLayout(new GridLayout(6, 6, -6, -5));
panel_south.add(row[i]);
JCheckBox[] rad = new JCheckBox[35];
for (int j = 0;j<35;j++){
rad[j] = new JCheckBox();
row[i].add(rad[j]);
}
When I try to use a line like this in the for loop:
row[i].rad[j].setSelected(true);
I get the error: rad cannot be resolved
What am I doing wrong here?
You should refactor out the JPanel that holds a grid of JTextFields, create a separate class for this, one that accepts a number for it's index, and that holds the JCheckBox grid or a JTable.
e.g.,
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class CheckBoxGridMain extends JPanel {
public static final int GRID_PANEL_ROWS = 3;
public static final int GRID_PANEL_COLS = 4;
private static final int GAP = 1;
private CheckBoxGrid[][] checkBoxGrid = new CheckBoxGrid[GRID_PANEL_ROWS][GRID_PANEL_COLS];
public CheckBoxGridMain() {
setLayout(new GridLayout(GRID_PANEL_ROWS, GRID_PANEL_COLS, GAP, GAP));
for (int row = 0; row < checkBoxGrid.length; row++) {
for (int col = 0; col < checkBoxGrid[row].length; col++) {
checkBoxGrid[row][col] = new CheckBoxGrid(row, col);
add(checkBoxGrid[row][col]);
}
}
}
private static void createAndShowGui() {
CheckBoxGridMain mainPanel = new CheckBoxGridMain();
JFrame frame = new JFrame("CheckBox Grid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class CheckBoxGrid extends JPanel {
private static final int CHECK_BOX_ROWS = 6;
private static final int CHECK_BOX_COLS = 6;
private static final int GAP = -5;
private JCheckBox[][] checkBoxes = new JCheckBox[CHECK_BOX_ROWS][CHECK_BOX_COLS];
private int gridIndex;
private ItemListener itemListener = new MyCheckBoxListener();
private int row;
private int col;
public CheckBoxGrid(int row, int col) {
this.row = row;
this.col = col;
gridIndex = row + col + 1;
setBorder(BorderFactory.createTitledBorder(String.valueOf(gridIndex)));
setLayout(new GridLayout(CHECK_BOX_ROWS, CHECK_BOX_COLS, GAP, GAP));
for (int cbRow = 0; cbRow < checkBoxes.length; cbRow++) {
for (int cbCol = 0; cbCol < checkBoxes[cbRow].length; cbCol++) {
JCheckBox checkBox = new JCheckBox();
checkBox.addItemListener(itemListener);
add(checkBox);
checkBoxes[cbRow][cbCol] = checkBox;
}
}
}
private class MyCheckBoxListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent itemEvt) {
JCheckBox source = (JCheckBox) itemEvt.getSource();
boolean selected = source.isSelected();
int cbRow = -1;
int cbCol = -1;
for (int r = 0; r < checkBoxes.length; r++) {
for (int c = 0; c < checkBoxes[r].length; c++) {
if (source.equals(checkBoxes[r][c])) {
cbRow = r;
cbCol = c;
}
}
}
String text = String.format("Grid %d, selected: %b, at [%d, %d]",
(row + col + 1), selected, cbCol, cbRow); // corrected row/col order
System.out.println(text);
}
}
}
Which displays

Categories

Resources