如何在 Java 中为单个组件创建两个边框?


要为一个组件创建两个边框,请使用 Java 中的 createCompoundBorder() 方法。在此,我们创建了 LineBorder 和 TitledBorder −

LineBorder lineBorder = new LineBorder(Color.red);
TitledBorder titleBorder = new TitledBorder("Demo Title");
Border border = BorderFactory.createCompoundBorder(lineBorder, titleBorder);

现在,为单个组件设置这两个边框 −

JButton button = new JButton("two borders");
button.setBorder(border);

以下是一个为单个组件创建两个边框的示例 −

示例

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.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Border raisedBorder = new EtchedBorder(EtchedBorder.RAISED);
      LineBorder lineBorder = new LineBorder(Color.red);
      TitledBorder titleBorder = new TitledBorder("Demo Title");
      Border border = BorderFactory.createCompoundBorder(lineBorder, titleBorder);
      JButton raisedButton = new JButton("Raised Border");
      raisedButton.setBorder(raisedBorder);
      JButton button = new JButton("two borders");
      button.setBorder(border);
      Container contentPane = frame.getContentPane(); contentPane.add(raisedButton,BorderLayout.WEST);
      contentPane.add(button,BorderLayout.EAST);
      frame.setSize(600, 300);
      frame.setVisible(true);
   }
}

输出

更新于:2019-07-30

265 次查看

开启你的 事业

通过完成课程获得认证

开始
广告