Swingexamples-using-comboboxes

提供:Dev Guides
移動先:案内検索

Swingの例-コンボボックスの使用

次の例は、Java Swingアプリケーションで標準のコンボボックスを使用する方法を示しています。

次のAPIを使用しています。

  • JComboBox -標準のコンボボックスを作成します。
  • JCheckBox.setSelectedIndex(index); -アイテムを選択します。
  • JCheckBox.getSelectedItem(); -選択したアイテムを取得します。

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

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(final JFrame frame){
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();
      panel.setLayout(layout);

      String[] numbers = {"One", "Two", "Three", "Four", "Five"};
      JComboBox<String> comboBox = new JComboBox<>(numbers);
      comboBox.setSelectedIndex(3);
      comboBox.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JComboBox combo = (JComboBox)e.getSource();
            JOptionPane.showMessageDialog(frame,combo.getSelectedItem());

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

出力

ComboBoxesの使用リンク:/cgi-bin/printpage.cgi [__印刷]