I will give you a snippet of my code:
JButton button = new JButton("Flip");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Flips flip = new Flips();
flipsLabel.setText(Arrays.toString(flip.hAndT));
flip.tailsCount();
tailsLabel.setText("Total Tails " + Integer.toString(flip.tCount));
flip.headsCount();
headsLabel.setText("Total Tails " + Integer.toString(flip.hCount));
}
});
The above is all working because the tCount
and hCount
are variables so I can set them as text in the JLabels.
However, I have the following method that I want to print to a JLabel as well:
public static void headsCount() {
System.out.println();
System.out.println("Heads");
System.out.println("=====");
for (int i = 0; i < HandT.length; i++) {
if (hAndT[i].equals("Head")) {
System.out.println("index " + Integer.toString(i));
hCount++;
}
}
}
The output is multiple lines for the indices where heads falls in an array. I cannot print this void method by setting it as text for a button action because it is a primitive type.
Will I have to turn the method into a return type and return an array of some sort with this information so I can print it to a JLabel?
Will I have to turn the method into a return type
Yes, you would probably return a String
.
Instead of using the System.out.println(), you might use a StringBuilder
and keep appending the text to the StringBuilder
.
Then you can simply use the toString()
method of the StringBuilder
to return the complete String
.
so I can print it to a JLabel?
I doubt you would use a JLabel, since a JLabel is not designed to display multiple lines of text. You might instead use a JTextArea
.
If you want to use a JLabel then you could still use the StringBuilder to build HTML to display in the Label.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments