📜  Java Swing-JLabel

📅  最后修改于: 2020-09-29 09:59:09             🧑  作者: Mango

Java JLabel

JLabel类的对象是用于将文本放置在容器中的组件。它用于显示一行只读文本。文本可以由应用程序更改,但用户无法直接编辑。它继承了JComponent类。

JLabel类声明

我们来看一下javax.swing.JLabel类的声明。

public class JLabel extends JComponent implements SwingConstants, Accessible

常用的构造函数:

Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment.

常用方法:

Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label’s contents along the X axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label’s contents along the X axis.

Java JLabel示例

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
    {
    JFrame f= new JFrame("Label Example");
    JLabel l1,l2;
    l1=new JLabel("First Label.");
    l1.setBounds(50,50, 100,30);
    l2=new JLabel("Second Label.");
    l2.setBounds(50,100, 100,30);
    f.add(l1); f.add(l2);
    f.setSize(300,300);
    f.setLayout(null);
    f.setVisible(true);
    }
    }

输出:

带有ActionListener的Java JLabel示例

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample(){
tf=new JTextField();
tf.setBounds(50,50, 150,20);
l=new JLabel();
l.setBounds(50,100, 250,20);
b=new JButton("Find IP");
b.setBounds(50,150,95,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
} }

输出: