自定义按钮形状
Java中设计GUI窗口界面时我们会设置Button来交互用户的动作,但有时会觉得默认的Button按钮有些丑,希望可以自定义按钮。
例如下面这个例子:(将按钮定义为圆角矩形)
)
而自定义Button形状就需要了解JButton类中的
paintComponent(Graphics g) 函数 //控制button的填充内容
paintBorder(Graphics g) 函数 //控制button的边框
那么具体怎么实现,直接上文档!!!
由于paintComponent函数需要一个Graphics类型的值,所以我们来查询Graphics类
在这个类下提供了很多方法,例如我们需要将Button改为圆角矩形
fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
下面是最开始例子的代码
/*NewButton类,继承JButton类重写用于绘制按钮形状的函数*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NewButton extends JButton
{
private String s;
private int sizeX;
private int sizeY;
public NewButton(String s ,int sizeX,int sizeY) //传递图片引用
{
super(s);
this.sizeX = sizeX;
this.sizeY = sizeY;
setContentAreaFilled(false);
}
protected void paintComponent(Graphics g) //绘制按钮内容
{
g.setColor(new Color(31,171,137));
g.fillRoundRect(0,0,getSize().width-1,getSize().height-1,15,15); //绘制一个圆角矩形getSize()为获取组件的大小
//g.drawImage(img, 0,0,50, 40, null); //除了形状外还可以为按钮绘制一个图片来美化按钮
super.paintComponent(g); //使用父类函数绘制一个焦点框
}
protected void paintBorder(Graphics g) //绘制按钮边框
{
g.drawRoundRect(0,0,getSize().width-1,getSize().height-1,15,15);
}
}
/*上面例子的代码*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SetWindons extends JFrame
{
private JTextField field_1, field_2;
private JTextArea area;
private NewButton button;
private JLabel label_1, label_2;
public SetWindons()
{
setLayout(new FlowLayout());
setTitle("面积计算");
setBounds(200,200,156,200);
init();
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public void init()
{
field_1 = new JTextField (10);
field_2 = new JTextField(10);
label_1 = new JLabel("长:");
label_2 = new JLabel("宽:");
area = new JTextArea(9,10);
button = new NewButton("确认",50,30);
add(label_1);
add(field_1);
add(label_2);
add(field_2);
add(button);
add(area);
//添加监视器
button.addActionListener(new ActionListener() //匿名类实现监听,计算面积
{
public void actionPerformed(ActionEvent e)
{
try // 异常处理
{
double a = Double.parseDouble(field_1.getText());
double b = Double.parseDouble(field_2.getText());
double sum = a * b;
area.append("面积为" + sum);
}
catch(Exception exp)
{
area.append("输入错误!");
}
}
}
);
}
}
除了圆角矩形外,如果想要构造特殊形状,可以使用里面提供的fillPolygon函数
其中X坐标数组和Y坐标数组一一对应,这样通过自定义的一些列点来绘制按钮,从而实现特殊形状的绘制。
其他
通过对button类的了解,编写了一个项目。编写时水平有限因此存在很多问题,若有兴趣请自行下载。
https://gitee.com/Aaranlei/keyboard-monitoring-system