Reputation: 3998
I had created a basic calculator using Java Swing. The question I have is how to print each calculation on the panel. for example, I have added two numbers, my panel should look something like 2 + 4 = 6, and if I perform another operation it should append another operation in the panel.
My idea: I know I can do with the labels and change the value of the labels, but this is not a good idea since as the operations increase I cannot keep on adding the labels, I believe there should be a way but since I am learning Swing, I need some help from experts.
Upvotes: 2
Views: 1056
Reputation: 12393
The panel will most likely read from a String. Try using StringBuilder or StringBuffer to append to the String as input is being entered.
This way, you can also modify/delete the final " = 6" and add another "+ 6 = 10" if you choose to add more operations. Then use toString() when you want to refresh the final outcome on the panel without creating a whole new String.
Upvotes: 0
Reputation: 36
Either make one JLabel and instead of adding new ones and displaying those, you can get the text using getText() on the JLabel, then append the text you want to add and finally use setText() sending your new and complete text so that the one JLabel has all text in it. OR You could make a JPanel or JComponent (something that you can draw on with paintComponent(Graphics g) and use g.drawString() that takes a string to draw (which would be your full appended text) and the x, y location at which to draw e.g. g.drawString("2 + 6 = 8", 100, 120); and you would have to call repaint() on the component in order to update the text. make sure you can store the string somewhere the component can access while drawing.
I hope this helps.
Upvotes: 0
Reputation: 103135
There are two possibilities:
Use a JTextArea and set it to be non-editable. The text area control will allow you to add multiple lines of text so that you can keep appending operations as you like.
textArea.setEditable(false);
Draw the text as graphics on a Canvas. This is a little more involved but you have more control over the way the text look and how it is formatted.
g.drawString("a + b = c", x, y);
Upvotes: 4