JavaGUI------------常用的组件(标签、按钮)

1.标签

    类:JLabel 作用:显示文本或者提示信息

构造函数:

    new JLabel(); new JLabel(Icon icon);//设置图标 new JLabel(Icon icon,int aligment);//设置图标+水平对齐方式 new JLabel(String str,int aligment);//设置文本+水平对齐方式 new JLabel(String str,Icon icon,int aligment);//设置文本+图标+水平对齐方式

示例:

import javax.swing.*;

public class Jlabel {
    public static void main(String[] args){
        JFrame jf=new JFrame("JLabel");
        jf.setBounds(400,300,200,300);

        JLabel jl=new JLabel("账户:",SwingConstants.LEFT);
        jf.add(jl);

        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

2.按钮

类:JButton

构造方法:

    new JButton(); new JButton(String text);//指定文字 new JButton(Icon icon);//指定图标 new JButton(String str,Icon icon);//指定文字+图标

其他方法:

.setTooltipText(String text); //设置提示文字

.setBordePainted();//设置边界是否显示

.setEnabled();//设置按钮是否可用

示例1(按钮可用,有边界-默认):

import javax.swing.*;
import java.awt.*;

public class Jbutton {
    public static void main(String[] args){
        JFrame jf=new JFrame("JLabel");
        jf.setBounds(400,300,200,300);
        jf.setLayout(new FlowLayout());
        
        JButton jb=new JButton("按钮1");
        jb.setEnabled(true);
        jf.add(jb);

        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

示例2(按钮不可用):

import javax.swing.*;
import java.awt.*;

public class Jbutton {
    public static void main(String[] args){
        JFrame jf=new JFrame("JLabel");
        jf.setBounds(400,300,200,300);
        jf.setLayout(new FlowLayout());
        
        JButton jb=new JButton("按钮1");
        jb.setEnabled(false);
        jf.add(jb);

        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

示例3(无边界):

import javax.swing.*;
import java.awt.*;

public class Jbutton {
    public static void main(String[] args){
        JFrame jf=new JFrame("JLabel");
        jf.setBounds(400,300,200,300);
        jf.setLayout(new FlowLayout());

        JButton jb=new JButton("按钮1");
        jb.setEnabled(true);
        jb.setBorderPainted(false);
        jf.add(jb);

        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
经验分享 程序员 微信小程序 职场和发展