<b>JLabel告示栏文字转动效果</b>[Java编程]
本文“<b>JLabel告示栏文字转动效果</b>[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
首先要掌握一个概念:一个字符串在计算机屏幕中所占的像素,比方说取一个JLabel里面的Text所占的宽和高,办法以下: (主要用到FontMetrics类)
import java.awt.FontMetrics;
import javax.swing.JLabel;
JLabel label = new JLabel("test Label ");
FontMetrics metrics = label.getFontMetrics(label.getFont());
int textH = metrics.getHeight(); //字符串的高,只和字体有关
int textW = metrics.stringWidth(label.getText()); //字符串的宽
普通情形下,一个空格占3个像素.
具体代码以下:
Test.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
private JFrame frame;
private String scrolledText;
private String str = "转动文字 Demo";
/** *//**
* Launch the application
* @param args
*/
public static void main(String args[]) {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/** *//**
* Create the application
*/
public Test() {
initialize();
}
/** *//**
* Initialize the contents of the frame
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 500, 375);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout());
frame.getContentPane().add(panel, BorderLayout.NORTH);
final JLabel label = new JLabel();
label.setText("New JLabel");
panel.add(label);
label_scrolledText(label);
// 当窗体改变时要重新对label的转动文字举行设置
frame.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent arg0) {
label_scrolledText(label);
}
});
}
/** *//**
* 转动文字
* @param label
*/
public void label_scrolledText(JLabel label) {
this.scrolledText = this.str;
label.setText(scrolledText);
FontMetrics metrics = label.getFontMetrics(label.getFont());
int textW = metrics.stringWidth(label.getText());
Dimension frameSize = frame.getSize();
for (int i = 1; i <= (frameSize.width - textW) / 3 - 3; i++)
scrolledText += " ";
label.setText(scrolledText);
Thread thread = new Thread(new TextChanger(label));
thread.start();
}
}
TextChanger.java
import javax.swing.JLabel;
public class TextChanger implements Runnable {
private JLabel label;
public TextChanger(JLabel label) {
this.label = label;
}
public void run() {
try {
while (true) {
String text = label.getText();
if (text.length() > 1) {
text = text.substring(1, text.length()) + text.charAt(0);
label.setText(text);
label.repaint();
}
Thread.sleep(50);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
终究的效果如图所示:
以上是“<b>JLabel告示栏文字转动效果</b>[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |