Skip to content
Advertisement

After inserting values in JTextField, their random value is not shown. How can I fix it?

I wrote this Java Application which is used to extract a random value from those entered in the JTextFields after starting a counter. Compiles and gives no errors, but the ("" +randomElement) value is not displayed.

I created the randomElement property inside the TimerListener class in the actionPerformed() method which starts the counter. At the end of the count the random value taken from the four JTextFields must be shown (as you can see from the code below).

Could you tell me where I’m wrong and how can I fix it?

JavaScript

Advertisement

Answer

To answer your actual question the reason its empty is because you do this in createAndShowGui:

JavaScript

You create a new instance of your Merge class which you then add to the JFrame which you already did in main(string[] args):

JavaScript

So now you have 2 instances of the Merge class in which one is not visible to the user. You should simply do this in createAndShowGui:

JavaScript

HOWEVER

  1. Don’t extend JPanel unnecessarily
  2. Create all Swing components on the EDT via SwingUtilities.invokeLater
  3. Use JFrame#setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); so it completely exits the application unless you only want to dispose?
  4. Call JFrame#pack() only after adding all components
  5. Don’t call setBounds yourself you are using a LayoutManager leave it to that!
  6. No need to call JFrame#getContentPane()#add simply call JFrame#add
  7. You choose a random number for every tick of the timer, why not just choose it once at the end of the timer?
  8. You may also want to disable your textField which counts as people could put input there and mess with your codes logic lol
  9. Don’t declare or initialize variables globally unless they are needed in different methods

enter image description here

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement