java label setText and setBounds clashing?

前端 未结 2 668
暖寄归人
暖寄归人 2020-12-21 06:41

I would like to have a JLabel changint color to a random one, while jumping to a random position, and while changing its text.

but the setText and setBounds seem to

2条回答
  •  眼角桃花
    2020-12-21 07:03

    Don't know why it's happening, but here's an ugly work-around:

    package com.me;
    
    import java.awt.Color;
    import java.util.Random;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class test2 extends JFrame {
    
    private static int i;
    
    private static JLabel label = new JLabel("0"){
    @Override
    public String getText(){
        return i+"";
    }
    };
    private static Random gen = new Random();
    
    public test2() {
        JPanel panel = new JPanel();
        panel.add(label);
        this.add(panel);
    }
    
    public static void move() {
        for (i = 0; i < 10; i++) {
            int n = gen.nextInt(254)+1;
            int nn = gen.nextInt(254)+1;
            int nnn = gen.nextInt(254)+1;
            //the setBounds command will not work with the setText command. why?
            label.setBounds(n*2, nn*2, 20, 20);
            label.setForeground(new Color(n, nn, nnn));
            try {
                Thread.sleep(200);
            } catch (Exception e) {}
        }
    }
    
    public static void main(String[] args) {
        test2 frame = new test2();
        frame.setVisible(true);
        frame.setSize(600, 600);
        frame.setResizable(true);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        move();
    
    }
    

    }

提交回复
热议问题