如何在 Java 中添加空边框到 JButton?


要向组件添加空边框,请使用 BorderFactory 类的 createEmptyBorder() 方法 −

Border emptyBorder = BorderFactory.createEmptyBorder(10, 10, 0, 0);

要将上述边框设置为组件,请使用 setBorder() 方法 −

JButton button = new JButton("Empty Border");
button.setBorder(emptyBorder);

以下是向 JButton 添加空边框的示例 −

示例

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;
import javax.swing.border.SoftBevelBorder;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Border raisedBorder = new SoftBevelBorder(SoftBevelBorder.RAISED, Color.GREEN, Color.GREEN.darker(),
      Color.MAGENTA, Color.magenta.brighter());
      Border raisedBorder2 = new SoftBevelBorder(SoftBevelBorder.RAISED);
      Border loweredBorder = new SoftBevelBorder(SoftBevelBorder.LOWERED, Color.ORANGE, Color.YELLOW.darker(),
      Color.BLUE, Color.yellow.brighter());
      Border emptyBorder = BorderFactory.createEmptyBorder(10, 10, 0, 0);
      JButton raisedButton = new JButton("Raised Border");
      raisedButton.setBorder(raisedBorder);
      JButton loweredButton = new JButton("Lowered Border");
      loweredButton.setBorder(loweredBorder);
      JLabel raisedLabel = new JLabel("Raised Border");
      raisedLabel.setBorder(raisedBorder2);
      JButton button = new JButton("Empty Border");
      button.setBorder(emptyBorder);
      Container contentPane = frame.getContentPane();
      contentPane.add(raisedButton,BorderLayout.WEST);
      contentPane.add(loweredButton,BorderLayout.EAST);
      contentPane.add(raisedLabel,BorderLayout.CENTER);
      contentPane.add(button,BorderLayout.NORTH);
      frame.setSize(600, 300);
      frame.setVisible(true);
   }
}

输出

更新于: 2019-07-30

403 次浏览

开始你的 职业生涯

完成该课程获得认证

开始学习
广告