如何在 Java 中为 JButton 应用不同的边框?
awtjavaobject oriented programmingprogrammingswing
JButton 是 AbstractButton 类 的子类,可用于在 Java Swing 应用程序中添加独立于平台的按钮。当用户单击按钮时,JButon 可以生成 ActionListener 接口,当用户可以通过鼠标 执行某些操作时,它还可以生成 MouseListener,当用户可以通过键盘执行某些操作时,它还可以生成 KeyListener。
我们可以使用 JComponent类的 setBorder() 方法为 JButton 设置不同的边框,如 LineBorder、BevelBorder、EtchcedBorder、EmptyBorder、TitledBorder 等。
语法
public void setBorder(Border border)
示例
import javax.swing.*; import java.awt.*; public class JButtonBordersTest extends JFrame { private JButton button[]; private JPanel panel; public JButtonBordersTest() { setTitle("JButton Borders"); panel = new JPanel(); panel.setLayout(new GridLayout(7, 1)); button = new JButton[7]; for(int count = 0; count < button.length; count++) { button[count] = new JButton("Button "+(count+1)); panel.add(button[count]); } button[0].setBorder(BorderFactory.createLineBorder(Color.blue)); button[1].setBorder(BorderFactory.createBevelBorder(0)); button[2].setBorder(BorderFactory.createBevelBorder(1, Color.red, Color.blue)); button[3].setBorder(BorderFactory.createBevelBorder(1, Color.green, Color.orange, Color.red, Color.blue)); button[4].setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); button[5].setBorder(BorderFactory.createEtchedBorder(0)); button[6].setBorder(BorderFactory.createTitledBorder("Titled Border")); add(panel, BorderLayout.CENTER); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JButtonBordersTest(); } }