0

I'm doing a small calculator using JLabel and I'm asking how to substring a JLabel,

public class plusListener implements ActionListener {
public void actionPerformed (ActionEvent event){
    s1 = label.getText();
    d1 = Double.parseDouble(s1);
    int x = s1.indexOf("+");
    label.setText(label.getText() +" + ");
    }
}

So what I'm trying to do is to let the JLabel print the numbers I'm typing and at the same time calculate it, for example i want 5 + 2, so the JLabel would print 5 + 2 = 7

But my main problem here is that I'm stuck at saving the second number to calculate it.

  • Personally, I would re-create the text every time, based on the available information and not rely on the previous text. This is where some kind of model would come in handy – MadProgrammer Nov 20 '19 at 22:02
  • @MadProgrammer so I would make the label null then store the new number in it? – Raphael Eid Nov 20 '19 at 22:06
  • 2
    `label.setText("this is some new text which will erase the original");` ... I might also consider using a non-editable `JTextField`, which will overcome `JLabel`s desire to truncate the text with `...` when it becomes to long to display, but that's me. One thing you might want to use is a some kind of `Stack` to hold the data and then use it to generate the result through some kind of model – MadProgrammer Nov 20 '19 at 22:14
  • Here is an example of using a JTextField to insert text as it is enterid by the user: https://stackoverflow.com/questions/33739623/how-to-add-a-shortcut-key-for-a-jbutton-in-java/33739732#33739732 – camickr Nov 21 '19 at 01:02

0 Answers0