你
import java.awt.*
import java.util.Date
import javax.swing.*
import sun.security.krb5.internal.rcache.ReplayCache
public class CanvasPanel extends JPanel implements Runnable {
private Image back
private Image cloud
int time
private Thread thread
private boolean play = true
int width = 458
int height = 357
int x = width
public CanvasPanel() {
super()
back = new ImageIcon(getClass().getResource("back.jpg")).getImage()
cloud = new ImageIcon(getClass().getResource("cloud.png")).getImage()
time = 100
play = true
if (thread == null || !thread.isAlive())
thread = new Thread(this)
thread.start()
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g)
g.drawImage(back, 0, 0, width, height, this)
g.drawImage(cloud, x, 10, this)
x -= 2
if (x <= -cloud.getWidth(this))
x = width
}
public void run() {
while (play) {
try {
Thread.sleep(time)
} catch (Exception e) {
e.printStackTrace()
}
repaint()
}
}
}
import java.awt.BorderLayout
import javax.swing.JFrame
import javax.swing.JPanel
public class ImageRun extends JFrame {
private JPanel panel
public static void main(String args[]) {
try {
ImageRun frame = new ImageRun()
frame.setVisible(true)
} catch (Exception e) {
e.printStackTrace()
}
}
public ImageRun() {
super()
setBounds(100, 100, 458, 357)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
getContentPane().add(getPanel(), BorderLayout.CENTER)
//
}
protected JPanel getPanel() {
if (panel == null) {
panel = new CanvasPanel()
}
return panel
}
}
back.jpg和cloud.jpg是两张图片
import java.awt.Graphicsimport java.awt.Image
import javax.swing.ImageIcon
import javax.swing.JPanel
public class PictureJPanel extends JPanel{
private ImageIcon icon
private Image image
public PictureJPanel() {
icon = new ImageIcon(getClass().getResource("/background.jpg"))
image = icon.getImage()
}
public void paintComponent(Graphics g) {
super.paintComponent(g)
//下面这行是为了背景图片可以跟随窗口自行调整大小,可以自己设置成固定大小
g.drawImage(image, 0, 0,this.getWidth(), this.getHeight(), this)
}
}
你可以自己新建一个绘制的面板.
你可以用Jlabel或者或者AbstractButton的子类来达到这个目的.下面给你一点用Jlabel的代码 JLabel label = new JLabel()label.setIcon(new ImageIcon("图片路径"))这样就可以了,AbstractButton的方法也是一样的,,都是setIcon如果要把图片放在中间,那么用下面的代码: label.setHorizontalAlignment(SwingUtilities.CENTER)
label.setVerticalAlignment(SwingUtilities.CENTER)这样,图片就在中间了.上面的代码,第一行是设置label的水平对齐为剧中,第二行是设置垂直对齐为剧中. 还有一种方法是就是继承JComponent类重写paint方法,自己绘制图片,但是这种方法对你的需求来说,是完全没必要的. 关于图片相关的信息,你可以用 Toolkit.getDefaultToolkit().getImage("图片路径")来创建一张只读图片,要注意的是,这种方式获得的图片是不可修改的,如果要获得可以修改的图片,你可以用ImageIO类来创建BufferedImage. 希望这些信息可以帮到你.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)