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);
}
});
}
}
Related
So, I am working on recreating Minesweeper in Java and right now I need to place all of the buttons on the JFrame in a grid. My code is below:
import javax.swing.*;
import java.util.ArrayList;
import java.awt.*;
import javax.imageio.*;
public class Graphics{
private JFrame frame;
private JPanel panel;
private JLabel label;
private int boardSizeY;
private int boardSizeX;
private ImageIcon ImgEmpty = new ImageIcon("/Images/Empty.png");
private ImageIcon ImgFull = new ImageIcon("/Images/UnSelected.png");
public Graphics(int sizeY, int sizeX){
boardSizeX = sizeX;
boardSizeY = sizeY;
gui();
drawButtons();
}
public void gui() {
frame = new JFrame("Minesweeper");
frame.setVisible(true);
frame.setSize(boardSizeX*20, boardSizeY*20 + 2);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
}
public void drawButtons(){
ArrayList<JButton> buttons = new ArrayList<>();
int x = 0;
int y = 0;
for(int t = 0; t < boardSizeX*boardSizeY; t++){
buttons.add(new JButton(ImgFull));
panel.add(buttons.get(t));
buttons.get(t).setBounds(x*20, y*20, 20, 20);
if(y == boardSizeY-1){
x++;
y = 0;
}
else y++;
}
frame.add(panel);
}
}
The code that I wrote works, however is extremely slow for board sizes greater than 10x10. What changes can I make to my drawButtons() function in order to quicken the process.
This 30 x 30 (900 buttons) version appears almost instantly on this machine. It uses JButton components and lays them out using a GridLayout.
This is what it looks like at 10 x 10 with a larger font.
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class MineSweeper {
public final static String BOMB = new String(Character.toChars(128163));
private JComponent ui = null;
private MineFieldModel mineFieldModel;
private final Color[] colors = {
Color.BLUE,
Color.CYAN.darker(),
Color.GREEN.darker(),
Color.YELLOW.darker(),
Color.ORANGE.darker(),
Color.PINK.darker(),
Color.MAGENTA,
Color.RED
};
private final int size = 30;
private final float fontSize = 10f;
private JButton[][] buttons;
private JLabel info = new JLabel("Enter the minefield!");
MineSweeper() {
initUI();
}
private JToolBar getToolBar() {
JToolBar tb = new JToolBar();
tb.setFloatable(false);
tb.setLayout(new FlowLayout(FlowLayout.LEADING, 4, 2));
tb.add(info);
return tb;
}
private final Point[] getExposableSquares(Point point) {
Point[] points = null;
int x = point.x;
int y = point.y;
if (mineFieldModel.isBomb(x, y)) {
}
return points;
}
public final void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
ui.add(getToolBar(), BorderLayout.PAGE_START);
mineFieldModel = new MineFieldModel(size, (int)(size*size*.4));
JPanel mineFieldContainer = new JPanel(new GridLayout(
size, size));
ui.add(mineFieldContainer, BorderLayout.CENTER);
int in = 5;
Insets insets = new Insets(in, in, in, in);
Font f = getCompatibleFonts().firstElement().deriveFont(fontSize);
buttons = new JButton[size][size];
for (int ii = 0; ii < size; ii++) {
for (int jj = 0; jj < size; jj++) {
JButton b = new SquareButton();
b.setMargin(insets);
b.setFont(f);
b.setText("?");
if (mineFieldModel.isExposed(ii, jj)) {
if (mineFieldModel.isBomb(ii, jj)) {
b.setForeground(Color.red);
b.setForeground(Color.BLACK);
b.setText(BOMB);
} else if (mineFieldModel.countSurroundingMines(ii, jj) > 0) {
int count = mineFieldModel.countSurroundingMines(ii, jj);
if (count > 0) {
b.setForeground(colors[count - 1]);
b.setText("" + count);
}
} else {
b.setText("");
}
}
buttons[ii][jj] = b;
mineFieldContainer.add(b);
}
}
}
private static Vector<Font> getCompatibleFonts() {
Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
Vector<Font> fontVector = new Vector<>();
for (Font font : fonts) {
if (font.canDisplayUpTo("12345678?" + BOMB) < 0) {
fontVector.add(font);
}
}
return fontVector;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
MineSweeper o = new MineSweeper();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
class MineFieldModel {
public int size;
/**
* Records bomb locations.
*/
boolean[][] mineField;
/**
* Records whether this location has been exposed.
*/
boolean[][] fieldPlaceExposed;
int numberMines;
Random r = new Random();
MineFieldModel(int size, int numberMines) {
this.size = size;
this.numberMines = numberMines;
mineField = new boolean[size][size];
fieldPlaceExposed = new boolean[size][size];
ArrayList<Point> locations = new ArrayList<>();
for (int ii = 0; ii < this.size; ii++) {
for (int jj = 0; jj < size; jj++) {
mineField[ii][jj] = false;
// must change this to false for the actual game.
fieldPlaceExposed[ii][jj] = true;
Point p = new Point(ii, jj);
locations.add(p);
}
}
Collections.shuffle(locations, r);
for (int ii = 0; ii < numberMines; ii++) {
Point p = locations.get(ii);
mineField[p.x][p.y] = true;
}
}
public boolean isBomb(int x, int y) {
return mineField[x][y];
}
public boolean isExposed(int x, int y) {
return fieldPlaceExposed[x][y];
}
public int getSize() {
return size;
}
public int countSurroundingMines(int x, int y) {
int lowX = x - 1;
lowX = lowX < 0 ? 0 : lowX;
int highX = x + 2;
highX = highX > size ? size : highX;
int lowY = y - 1;
lowY = lowY < 0 ? 0 : lowY;
int highY = y + 2;
highY = highY > size ? size : highY;
int count = 0;
for (int ii = lowX; ii < highX; ii++) {
for (int jj = lowY; jj < highY; jj++) {
if (ii != x || jj != y) {
if (mineField[ii][jj]) {
count++;
}
}
}
}
return count;
}
}
class SquareButton extends JButton {
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int w = d.width;
int h = d.height;
int s = w>h ? w : h;
return new Dimension(s, s);
}
}
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.
In my Springbreak holiday I started to write Checkers Game. I have created my CheckersBoard but I couldn't write MouseListener part. Can you help me with this part? I'm not pretty sure how to implement this part? Is MouseListener correct? Or should I choose another Listener? I have googled but couldn't any clue.
Thank you so much.
public class CheckersGUI {
private final JPanel gui = new JPanel(new BorderLayout(3, 3));
private JButton[][] Squares = new JButton[8][8];
private JPanel Board;
private final JLabel message = new JLabel(
"Ready to play!");
private static final String COLS = "ABCDEFGH";
private ImageIcon brown = new ImageIcon("brown.jpg");
private ImageIcon red = new ImageIcon("red.png");
CheckersGUI() {
create();
//create ButtonHandler
/* ButtonHandler handler = new ButtonHandler();
for (int i=0; i<Squares.length; i++){
for (int j=0; i<Squares[0].length; i++){
Squares[i][j].addMouseListener(handler);
}
}
}
private class ButtonHandler implements MouseListener{
public void MouseClicked ( MouseEvent event){
}*/
}
public final void create() {
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
JToolBar tools = new JToolBar();
tools.setFloatable(false);
gui.add(tools, BorderLayout.PAGE_START);
Action newGameAction = new AbstractAction("New") {
#Override
public void actionPerformed(ActionEvent e) {
setupNewGame();
}
};
tools.add(newGameAction);
// TODO - add functionality!
tools.addSeparator();
tools.add(message);
gui.add(new JLabel(""), BorderLayout.LINE_START);
Board = new JPanel(new GridLayout(0, 9)) ;
Board.setBorder(new CompoundBorder(
new EmptyBorder(8,8,8,8),
new LineBorder(Color.BLACK)
));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(Board);
gui.add(boardConstrain);
// create the chess board squares
Insets buttonMargin = new Insets(0, 0, 0, 0);
for (int ii = 0; ii < Squares.length; ii++) {
for (int jj = 0; jj < Squares[ii].length; jj++) {
JButton b = new JButton();
b.setMargin(buttonMargin);
ImageIcon icon = new ImageIcon(
new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB));
b.setIcon(icon);
if ((jj % 2 == 1 && ii % 2 == 1)
|| (jj % 2 == 0 && ii % 2 == 0)) {
b.setBackground(Color.WHITE);
} else {
b.setBackground(Color.BLACK);
}
Squares[jj][ii] = b;
}
}
/*
* fill the chess board
*/
Board.add(new JLabel(""));
// fill the top row
for (int ii = 0; ii < 8; ii++) {
Board.add(
new JLabel(COLS.substring(ii, ii + 1),
SwingConstants.CENTER));
}
// fill the black non-pawn piece row
for (int ii = 0; ii < 8; ii++) {
for (int jj = 0; jj < 8; jj++) {
switch (jj) {
case 0:
Board.add(new JLabel("" + (9-(ii + 1)),
SwingConstants.CENTER));
default:
Board.add(Squares[jj][ii]);
}
}
}
}
public final JComponent getGui() {
return gui;
}
/**
* Initializes the icons of the initial chess board piece places
*/
private final void setupNewGame() {
message.setText("Make your move!");
for (int ii = 0; ii < 8; ii++) {
Squares[ii][1].setIcon(red);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][2].setIcon(red);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][5].setIcon(brown);
}
for (int ii = 0; ii < 8; ii++) {
Squares[ii][6].setIcon(brown);
}
}
public static void main(String[] args) {
CheckersGUI cg = new CheckersGUI();
JFrame f = new JFrame("Checkers");
f.add(cg.getGui());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
f.setResizable(false);
f.setVisible(true);
}
}
You can add an ActionListener to each button. If the button is pressed (actually, when it is released) the actionPerformed method will be called.
Add the following to your code, to make each square red after it has been clicked:
public static class ButtonHandler implements ActionListener {
private JButton b;
public ButtonHandler(JButton b) {
this.b = b;
}
#Override
public void actionPerformed(ActionEvent e) {
b.setBackground(Color.red);
}
}
This is the handler. Notice that each handler instance will be associated with a button.
Now, create and add a new ButtonHandler to each button after it has been created:
JButton b = new JButton();
...
b.addActionListener(new ButtonHandler(b));
You can change the implementation of actionPerformed.
Example: Add a method getCurrentPlayer() to actionPerformed, then, if the current player is player one, change the color to blue, else, change the color to red.
I trust this will help you to achieve what you need.
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.
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