Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để hiển thị các mục phông chữ khác nhau bên trong JComboBox trong Java?


A JComboBox là một lớp con của JComponent lớp và nó là sự kết hợp của trường văn bản danh sách thả xuống từ đó người dùng có thể chọn một giá trị. A JComboBox có thể tạo ActionListener, ChangeListener ItemListener giao diện khi người dùng thao tác trên hộp tổ hợp. Chúng tôi có thể hiển thị các kiểu phông chữ khác nhau bên trong JComboBox bằng cách triển khai ListCellRenderer giao diện

Ví dụ

import java.awt.*;
import javax.swing.*;
public class JComboBoxFontTest extends JFrame {
   private JComboBox fontComboBox;
   private String fontName[];
   private Integer array[];
   public JComboBoxFontTest() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      fontName = ge.getAvailableFontFamilyNames();
      array = new Integer[fontName.length];
      for(int i=1;i<=fontName.length;i++) {
         array[i-1] = i;
      }
      fontComboBox = new JComboBox(array);
      ComboBoxRenderar renderar = new ComboBoxRenderar();
      fontComboBox.setRenderer(renderar);
      setLayout(new FlowLayout());
      add(fontComboBox);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   private class ComboBoxRenderar extends JLabel implements ListCellRenderer {
      @Override
      public Component getListCellRendererComponent(JList list, Object value, int index, boolean           isSelected, boolean cellHasFocus) {
         int offset = ((Integer)value).intValue() - 1;
         String name = fontName[offset];
         setText(name);
         setFont(new Font(name,Font.PLAIN,20));
         return this;
      }
   }
   public static void main(String args[]) {
      new JComboBoxFontTest();
   }
}

Đầu ra

Làm cách nào để hiển thị các mục phông chữ khác nhau bên trong JComboBox trong Java?