JButton常用方法
JButton组件表示一个按钮,使用JButton可以直接在窗体中增加一个按钮。JButton类的常用方法如下表所示
1 | 方法 | 描述 |
---|---|---|
1 | public JButton() throws HeadlessException | 创建一个JButton对象 |
2 | public JButton(String label) throws HeadlessException | 创建一个JButton对象,并制定其中显示的内容 |
3 | public JButton(Icon icon) | 创建一个带图片的按钮 |
4 | public JButton(Stirng text,Icon icon) | 创建一个带图片和文字的按钮 |
5 | public void setLabel(String label) | 设置JButton的显示文字 |
6 | public String getLabel() | 获取JButton中显示的文字 |
7 | public void setBounds(int x,int y,int width,int height) | 设置组件的x,y坐标,宽度,高度 |
8 | public void setMnemonic(int mnemonic) | 设置按钮的快捷键 |
实例:在窗体中建立一个普通的按钮
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Font;
public class JButtonDemo01
{
public static void main(String args[])
{
//实例化窗体对象
JFrame frame = new JFrame("测试按钮JButton");
//按钮对象
JButton but = new JButton("一个按钮");
//初始化话字体
Font fnt = new Font("黑体", Font.BOLD, 18);
//设置按钮字体
but.setFont(fnt);
frame.add(but);
//设置窗体大小
frame.setSize(400, 200);
//设置窗体坐标
frame.setLocation(300, 200);
//窗体可见
frame.setVisible(true);
}
}
运行结果:
JButton也可以为一个按钮设置一个现实的图片,与JLabel类似,直接在创建对象的时候设置即可
实例:在JButton按钮上设置显示图片
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class JButtonDemo02
{
public static void main(String args[])
{
//实例化窗体
JFrame frame = new JFrame("按钮上设置图片");
//指定图片路径
String picPath = "C:\\Users\\Administrator\\Desktop\\蓝精灵_Jc.jpg";
//实例化图片
Icon icon = new ImageIcon(picPath);
//在窗体中添加图片
JButton but = new JButton(icon);
frame.add(but);
frame.setSize(300, 300);
frame.setLocation(300, 200);
frame.setVisible(true);
}
}
运行结果:
当然也可以在按钮中同时添加图片和文字:
实例:在按钮中同时添加图片和文字
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class JButtonDemo02
{
public static void main(String args[])
{
//实例化窗体
JFrame frame = new JFrame("按钮上设置图片");
//指定图片路径
String picPath = "C:\\Users\\Administrator\\Desktop\\蓝精灵_Jc.jpg";
//实例化图片
Icon icon = new ImageIcon(picPath);
//在窗体中添加图片
JButton but = new JButton("文字",icon);
Font font=new Font("黑体",Font.ITALIC + Font.BOLD,28);
but.setFont(font);
but.setForeground(Color.BLUE);
frame.add(but);
frame.setSize(400,300);
frame.setLocation(300, 200);
frame.setVisible(true);
}
}
运行结果: