Search code examples
javaarraysswingjlabel

Java - Changing A JLabel With Texts Stored in An Array


Hello World, Am kinda new to java and i am trying to create a method that changes a JLabel's text to some text stored in an array when an action happens, somthing like this :

     JLabel one = new JLabel("Hello World");
     JButton b1 = new JButton("Next");
     JButton b2 = new JButton("Prev");

     String[] main = ["LoveLace","Dynamics","Creed","Main"];
     b1.addActionListsner(new ActionListener() {
       actionPerformed(ActionEvent e) {

          //In here it will load the first indexed string which is "Lovelace"
          //This is where i need help
          //Think of it like a jQuery slider
          //When the next button is clicked, it loads a new word to the element
          //When the prev button is clicked it load the last indexed string of the array

Please This is actually a manual word slider that is changes the text when the next button is clicked and loads the last indexed string of the array when the prev button is clicked, Please i dont hava any idea on how to do this, please help


Solution

  • I think this should work...

    private void yourMethodName(final String newLabelText) {
        one.setText(newLabelText);
    }
    

    if you want to use this method universal...

    private void yourMethodName(final JLabel label, final String newLabelText) {
        label.setText(newLabelText);
    }
    

    now you just need call this method(s) with the parameter(s) you want to change. If the changes are not diesplayed, you need to repaint the container where your stuff is in. If you don't use a container I would advice you to create one and add all your stuff into this container. The aswer of this thread might be helpful.