Search code examples
javaarraysswinguser-interfacejbutton

Connect a java class to a separate GUI Jpanel button and/or textarea?


So im linking a java class with array lists and a random array generator to a separate GUI in the same project. Its a Jeopardy Game, so I need the buttons to "get" the strings from the array list and "check" the answer in another. I need to know how to make the GUI "get" info from the other "classes". Thanks.

(Question&Answer Class Example)

   Random generator = new Random(); 
   int random_int = generator.nextInt(10) + 1;

   double random_int = Math.random() * ( 0 - 24 );     
   String[] am = new String[25];


   String[] ama = new String[25];


   am[0] = "Sam";ama[0] = "Sam";
   am[1] = "Sam";ama[1] = "Sam";
   am[2] = "Sam";ama[2] = "Sam";
  ...
   am[23] = "Sam";ama[23] = "Sam";
   am[24] = "Sam";ama[24] = "Sam";  

  String am_qu = am[random_int];
  String am_an = ama[random_int];

(GUI Jpanel button "Action" Example)

    private void am1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
    JOptionPane.showMessageDialog(null,""+am_qu+); <--That is what I need to work!

}     

The Jeopardy game will have buttons that you click which will show dialog box with question, a button that says answer and when that is clicked it will open an input box to check answer after the final submit.


Solution

  • I'm not entirely sure how your project is set up, or why your code isn't working, but here's a working snippet I literally just shoved into a JFrame of mine:

        final Random generator = new Random(); 
        final String[] am = new String[25];
        final String[] ama = new String[25];
    
        for(int n = 0; n < 25; n++) {
            am[n] = "Sam " + n + " (Q)";
            ama[n] = "Sam " + n + " (A)";
        }
    
        JButton testButton = new JButton("Click This!");
    
        testButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {             
                final int random_int = generator.nextInt(24) + 1;
                System.out.println(random_int);
                JOptionPane.showMessageDialog(null, am[random_int] + " " + ama[random_int]);
            }           
        });
    

    See the image below for output:

    screenshot of output