java的标签的setText和冲突的setBounds? [英] java label setText and setBounds clashing?

查看:259
本文介绍了java的标签的setText和冲突的setBounds?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个JLabel changint颜色随机之一,而跳跃到一个随机位置,同时改变其文本。

不过的setText和的setBounds似乎发生冲突,我不知道为什么。如果你注释掉的setText那么的setBounds将工作,但他们不会一起工作。

 进口java.awt中的*。
进口的java.util。*;
进口的javax.swing *。公共类test2的扩展JFrame的{私有静态的JLabel标签=新的JLabel(0);
私有静态随机根=新的随机();公开测试2(){
    的JPanel面板=新JPanel();
    panel.add(标签);
    this.add(面板);
}公共静态无效的移动(){
    对(INT I = 0; I&小于10;我++){
        INT N = gen.nextInt(254)+1;
        INTン= gen.nextInt(254)+1;
        INT NNN = gen.nextInt(254)+1;
        label.setText(+ I);
        //定义的setBounds命令不会用的setText命令工作。为什么?
        label.setBounds(N * 2,NN * 2,20,20);
        label.setForeground(新颜色(N,NN,NNN));
        尝试{
            视频下载(200);
        }赶上(例外五){}
    }
}公共静态无效的主要(字串[] args){
    测试2帧=新TEST2();
    frame.setVisible(真);
    frame.setSize(600,600);
    frame.setResizable(真);
    frame.setLocationRelativeTo(NULL);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    移动();
}
}


解决方案

的setBounds不应该用一个非空布局工作,你的问题发生,因为改变JLabel中的文本刺激的JPanel的重新布局,并且由于缺省JPanels使用的FlowLayout,选择JLabel停留在中间的顶部。所以,如果你真的需要这个功能,那么考虑设置JPanel的布局为空,否则使用的JLayeredPane。

 公开测试2(){
     的JPanel面板=新JPanel(NULL);
     panel.add(标签);
     this.add(面板);
  }

此外,你不应该呼吁EDT,Swing线程的Thread.sleep(...)。相反,考虑使用Swing的定时器。

自从我与其他的例子不同意,我将发布什么,我在它的地方,一个使用一个Swing计时器推荐的例子:

 进口java.awt中的*。
java.awt.event中导入*。
进口了java.util.Random;
进口的javax.swing *。@燮pressWarnings(串行)
公共类Test3的继承JPanel {
    私有静态最终诠释SIDE = 600;
    公共静态最终诠释MAX_COUNTER = 20;
    私有静态最终诠释TIMER_DELAY = 400;
    私有静态最终诠释MAX_RAND = 220;
    私人INT计数器= 0;
    私人标签的JLabel =新的JLabel(将String.valueOf(计数器));
    私人随机根=新的随机();
    私人INT [] randNumb =新INT [3];    公共Test3的(){
        集preferredSize(新尺寸(,一面));
        setLayout的(NULL);
        添加(标签);        新的定时器(TIMER_DELAY,新TimerListener())开始()。
    }    私人无效myMove(){
        的for(int i = 0; I< randNumb.length;我++){
            randNumb [I] = gen.nextInt(MAX_RAND);
        }
        label.setText(将String.valueOf(计数器));
        的Label.setSize(label.get preferredSize());
        label.setLocation((SIDE * randNumb [0])/ MAX_RAND,(SIDE * randNumb [1])/ MAX_RAND);
        label.setForeground(新的色彩(randNumb [0],randNumb [1],randNumb [2]));
        重绘();
    }    私有类TimerListener实现的ActionListener {        公共无效的actionPerformed(ActionEvent的五){
            如果(计数器< MAX_COUNTER){
                myMove();
                反++;
            }其他{
                ((定时器)e.getSource())停止();
            }
        }
    }    私有静态无效createAndShowUI(){
        JFrame的帧=新的JFrame(Test3的);
        。frame.getContentPane()增加(新Test3的());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(NULL);
        frame.setVisible(真);
    }    公共静态无效的主要(字串[] args){
        了java.awt.EventQueue.invokeLater(新的Runnable(){
            公共无效的run(){
                createAndShowUI();
            }
        });
    }
}

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 clash and i don't know why. if you comment out the setText then the setBounds will work, but they won't work together.

import java.awt.*;
import java.util.*;
import javax.swing.*;

public class test2 extends JFrame { 

private static JLabel label = new JLabel("0");
private static Random gen = new Random();

public test2() {
    JPanel panel = new JPanel();
    panel.add(label);
    this.add(panel);
}

public static void move() {
    for (int i = 0; i < 10; i++) {
        int n = gen.nextInt(254)+1;
        int nn = gen.nextInt(254)+1;
        int nnn = gen.nextInt(254)+1;
        label.setText(""+i);
        //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();
}
}

解决方案

setBounds shouldn't work with a non-null layout, and your problem is happening because changing the text in the JLabel stimulates a re-layout of the JPanel, and since JPanels by default use FlowLayout, the JLabel stays at the top in the middle. So if you really need this functionality, then consider setting the layout of the JPanel to null, or else use a JLayeredPane.

  public test2() {
     JPanel panel = new JPanel(null);
     panel.add(label);
     this.add(panel);
  }

Also you shouldn't be calling Thread.sleep(...) on the EDT, the Swing thread. Instead consider using a Swing Timer.

Since I disagreed with the other example, I will post an example of what I was recommending in its place, one that uses a Swing Timer:

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;

@SuppressWarnings("serial")
public class Test3 extends JPanel {
    private static final int SIDE = 600;
    public static final int MAX_COUNTER = 20;
    private static final int TIMER_DELAY = 400;
    private static final int MAX_RAND = 220;
    private int counter = 0;
    private JLabel label = new JLabel(String.valueOf(counter));
    private Random gen = new Random();
    private int[] randNumb = new int[3];

    public Test3() {
        setPreferredSize(new Dimension(SIDE, SIDE));
        setLayout(null);
        add(label);

        new Timer(TIMER_DELAY, new TimerListener()).start();
    }

    private void myMove() {
        for (int i = 0; i < randNumb.length; i++) {
            randNumb[i] = gen.nextInt(MAX_RAND);
        }
        label.setText(String.valueOf(counter));
        label.setSize(label.getPreferredSize());
        label.setLocation((SIDE * randNumb[0])/MAX_RAND, (SIDE*randNumb[1])/MAX_RAND);
        label.setForeground(new Color(randNumb[0], randNumb[1], randNumb[2]));
        repaint();
    }

    private class TimerListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (counter < MAX_COUNTER) {
                myMove();
                counter++;
            } else {
                ((Timer)e.getSource()).stop();
            }
        }
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Test3");
        frame.getContentPane().add(new Test3());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

这篇关于java的标签的setText和冲突的setBounds?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆