Swing 示例 - 给 JPanel 添加边框



下面的示例展示如何在 Java Swing 应用程序中给 JPanel 添加边框。

我们使用以下 API。

  • BorderFactory.createLineBorder() - 创建线条边框。

  • JPanel.setBorder(border) - 给 JPanel 设置所需的边框。

示例

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.LayoutManager;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(JFrame frame){
      //Create a border
      Border blackline = BorderFactory.createLineBorder(Color.black);
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       
      JPanel panel1 = new JPanel();
      String spaces = "                   ";
      panel1.add(new JLabel(spaces + "Border to JPanel" + spaces));  
      panel1.setBorder(blackline);
      panel.add(panel1);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}

输出

Add border to a JPanel
swingexamples_borders.htm
广告