0

I have a string which is getting the data from a jtextfield, and then I substring this data into 3 letters in three strings (String first, second,third)

try {
String text,first,second,third,result;
Swing get = new Swing();
text = get.getMyText();
first = text.substring(0,1);
second = text.substring(1,2);
third = text.substring(2,3);
result = first + third + second;
if(text.isEmpty) {
throw new Exception();
    }
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Empty","....",JOptionPane.ERROR_MESSAGE);
    }

I get this strange message from the system instead of the JOptionPane message:

Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

any clue of what I miss here ?

for your information, I've tried as well the below, as well still the same error

if(first.isEmpty() || second.isEmpty() || third.isEmpty()) {
       // my message
    }

my Swing class is as follow:

public class Swing {

    // second line of the frame

    private static JFrame window; // creating the frame
    private static JTextField text; 
    // setting the frame
    /**
     * @wbp.parser.entryPoint
     */
    public void Run() {

        window = new JFrame("Tool");
        window.setResizable(false);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.getContentPane().setBackground(new Color(230, 230, 250));
        window.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        window.getContentPane().isOpaque();

        window.getContentPane().setLayout(null);

        // the textfield
        text = new JTextField();
        text.setHorizontalAlignment(SwingConstants.CENTER);
        text.setForeground(Color.BLUE);
        text.setFont(new Font("David", Font.PLAIN, 20));
        text.setColumns(10);
        text.setBounds(504, 11, 149, 20);
        window.getContentPane().add(text);

        // adding the button from the other class (MyBtn)
        MyBtn addBTN = new MyBtn();
        window.getContentPane().add(addBTN.run());

        // setting the frame
        window.setVisible(true);
        window.setSize(750, 500);
        window.setLocationRelativeTo(null); 
    }

    // preparing the getters for the input
    public String getText() {
        return text.getText();
    }
  • 1
    Hint: you want us to spend our time to help you; so: you please spend some time to make that as easy as possible. That starts with properly formatted code examples. And, side note: your variable names are not helpful. They don't tell much what the object is really about. first, second, third ... what? And what on earth is a "Swing" class about? That name only confuses readers! And hint no.2 : such problems can very often be resolved by simply adding trace statements. If you had printed your text string right after fetching it ... you would have saved the time to write up your question. – GhostCat Aug 07 '16 at 21:06
  • Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Aug 07 '16 at 21:23

1 Answers1

1

You need to test if text is empty before trying to extract subStrings from it as my bet is that you're likely trying to get a subString from an empty String, and for this reason you're seeing the runtime exception.

My bet is that your Swing class is a GUI, possibly a JFrame, that you're creating a non-displayed Swing object and trying to extract text from it, and since it isn't displayed, the user hasn't entered any data into the text fields. Perhaps instead you want to extract the text from a completely separate and unique displayed Swing object. But again, this is just a guess. If I'm right, then you'll want to pass in a reference to the visualized GUI component here where it is needed and not create a new one unnecessarily.

Also what class is catch (exception e) {? Did you mean to capitalized Exception?


Something like:

// get should be set with a valid reference to the displayed
// Swing object. Don't create a **new** Swing object
// Swing get = new Swing();  // no!

String text = get.getMyText().trim();

if (text.isEmpty() || text.length() < 4) {
    // show error message in JOptionPane
} else {
    String text,first,second,third,result;
    first = text.substring(0,1);
    second = text.substring(1,2);
    third = text.substring(2,3);
    result = first + third + second;
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thank you for your answer, Swing is a name of class where I created my window and the component, and about the catch, yes I meant it as Exception, just I wrote it wrong in my question, sorry. Could you please explain your solution by writing how my code should be? Thank you again – Aboelmagd Saad Aug 07 '16 at 20:55
  • 2
    @AboelmagdSaad: I can't correct your code fully (and we don't generally write code for you), but again, you should check if text is empty **first**. But for more extensive help, you need to show and tell more, specifically about Swing. Is it a class that extends JFrame? Is it already visible when the code above is called? Where is this code called in relationship to the Swing class? Please clarify for us. Also consider creating and posting a valid [mcve]. – Hovercraft Full Of Eels Aug 07 '16 at 20:59
  • @AboelmagdSaad: see edit. But again, you are not handing Swing correctly in all likelihood. One thing you should not do to solve this is to use static methods and fields (just in case this occurred to you). – Hovercraft Full Of Eels Aug 07 '16 at 21:02
  • @AboelmagdSaad: That JFrame field and JTextField neither should be static -- that's a mistake. Also the Swing object that you care about is the one that you've called `Run()` on (which you should rename to `run()`). – Hovercraft Full Of Eels Aug 07 '16 at 21:09
  • I'm not asking to generate me a code, just asking for help to tell me what I miss, I'm still in my first steps with Java, and I expect that I will do a mistakes, and this is how I will learn, and that's why I ask you here fantastic guys for help to correct me, I only test what I learned. – Aboelmagd Saad Aug 07 '16 at 21:12
  • 1
    @AboelmagdSaad: I'm trying to help you for gosh's sake – Hovercraft Full Of Eels Aug 07 '16 at 21:13
  • @AboelmagdSaad: or if you're trying to use this window as a dialog window, then perhaps that's what you need to do -- use a JDialog and not a JFrame, but again do tell us more about how this code is used in your program and how Swing is used as well. – Hovercraft Full Of Eels Aug 07 '16 at 21:47
  • I know you are trying to help, but I feel lost :D, too much info. My swing contains only the components. There is a main class which runs the other 2 classes (Swing + MyBtn) All the other exceptions works perfect, only this exception if the textfiled text is nothing is not working for me, will try to analyze it more . I appreciate your suggestion, but unfortunately it didn't help :( I'm going crazy, stupid error and as well stupid me for not understanding it :D !! – Aboelmagd Saad Aug 07 '16 at 22:42