JLabel(二)图片的放大缩小
这是JLabel控件的另一种写法,可以让图片作为背景,另外文本可以用简单的html语法,代码如下:import javax.swing.*;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.applet.Applet;
import java.net.URL;
class HelloWorld extends JFrame{
private JPanel jp;
private JLabel jl;
private Image img;
public static void main(String args[]){
HelloWorld jf = new HelloWorld();
jf.setVisible(true);
}
HelloWorld(){
setBounds(100,100,450,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp = new JPanel();
// Font helv14b = new Font("Helvetica", Font.BOLD, 14);
img = new ImageIcon("./logo.png").getImage();
jl = new JLabel("<html>Let coding change the world<br>FishC.com</html>"){
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(img,0,0,this.getWidth(),this.getHeight(),null);
}
};
// jl.setIcon(new ImageIcon("./logo.png"));
// jl.setFont(helv14b);
jp.add(jl);
setContentPane(jp);
}
}
效果图:
我们还可以自己控制图片大小,这次再从新写个MyJLabel.java文件,代码如下:
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
class MyJLabel extends JFrame{
private JPanel jp;
private JLabel jl;
private ImageIcon ii;
private Image img;
public static void main(String args[]){
MyJLabel jf = new MyJLabel();
jf.setVisible(true);
}
MyJLabel(){
setBounds(100,100,450,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp = new JPanel();
jl = new JLabel("<html><br>FishC.com<br>Let coding change the world</html>"){
public void paint(Graphics g){
ii = new ImageIcon("./logo.png");
img = ii.getImage();
Image smallImage = img.getScaledInstance(200,100,Image.SCALE_DEFAULT);
ImageIcon myimg = new ImageIcon(smallImage);
this.setIcon(myimg);
this.setSize(500, 200);
super.paint(g);
}
};
jp.add(jl);
setContentPane(jp);
}
}
效果图:
以上两种都采用了从写JLabel类里的方法形式,比如我们的类继承了另外一个类就可以通过从写方法的形式覆盖上一个类的方法,也可以直接在new的类后面大括号里重写,达到我们自己的目的比如以下的例子:
class Decorating{
void a(){
System.out.println("this is a function");
}
public static void main(String args[]){
Decorating dec = new Decorating(){
void a(){
System.out.println("this is covered a function");
}
};
dec.a();
}
}
输出结果为:
页:
[1]