I'm developing a simple 15-puzzle game. I added 16 generated numbered buttons to a JFrame and that was the exercise (University).
I'm now trying to go further and make interactions so I need to get all buttons and put them into a 2D vector in order to calculate where user clicks and if and where the cell could "slide", but I don't know how to get them from the Frame.
Here is the generator code:
public void generation(){
int num;
Random rand = new Random();
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < this.getTot(); i++)
list.add(""+ i);
while(!list.isEmpty()){
do{
num = rand.nextInt(this.getTot());
} while (!list.contains("" + num));
list.remove("" + num);
if(num == 0){
this.add(new Button(" ");
}
else{
this.add(new Button("" + num);
}
}
}
And here is the constructor:
public Base15(int x, int y){
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(x, y));
this.x = x;
this.y = y;
this.generation();
this.cells = new Button[x][y];
}
Thank you.
UPDATE: Followed ufis suggestions and had the 2d array done!
for (int row = 0; row < x; row++){
for (int col = 0; col < y; col++){
do{
num = rand.nextInt(this.getTot());
} while (!list.contains("" + num));
list.remove("" + num);
if(num == 0){
cells[row][col] = new Button(" ", sw, label);
this.add(cells[row][col]);
}else{
cells[row][col] = new Button("" + num, sw, label);
this.add(cells[row][col]);
}
}
Thank you all!
Unless I completely misunderstand your question you can do
JFrame theFrame = new JFrame();
// lots of code here to add buttons
Component[] components = theFrame.getComponents();
for (Component component : components) {
if (component instanceof Button) {
// do something
}
}
But it would be better if you store some reference to all your Buttons as you create / add them to the Frame.
EDIT:
I think you should check the way you create your Buttons when you add them to the frame.
When you do
JFrame theFrame = new JFrame();
for (int i = 0; i < 15; i++) {
theFrame.add(new Button());
}
You have no reference to your Buttons. This is why you need to "get the Buttons from the Frame.
If you do something like
JFrame theFrame = new JFrame();
Button[] buttons = new Button[15];
for (int i = 0; i < 15; i++) {
buttons[i] = new Button();
theFrame.add(buttons[i]);
}
You will not have to loop through all the components at a later stage, because you have reference to the buttons in your buttons array. You can of course make that a Button[][] too. But the win here is that you have the reference to the list of buttons at creation time.
public void resetPanel(JFrame form)
{
Component[] components = form.getContentPane().getComponents();
for(Component component : components)
{
if(component instanceof JButton){
JButton button = (JButton) component;
button.setText("?");
}
}
}
Related
I am trying to find a way to either SWITCH the buttons or SWAP the button icons in a 2D array of buttons. I am attempting to create a board game and move pieces around.
I'm not sure if my logic is just completely off here but my though process is.. Create a Gamepiece class that extends JButton. Pass those buttons into a 2d array and add that button to the GridLayout.
Now, I feel like swapping the icons on the buttons is simpler but I cant seem to figure out how to do it correctly.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Board implements ActionListener {
private int p1;
private int p2;
private int fromRow;
private int fromCol;
private int toRow;
private int toCol;
private JPanel grid = new JPanel(new GridLayout(8,8));
private JFrame jf = new JFrame();
GamePieces gp;
private boolean isFirstClick = true;
Icon eagles = new ImageIcon("eagles.png");
Icon cowboys = new ImageIcon("cowboys.png");
GamePieces boardGame [][] = new GamePieces [8][8];
int board [][] = new int [][]{{1,1,1,1,0,0,0,0},
{1,1,1,0,0,0,0,0},
{1,1,0,0,0,0,0,0},
{1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,2},
{0,0,0,0,0,0,2,2},
{0,0,0,0,0,2,2,2},
{0,0,0,0,2,2,2,2}};
///////////////////////////////////////////////////////////////////
public Board(){
jf.setTitle("Board Game");
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(640,640);
JMenuBar menuBar = new JMenuBar();
jf.setJMenuBar(menuBar);
JMenu file = new JMenu("File");
JMenu about = new JMenu("About");
menuBar.add(file);
menuBar.add(about);
createBoard();
jf.setVisible(true);
}// end constructor
////////////////////////////////////////////////////////////////////
public void movePiece(){
for(int row = 0; row < boardGame.length; row++){
for(int col = 0; col < boardGame.length; col++){
boardGame[toRow][toCol] = boardGame[fromRow][fromCol];
gp = new GamePieces(fromRow,fromCol);
gp.setIcon(eagles);
boardGame[toRow][toCol] = gp;
jf.repaint();
}
}
}
/////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent ae){
for(int row = 0; row < boardGame.length; row++){
for(int col = 0; col < boardGame.length; col++){
if(ae.getSource() == boardGame[row][col]){
if(isFirstClick){
fromRow = boardGame[row][col].getRow();
fromCol = boardGame[row][col].getCol();
isFirstClick = false;
System.out.println("First Row " + boardGame[row][col].getRow() + " Col " + boardGame[row][col].getCol());
}
else {
toRow = boardGame[row][col].getRow();
toCol = boardGame[row][col].getCol();
System.out.println("Second Row " + boardGame[row][col].getRow() + " Col " + boardGame[row][col].getCol());
this.movePiece();
}
}
}
}
}
///////////////////////////////////////////////////////
public void createBoard(){
for(int row = 0; row < board.length; row++){
for(int col = 0; col < board.length; col++){
if (board[row][col] == 1){
gp = new GamePieces(row,col);
gp.setIcon(eagles);
boardGame[row][col] = gp;
grid.add(boardGame[row][col]);
boardGame[row][col].addActionListener(this);
}
else if (board[row][col] == 0){
gp = new GamePieces(row,col);
boardGame[row][col] = gp;
grid.add(boardGame[row][col]);
boardGame[row][col].addActionListener(this);
}
else if(board[row][col] == 2){
gp = new GamePieces(row,col);
gp.setIcon(cowboys);
boardGame[row][col] = gp;
grid.add(boardGame[row][col]);
boardGame[row][col].addActionListener(this);
}
}
}
jf.add(grid);
}
class GamePieces extends JButton {
private int row;
private int col;
private String player;
public GamePieces(int row, int col){
this.row = row;
this.col = col;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
}
public String getPlayer(){
return player;
}
}
public static void main(String [] args){
Board Halmas = new Board();
}
}
No, don't swap buttons as there's no need, and no benefit to doing this. Instead use an MVC or Model-View-Control program structure and swap Icons held by JButtons or JLabels (my preference) as dictated by changes in the model's state.
Regardless of what overall technique you use, swap your icons, not your buttons.
I've been tasked to make a java replica of Candy Crush Saga.
Right now im quite stuck on the GUI part.
I've decided that each candy will be represented by a JLabel holding the candy icon, and a mouselistener to control the functionality.
What happens is, after i finish running the screen shows, the mouse listeners respond but the image doesn't show, meaning i can press the labels get a response but cannot see the icons. I take this as the labels are on the panel but somehow not visible or the icon is not loaded correctly - although when checking the ImageIcon.toString it shows the path to the file.
Any ideas?
Here is the code:
public class Board extends JPanel {
Candy[][] board;
static final int TILE_SIZE = 55;
static final int TILES_MARGIN = 8;
public Board() {
setFocusable(true);
board = new Candy[13][13];
Candy c;
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++) {
if (i != 0 && i != 1 && j != 0 && j != 1 && i != 11 && i != 12 && j != 11 && j != 12) {
Random rand = new Random();
int randomNum = rand.nextInt((6 - 1) + 1) + 1;
c = new Basic(randomNum, this);
} else {
c = new Basic(0, this);
}
setAt(i, j, c);
}
repaint();
}
public void drawCandy(Graphics g2, Candy candy, int x, int y) {
Graphics2D g = ((Graphics2D) g2);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
int value = candy.getClr();
int xOffset = offsetCoors(x);
int yOffset = offsetCoors(y);
ImageIcon myImg = candy.switchIcon();
JLabel toAdd = new JLabel(myImg);
toAdd.setIcon(myImg);
toAdd.setLocation(xOffset,yOffset);
toAdd.setSize(TILE_SIZE,TILE_SIZE);
toAdd.addMouseListener(new ButtonPressed(x,y,candy));
toAdd.setVisible(true);
if (value != 0)
add(toAdd);
}
private static int offsetCoors(int arg) {
return (arg-2) * (TILES_MARGIN + TILE_SIZE) + TILES_MARGIN;
}
public void paint(Graphics g) {
super.paint(g);
removeAll();
requestFocusInWindow();
g.setColor(Color.black);
g.fillRect(0, 0, this.getSize().width, this.getSize().height);
for (int x = 2; x < 11; x++) {
for (int y = 2; y < 11; y++) {
drawCandy(g, board[x][y], x, y);
}
}
validate();
}
and the JFrame :
public Game() {
super("Candy Crush Game");
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
setSize(600, 600);
setResizable(false);
setLocationRelativeTo(null);
this.board = new Board();
this.score = 0;
this.moves = 20;
this.getContentPane().add(board, BorderLayout.CENTER);
setVisible(true);
board.checkSquare(2, 2, 10, 10);
}
I'm quite frustrated, any help will be great!
Instead of overriding paint() method use paintComponent() method for JPanel.
#Overrie
public void paintComponent(Graphics g) {
super.paintComponent(g);
//your custom painting here
}
Read more
Painting in AWT and Swing
paintComponent() vs paint() and JPanel vs Canvas in a paintbrush-type GUI
There might be some issue in reading image icon. My another post might help you.
ImageIcon does not work with me
Instead of creating new JLabel simply change it's icon.
i am creating a maze generation application. what i want to happen is that, when i run my program, it will show the animation on how the maze was created (it will show how it knocks the wall to create a path).
i tried to put delay on some of its parts but it won't run.thank you for the HUGE HELP!
here's the code:
public class Maze extends JPanel {
private Room[][] rooms;// m x n matrix of rooms
private ArrayList<Wall> walls; // List of walls
private Random rand;// for random wall
private int height;// height of matrix
private int width;// width of matrix
private int num;// incrementor
private JoinRoom ds;// union paths
// paint methods //
private int x_cord; // x-axis rep
private int y_cord;// y-axis rep
private int roomSize;
private int randomWall;
private int create;
int mazectr;
public static int m;// these are variables for the size of maze (m x n)
public static int n;
public Maze(int m, int n) {
JPanel j = new JPanel();
final JFrame f = new JFrame();
this.height = m;
this.width = n;
rooms = new Room[m][n];
walls = new ArrayList<Wall>((m - 1) * (n - 1));
long startTime = System.currentTimeMillis();
generateRandomMaze();
long endTime = System.currentTimeMillis();
final JLabel jl = new JLabel("Time Taken: " + (endTime-startTime) + "ms");
final JButton y = new JButton("OK");
j.add(jl);
j.add(y);
f.add(j);
y.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e)
{
f.setVisible(false);
}
});
f.setVisible(true);
f.setSize(100, 100);
//jl.setLocation(1000, 1500);
//jl.setBounds(0, 0, 110, 130);
setPreferredSize(new Dimension(800, 700));
}
private void generateRandomMaze() {
generateInitialRooms();// see next method
ds = new JoinRoom(width * height);
rand = new Random(); // here is the random room generator
num = width * height;
while (num > 1) {
// when we pick a random wall we want to avoid the borders getting eliminated
randomWall = rand.nextInt(walls.size());
Wall temp = walls.get(randomWall);
// we will pick two rooms randomly
int roomA = temp.currentRoom.y + temp.currentRoom.x * width;
int roomB = temp.nextRoom.y + temp.nextRoom.x * width;
// check roomA and roomB to see if they are already members
if (ds.find(roomA) != ds.find(roomB)) {
walls.remove(randomWall);
ds.unionRooms(ds.find(roomA), ds.find(roomB));
temp.isGone = true;
temp.currentRoom.adj.add(temp.nextRoom);
temp.nextRoom.adj.add(temp.currentRoom);
num--;
}// end of if
}// end of while
}
// name the room to display
private int roomNumber = 0;
private static Label input;
private static Label input2;
/**
* Sets the grid of rooms to be initially boxes
* This is self explanitory, we are only creating an reverse L for all
* The rooms and there is an L for the border
*/
private void generateInitialRooms() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// create north walls
rooms[i][j] = new Room(i, j);
if (i == 0) {
rooms[i][j].north = new Wall(rooms[i][j]);
} else {
rooms[i][j].north = new Wall(rooms[i - 1][j], rooms[i][j]);
walls.add(rooms[i][j].north);
}
if (i == height - 1) {
rooms[i][j].south = new Wall(rooms[i][j]);
}
if (j == 0) {
rooms[i][j].west = new Wall(rooms[i][j]);
} else {
rooms[i][j].west = new Wall(rooms[i][j - 1], rooms[i][j]);
walls.add(rooms[i][j].west);
}
if (j == width - 1) {
rooms[i][j].east = new Wall(rooms[i][j]);
}
rooms[i][j].roomName = roomNumber++;// we will name the rooms
}
}
// initalize entrance and exit
rooms[0][0].west.isGone = true;// you can replace .west.isGone with .north.isGone
// this is just saying the roomName for top left is 0
rooms[0][0].roomName = 0;
// we will remove the south wall of the last room
rooms[height - 1][width - 1].south.isGone = true;
// this is just saying the roomName for bottom right is the last element in the mxn room matrix
rooms[height - 1][width - 1].roomName = (height * width);
}
public void paintComponent(Graphics g) {
x_cord = 40;
y_cord = 40;
Thread t = new Thread();
// could have taken height as well as width
// just need something to base the roomsize
roomSize = (width - x_cord) / width + 20;
// temp variables used for painting
int x = x_cord;
int y = y_cord;
for (int i = 0; i <= height - 1; i++) {
for (int j = 0; j <= width - 1; j++) {
if (!(rooms[i][j].north.isGone)) {
g.drawLine(x, y, x + roomSize, y);
}//end of north if
// west wall not there draw the line
if (rooms[i][j].west.isGone == false) {
g.drawLine(x, y, x, y + roomSize);
}// end of west if
if ((i == height - 1) && rooms[i][j].south.isGone == false) {
g.drawLine(x, y + roomSize, x + roomSize,
y + roomSize);
}// end of south if
if ((j == width - 1) && rooms[i][j].east.isGone == false) {
g.drawLine(x + roomSize, y, x + roomSize,
y + roomSize);
}// end of east if
x += roomSize;// change the horizontal
try
{
Thread.sleep(50);
} catch (Exception e) {};
t.start();
}// end of inner for loop
x = x_cord;
y += roomSize;
}// end of outer for loop
}
public static void main(String[] args) throws IOException {
// use JFrame to put the created panel on
String path = "E:\\Iskul\\trys\\tryy\\bin\\GUI.jpg";
File file = new File("E:\\Iskul\\trys\\tryy\\bin\\GUI.jpg");
BufferedImage image = ImageIO.read(file);
File fileRec = new File("E:\\Iskul\\trys\\tryy\\bin\\re.jpg");
BufferedImage imageRec = ImageIO.read(fileRec);
File fileHex = new File("E:\\Iskul\\trys\\tryy\\bin\\hexx.jpg");
BufferedImage imageHex = ImageIO.read(fileHex);
final JFrame frame = new JFrame("Prim's Algorithm");
final JPanel jp = new JPanel();
final JTextField input = new JTextField(10);
final JTextField input2 = new JTextField(10);
final JButton jb = new JButton(new ImageIcon(imageRec));
jb.setBorder(BorderFactory.createEmptyBorder());
final JButton jb1 = new JButton(new ImageIcon(imageHex));
jb1.setBorder(BorderFactory.createEmptyBorder());
final JLabel label = new JLabel(new ImageIcon(image));
jb.setLocation(100, 10);
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(795, 501));
jp.add(input);
jp.add(input2);
frame.add(jp);
jp.add(jb);
jp.add(jb1);
//jb.setImage(image);
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//int mazectr = 1;
int m = Integer.valueOf(input.getText());
int n = Integer.valueOf(input2.getText());
frame.remove(label);
frame.remove(jp);
//frame.add(new Maze(m,n));
frame.getContentPane().add(new Maze(m, n));
frame.pack();
}});
jb1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//int m = Integer.valueOf(input.getText());
//int n = Integer.valueOf(input2.getText());
Hexa1 hexa = new Hexa1();
hexa.main();
//hexa.run();
}
});
}}// end of main
Your code wont work, you cant do an sleep in the Paint method, because if you do so, he wont draw, he just waits and at the end he'll draw your whole image.
If you want to do a nice effect, you should draw one step after the other but you should be aware that this is a lot of work to realize...
I am currently developing a booking system as a task for my degree. I need the seating plan to be "saved/stored" for each showing time (radio buttons), so that e.g. If I book 2 tickets at 13:00, I can also book 2 tickets on the same spot for 15:00. What is the best way of doing this?
PS: I'm not making use of a database and I would prefer not to; due to task's requirements.
Here's my code, please run it if you can.
// CM1203 Fundamentals of Computing with Java; Second Assignement.
// Walter Carvalho - C1001984; 2012.
// Cardiff University
// Load Libraries
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
public class cinemaSystem extends JFrame implements ActionListener {
// Global Variables
boolean lselected, rselected, mselected;
double chargeDue;
int a, b, c;
static Ticket oapticket, childticket, adultticket;
JFrame frame = new JFrame(); // Creates JFrame
JLabel title, lchild, ladult, loap, ltotalprice, time;
JTextField child, adult, oap, totalprice;
JButton submit;
JRadioButton time1, time2, time3, time4, time5; // Radio Butons
JToggleButton l[][], m[][], r[][]; // Names grid of JButtons
JPanel panel1, panel2, panel3, panel4, panel5, panel6;
ArrayList<String> seatsAvailable = new ArrayList<String>();
ArrayList<String> coupon = new ArrayList<String>();
// Constructor
public cinemaSystem(){
title = new JLabel("Cinema Booking System");
title.setFont(new Font("Helvetica", Font.BOLD, 30));
title.setLocation(12,5);
title.setSize(600, 60);
frame.setLayout(null); // Setting Grid Layout
// panel1.setLayout(new GridLayout(seat,row));
l = new JToggleButton[4][4]; // Allocating Size of Grid
panel1 = new JPanel(new GridLayout(4,4));
panel1.setBounds(20, 95, 220, 140);
for(int y = 0; y <4 ; y++){
for(int x = 0; x < 4; x++){
l[x][y] = new JToggleButton("L" + y + x); // Creates New JButton
l[x][y].addActionListener(this);
seatsAvailable.add("L" + y + x);
panel1.add(l[x][y]); //adds button to grid
}
}
m = new JToggleButton[4][2]; // Allocating Size of Grid
panel2 = new JPanel(new GridLayout(2,4));
panel2.setBounds(240, 165, 220, 70);
for(int y = 0; y <2 ; y++){
for(int x = 0; x < 4; x++){
m[x][y] = new JToggleButton("M" + y + x); // Creates New JButton
m[x][y].addActionListener(this);
seatsAvailable.add("M" + y + x);
panel2.add(m[x][y]); //adds button to grid
}
}
r = new JToggleButton[4][4]; // Allocating Size of Grid
panel3 = new JPanel(new GridLayout(4,4));
panel3.setBounds(460, 95, 220, 140);
for(int y = 0; y <4 ; y++){
for(int x = 0; x < 4; x++){
r[x][y] = new JToggleButton("R" + y + x); // Creates New JButton
r[x][y].addActionListener(this);
seatsAvailable.add("R" + y + x);
panel3.add(r[x][y]); //adds button to grid
}
}
panel4 = new JPanel(new FlowLayout());
panel4.setBounds(0, 250, 300, 70);
lchild = new JLabel("Child");
child = new JTextField("0", 2);
child.addActionListener(this);
ladult = new JLabel("Adult");
adult = new JTextField("0", 2);
adult.addActionListener(this);
loap = new JLabel("OAP");
oap = new JTextField("0", 2);
oap.addActionListener(this);
submit = new JButton("Submit");
submit.addActionListener(this);
oapticket = new Ticket(4.70);
childticket = new Ticket(3.50);
adultticket = new Ticket(6.10);
child.addKeyListener(new MyKeyAdapter());
oap.addKeyListener(new MyKeyAdapter());
adult.addKeyListener(new MyKeyAdapter());
panel4.add(lchild);
panel4.add(child);
panel4.add(ladult);
panel4.add(adult);
panel4.add(loap);
panel4.add(oap);
panel4.add(submit);
panel5 = new JPanel(new FlowLayout());
panel5.setBounds(240, 250, 300, 70);
ltotalprice = new JLabel("Charge Due (£): ");
totalprice = new JTextField("£0.00", 5);
totalprice.setEnabled(false);
panel5.add(ltotalprice);
panel5.add(totalprice);
panel6 = new JPanel(new FlowLayout());
panel6.setBounds(0, 55, 560, 30);
time = new JLabel("Please select a film time: ");
time1 = new JRadioButton("13:00", true);
time2 = new JRadioButton("15:00", false);
time3 = new JRadioButton("17:00", false);
time4 = new JRadioButton("19:00", false);
time5 = new JRadioButton("21:00", false);
ButtonGroup group = new ButtonGroup();
group.add(time1);
group.add(time2);
group.add(time3);
group.add(time4);
group.add(time5);
panel6.add(time);
panel6.add(time1);
panel6.add(time2);
panel6.add(time3);
panel6.add(time4);
panel6.add(time5);
time1.addActionListener(this);
time2.addActionListener(this);
time3.addActionListener(this);
time4.addActionListener(this);
time5.addActionListener(this);
frame.add(title);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.add(panel4);
frame.add(panel5);
frame.add(panel6);
frame.setPreferredSize(new Dimension(700, 350));
frame.setTitle("Cinema Booking");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
// Calculates Charge Due for current transaction.
public double calcChargeDue(){
DecimalFormat df = new DecimalFormat("#.##");
double chargeDue = 0.0;
chargeDue = (a*childticket.price) + (b*oapticket.price) + (c*adultticket.price);
totalprice.setText("£"+df.format(chargeDue));
return chargeDue;
}
// Method to check if the number of people matches the number of seats selected.
public void check(){
int check = coupon.size();
int noTickets = a + b + c;
if (check != noTickets){
submit.setEnabled(false);
}
else {
submit.setEnabled(true);
}
}
// Ticket Object
public class Ticket {
double price;
// Constructor
public Ticket(double cost) {
price = cost;
}
public double getTicketPrice() {
return price;
}
}
public void actionPerformed(ActionEvent e)
{
a = Integer.parseInt(child.getText());
b = Integer.parseInt(oap.getText());
c = Integer.parseInt(adult.getText());
for(int y = 0; y < 4; y++){
for(int x = 0; x < 4; x++){
lselected = l[x][y].isSelected();
rselected = r[x][y].isSelected();
if (e.getSource() == l[x][y]) {
if(lselected == true){
coupon.add(e.getActionCommand());
calcChargeDue();
check();
}
else {
coupon.remove(e.getActionCommand());
check();
}
}
if (e.getSource() == r[x][y]) {
if(rselected == true){
coupon.add(e.getActionCommand());
calcChargeDue();
check();
}
else {
coupon.remove(e.getActionCommand());
check();
}
}
if (e.getSource() == oap){
calcChargeDue();
check();
}
if (e.getSource() == adult){
calcChargeDue();
check();
}
if (e.getSource() == child){
calcChargeDue();
check();
}
}
}
for(int y = 0; y < 2; y++){
for(int x = 0; x < 4; x++){
mselected = m[x][y].isSelected();
if (e.getSource() == m[x][y]) {
if(mselected == true){
coupon.add(e.getActionCommand());
calcChargeDue();
check();
}
else {
coupon.remove(e.getActionCommand());
check();
}
}
}
}
if(time1 == e.getSource()){
}
if(time2 == e.getSource()){
}
if(time3 == e.getSource()){
}
if(time4 == e.getSource()){
}
if(time5 == e.getSource()){
}
if(submit == e.getSource()) {
for(int y = 0; y < 4; y++){
for(int x = 0; x < 4; x++){
lselected = l[x][y].isSelected();
rselected = r[x][y].isSelected();
if (lselected == true) {
l[x][y].setEnabled(false);
}
if (rselected == true) {
r[x][y].setEnabled(false);
}
}
}
for(int y = 0; y < 2; y++){
for(int x = 0; x < 4; x++){
mselected = m[x][y].isSelected();
if (mselected == true) {
m[x][y].setEnabled(false);
}
}
}
Collections.sort(coupon);
System.out.println("Here's your ticket:");
System.out.println(coupon);
System.out.println("Child: " + child.getText());
System.out.println("Adult: " + adult.getText());
System.out.println("OAP: " + oap.getText());
System.out.println("Total Price: " + totalprice.getText());
System.out.println("Thank you. Enjoy your film.");
System.out.println(" ");
coupon.clear();
child.setText("0");
adult.setText("0");
oap.setText("0");
}
}
// Main Class
public static void main(String[] args) {
new cinemaSystem(); //makes new ButtonGrid with 2 parameters
}
}
Related: Java: Disable all JToggleButtons after Submission — setEnabled(false);
If you already have it working for one booking time, all you need to do is take all your data structures used for storing information about that booking time and double them up to support several independent booking times.
For instance, ArrayList<String> seatsAvailable = new ArrayList<String>(); will become:
Dictionary<Time, ArrayList<String> > seatsAvailable =
new Dictionary<Time, ArrayList<String> >();
Time firstBooking = new Time(13,0,0);
Time secondBooking = new Time(15,0,0);
seatsAvailable.put( firstBooking , new ArrayList<String>() );
seatsAvailable.put( secondBooking , new ArrayList<String>() );
Now you can keep track of two completely seperate ArrayLists of seatsAvailable.
How to draw a numbers onto a panel in a 2d array for a game board?
import javax.swing.*;
import java.awt.*;
public class board2 extends JFrame {
JFrame frame;
JPanel squares[][] = new JPanel[10][10];
public board2() {
setSize(500, 500);
setLayout(new GridLayout(10, 10));
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
squares[i][j] = new JPanel();
if ((i + j) % 2 == 0) {
squares[i][j].setBackground(Color.black);
} else {
squares[i][j].setBackground(Color.white);
}
add(squares[i][j]);
}
}
}
}
I would like to number the panels in the way shown here.
Summary: You should add a label to each of your panels that displays the number.
A couple points:
If your class extends JFrame, you dont need to have one as a member variable.
It isnt clear that you are setting your frame visible anywhere (perhaps you just didnt include that code in your example. I am bringing this up because there is no declaration of what is actually wrong) with your code so far - so perhaps it just inst showing up, so a setVisible(true) would be important.
If you want to add numbers, you need to ad a JLabel to each as you iterate. It would be good to have the foreground of these JLabel instances alternate foreground. You can create the label by using your i and j counters to calculate your square's number.
It would be good to encapsulate the numbering mechanism in a separate method, as you have noted that the specification requires alternating rows to count from the left or the right. Something like the following:
JLabel label = new JLabel(getCellNumber(((i*10)+j),10) + "");
and then a crude version of the getCellNumber() method could look something like this:
private int getCellNumber(int id, int columnCnt) {
int rowID = (id) / columnCnt;
int colID = (id) % columnCnt;
if (rowID %2 == 1) {
colID = columnCnt - colID;
} else {
colID++;
}
return 101 - ((rowID * columnCnt) + colID);
}
This is your program:
import javax.swing.*;
import java.awt.*;
public class ChessBoard extends JFrame {
JFrame frame;
JPanel squares[][] = new JPanel[10][10];
public ChessBoard() {
setName("Chess Board");
setSize(500, 500);
setLayout(new GridLayout(10, 10));
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
JLabel label = new JLabel(getCellNumber(((i*10)+j),10) + "");
JPanel panel = new JPanel();
panel.add(label);
squares[i][j] = panel;
if ((i + j) % 2 == 0) {
squares[i][j].setBackground(Color.black);
label.setForeground(Color.white);
} else {
squares[i][j].setBackground(Color.white);
label.setForeground(Color.black);
}
add(squares[i][j]);
}
}
setVisible(true);
}
public static void main(String [] args){
new ChessBoard();
}
private int getCellNumber(int id, int columnCnt) {
int rowID = (id) / columnCnt;
int colID = (id) % columnCnt;
if (rowID %2 == 1) {
colID = columnCnt - colID;
} else {
colID++;
}
return 101 - ((rowID * columnCnt) + colID);
}
}