0

java file in a same package. Its bus booking system, one is Reservation.java that has the program and the other is JPanel.java GUI. My problem is: I wanna increase counter in Main.java by pressing button in JPanel.java

Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();

    JPanel panel = new JPanel();
    frame.getContentPane().add(panel);

JPanel.java

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    BookWindow window = new BookWindow(); //not working
    i++;
}    

Thank you <3

  • Basic approach woukd be: implement a new class that `extends Jpanel`, e.g. `MyJPanel`, create a field `int mainValue` there and increase its value in `jButton2ActionPerformed` method. Finally, add a getter to `mainValue` field and thus you can get its value in Main – Ivan Pronin May 16 '17 at 19:41
  • `JPanel.java` ? Have you declared your own class called `JPanel`? That's very confusing. I highly recommend you call it something else to avoid any ambiguity. – Michael May 16 '17 at 19:45
  • @IvanPronin Thank you for your reply. So in my main class i have seats[] then i'll add getter by public int getSeats(){ return seats; } but its not working how do i get array? and what do i type in jButton2ActionPerformed – Тэмүүжин Цогоо May 16 '17 at 19:47
  • @Michael yeah its really confusing I'm new so i didn't knew it was used alot :)) I still don't understand what to type under jButton2ActionPerformed :( – Тэмүүжин Цогоо May 16 '17 at 19:49
  • Possible duplicate of [Java AWT/SWT/Swing: How to plan a GUI?](http://stackoverflow.com/questions/1742001/java-awt-swt-swing-how-to-plan-a-gui) – Catalina Island May 17 '17 at 09:58

1 Answers1

0

How about declaring your counter as a static variable in your 'Main' class and adding a static method to increment your counter:

public final class Main extends Application {
 private static int counter=0;

 static void incrementMainCounter()
  {
   counter++;
  }

 public static void main(String args[]) {
    JFrame frame = new JFrame();

    JPanel panel = new JPanel();
    frame.getContentPane().add(panel);
 }

}

Then just call your increment function whenever you need to:

 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    BookWindow window = new BookWindow(); //not working
    incrementMainCounter();
}   
  • private static int bookWindow() { for (int i = 0; i < 20; i++) { if (seats[i] == 0) { seats[i] = 1; return i + 1; } } return -1; } my code is this it checks if its full or not, i used array. I just wanna call this function to the ActionListener in JPanel.java i think that will make it work – Тэмүүжин Цогоо May 16 '17 at 19:57