Swing中使用邊框?

2019-10-16 22:04:53

下面的範例展示了如何在Java Swing應用程式中使用邊框。

使用以下API -

  • BorderFactory.createLineBorder() - 建立線條邊框。
  • BorderFactory.createEtchedBorder() - 建立蝕刻邊框。
  • BorderFactory.createEmptyBorder() - 建立空邊框。
  • JPanel.setBorder(border) - 為JPanel設定所需的邊框。

範例

package com.yiibai.swingdemo;


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;
import javax.swing.border.EtchedBorder;

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

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing使用邊框範例(tw511.com)");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

   private static void createUI(JFrame frame){
      Border blackline = BorderFactory.createLineBorder(Color.red);
      Border raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
      Border loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
      Border raisedbevel  = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
      Border loweredbevel = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
      Border empty = BorderFactory.createEmptyBorder();

      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      JPanel panel1 = new JPanel();
      panel1.add(new JLabel("紅色邊框"));
      panel1.setBorder(blackline);

      JPanel panel2 = new JPanel();
      panel2.add(new JLabel("邊框凸起"));
      panel2.setBorder(raisedetched);

      JPanel panel3 = new JPanel();
      panel3.add(new JLabel("邊框凹下"));
      panel3.setBorder(loweredetched);

      JPanel panel4 = new JPanel();
      panel4.add(new JLabel("凸起的斜面邊框"));
      panel4.setBorder(raisedbevel);

      JPanel panel5 = new JPanel();
      panel5.add(new JLabel("降低斜面邊框"));
      panel5.setBorder(loweredbevel);

      JPanel panel6 = new JPanel();
      panel6.add(new JLabel("空邊框"));
      panel6.setBorder(empty);

      panel.add(panel1);
      panel.add(panel2);
      panel.add(panel3);
      panel.add(panel4);
      panel.add(panel5);
      panel.add(panel6);

      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}

執行上面範例程式碼,得到以下結果:

Swing邊框