+ 1

How to print my text in the same JFrame by clicking my JButton ?

Hi so I m working on a program that is a code generator that generate random codes i've setted up the user interface with a Jbutton to generate the code but I don't know how to make that JButton print the code on the same JFrame when clicked on Also as this generate random codes differents everytime this is not a simple String but a method so I would like to get the text output of that method displayed on the same JFrame where there is already my user interface by clicking on my JButton . Anybody know how to do that? I'm really struggling with that so any help is really appreciated ^^

20th May 2019, 4:13 PM
eden annonay
eden annonay - avatar
3 Antworten
+ 1
Do you want to print it in a JLabel or where else? Also, can you please write the method so I can understand what type of method it is?
20th May 2019, 6:10 PM
PacoB
PacoB - avatar
0
You can for example add a JTextArea to your frame and add the text to it. You can make a method that return a String: public String textMethod(){ return "blablabla"; } If you mean you wanna output different text every time you click you can do it like this: public String textMethod(){ String[] arr = {"aaa","bbb","ccc","dd"}; Random rand = new Random(); int rn = rand.nextInt(arr.length); return arr[rn]; } And in your actionPerformed method: String text = textMethod(); YourJTextArea.setText(text);
20th May 2019, 6:00 PM
JavaBobbo
JavaBobbo - avatar
0
Yes if possible i'd like to print it in a JLabel but I'd also like that the user can copy/paste the text generated wich I think isn't possible in a JFrame As for the method : public void generateCode() { Code nmb = new Code(); System.out.print ("Your code is "); nmb.randomNumber();nmb.randomLetterCap();nmb.randomLetter();nmb.randomLetter();nmb.randomNumber();nmb.randomLetterCap(); } } class Code { public void randomNumber(){ Random rand = new Random (); int n= rand.nextInt(100); n+=1; System.out.print(n); } public void randomLetter(){ Random rand1 = new Random (); char c = (char)(rand1.nextInt(26)+'a'); System.out.print(c); } public void randomLetterCap(){ String myString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Random randomNumbero = new Random(); for (int i = 0; i < 1; i++) { int randomNo = randomNumbero.nextInt(myString.length()); Character character = myString.charAt(randomNo); System.out.print(Character.toUpperCase(character)); } } }
21st May 2019, 1:17 PM
eden annonay
eden annonay - avatar