使用按钮来回切换三个标签之间的文本

时间:2018-01-23 18:12:45

标签: java swing jlabel

我想知道如何只需按一下按钮,就可以反复地,来回地在三个标签之间切换文字。

1 个答案:

答案 0 :(得分:0)

您可以使用Random();选择随机JLabel和随机字词。

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;

public class randomDAMN extends JFrame {

randomDAMN() {
    JButton b1 = new JButton("Change");
    JLabel l1 = new JLabel();
    JLabel l2 = new JLabel();
    JLabel l3 = new JLabel();
    ArrayList<Object> o = new ArrayList<Object>();
    String[] word1 = { "Why", "Damn", "Woah", "this", "hell", "question" };
    Random r = new Random();
    add(l1);
    add(l2);
    add(l3);
    add(b1);
    o.add(l1);
    o.add(l2);
    o.add(l3);
    b1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            int selectLabel = r.nextInt(o.size());
            int selecteditem = r.nextInt(word1.length);
            abc a = new abc(selectLabel, o, word1, selecteditem);
            a.ran();
        }
    });
    setSize(300, 300);
    setLayout(new GridLayout(4, 1));
    setResizable(false);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

    public static void main(String[] args) {
        new randomDAMN();
    }
}

class abc {
    int selectLabel;
    ArrayList<Object> o;
    String[] word1;
    int selecteditem;

    abc(int selectLabel, ArrayList<Object> o, String[] word1, int selecteditem) {
        this.selectLabel = selectLabel;
        this.o = o;
        this.word1 = word1;
        this.selecteditem = selecteditem;
    }

    void ran(){
        ((JLabel) o.get(selectLabel)).setText(word1[selecteditem]);
    }
}