Swing如何向JLabel新增邊框?

2019-10-16 22:04:56

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

使用以下API -

  • BorderFactory.createLineBorder() - 建立線條邊框。
  • JLabel.setBorder(border) - 為JLabel設定所需的邊框。

範例

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;

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

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing AddBorder2JLabel(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){
      //Create a border
      Border blackline = BorderFactory.createLineBorder(Color.red);
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       
      JPanel panel1 = new JPanel();
      String spaces = "                   ";
      JLabel label = new JLabel(spaces + "新增JLabel邊框" + spaces);
      label.setBorder(blackline);
      panel1.add(label);  
      panel1.add( new JLabel(spaces + "JLabel無邊框" + spaces));  
      panel.add(panel1);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}

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