Question

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

Was it helpful?

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.

OTHER TIPS

ok this is really bad code, as i'm beginner too. if your array is of this size only then:

 b1.addActionListsner(new ActionListener() {
   actionPerformed(ActionEvent e) {

     switch(one.getText()){

         case main[0] : one.setText(main[1]);
                        break;
         case main[1] : one.setText(main[2]);
                        break;
                     and so on....
                        }
                   }

if JRE version is below 1.7 use ENUM in switch instead of passing the string to case as it wont work.

this will be tedious if your array is large. In that case use a counter variable and set it with the array's index, and make sure you put conditions that your counter variable doesnt exceed the max or min index of your array!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top