[英]How to add image and text in motion in java jFrame?
I have similar a marquee to the tags html5, text moving horizontally from right to left, works perfectly without errors. 我有一个类似于html5标签的选框,文本从右向左水平移动,可以完美工作而不会出错。
public class texscroll extends JPanel {
private int x = 510, y = 25;
private String string = "Text in moving similary to the tags HTML5 Marquesina (<marquee>).";
public texscroll() {
Font font = new Font("Arial", Font.BOLD + Font.PLAIN, 15);
setFont(font);
setForeground(Color.BLACK);
setOpaque(false);
Timer timer = new Timer(14, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
x -= 1;
if (x == -10 * string.length()) {
x = 510;
}
repaint();
}
});
timer.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(720, 480);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
Graphics2D g2 = (Graphics2D) g;
g2.drawString(string, x, y);
}
}
But now I would like to be able to add or combine text and images in movement. 但是现在,我希望能够添加或组合运动中的文本和图像。
private String string = "Text in moving similary to the tags HTML5 Marquesina (<marquee>).";
How can I call the images (img/img.png)
so they can be visualized in motion? 如何称呼图像(img/img.png)
以便在运动中对其进行可视化显示?
Simply draw the image as you draw text : 在绘制文本时只需绘制图像即可:
class Texscroll extends JPanel {
private int x = 510, y = 25;
private final String string = "Text in moving similary to the tags HTML5 Marquesina (<marquee>).";
private final Image image;
public Texscroll() {
Font font = new Font("Arial", Font.BOLD + Font.PLAIN, 15);
setFont(font);
setForeground(Color.BLACK);
image = getImage();
Timer timer = new Timer(14, arg0 -> {
x -= 1;
if (x == -10 * string.length()) {
x = 510;
}
repaint();
});
timer.start();
setPreferredSize(new Dimension(720, 480));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawString(string, x, y);
g2.drawImage(image, x, y + 100, getFocusCycleRootAncestor());
}
//use any image
private BufferedImage getImage() {
int iconWidth =100;
BufferedImage img = new BufferedImage(iconWidth , iconWidth,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setColor(Color.RED);
g2.fillOval(1, 1, iconWidth - 2, iconWidth - 2);
g2.dispose();
return img;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.