如何创建用于 Java 中组件的带标题边框?


若要创建用于 Java 中组件的带标题边框,请使用 createTitledBorder() 方法。假设我们有一个面板,我们需要为其设置一个带标题的边框。这是我们的面板 −

JPanel panel = new JPanel();

现在,设置边框并为标题边框设置文本 −

panel.setBorder(BorderFactory.createTitledBorder(
   BorderFactory.createEtchedBorder(), "My Demo Table", TitledBorder.LEFT, TitledBorder.TOP));

以下是创建带标题边框的示例 −

示例

package my;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
         BorderFactory.createEtchedBorder(), "My Demo Table", TitledBorder.LEFT, TitledBorder.TOP));
      String[][] rec = {
         { "001", "David", "AUS" },
         { "002", "Steve", "AUS" },
         { "003", "Yuvraj", "IND" },
         { "004", "Kane", "NZ" },
         { "005", "Ben", "ENG" },
         { "006", "Eion", "ENG" },
         { "007", "Miller", "SA" },
         { "008", "Rohit", "IND" }
      };
      String[] header = { "Id", "Player", "Team" };
      JTable table = new JTable(rec, header);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}

输出

更新于:30-Jul-2019

2K+ 浏览量

开启你的 职业生涯

完成本课程,获得认证

开始学习
广告