jlabel graphics
时间: 2023-08-25 14:07:42 浏览: 72
JLabel is a class in Java Swing that can be used to display text or images. To display graphics on a JLabel, you can create a subclass of JLabel and override its paintComponent() method.
Here is an example:
```
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyLabel extends JLabel {
private Image image;
public MyLabel() {
super();
ImageIcon icon = new ImageIcon("image.jpg");
image = icon.getImage();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
MyLabel label = new MyLabel();
panel.add(label);
frame.add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
```
In this example, we create a subclass of JLabel called MyLabel. In the constructor, we load an image using an ImageIcon and store it in an instance variable called image. In the paintComponent() method, we call the superclass's paintComponent() method and then draw the image using the Graphics object passed as a parameter. Finally, we create a JFrame and add a JPanel containing our custom JLabel to it. When we run the program, the image is displayed on the label.
阅读全文