The first thing to grasp is a concept: a string of pixels in the computer screen, for example, to take a jlabel inside the text occupied by the width and height, the method is as follows: (mainly used FontMetrics class)
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()); //字符串的宽
Typically, a space occupies 3 pixels.
The specific code is as follows:
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 = "scrolling text 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);
///When the form changes, you want to reset the label's scrolling text
Frame.addcomponentlistener (New Componentadapter () {
public void componentresized (ComponentEvent arg0) {
label_scrolledtext (label);
}
});
}
/** *//**
* Scrolling Text
* @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 ();
}
}
}
The final effect is as shown in the figure: