Swingexamples-create-button-with-icon-text

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

Swingの例-アイコンとテキストでボタンを使用する

次の例は、Java Swingアプリケーションでアイコンとテキストを使用してボタンを作成する方法を示しています。

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

  • JButton -標準ボタンを作成します。
  • ImageIcon -画像アイコンを作成します。
  • * JButton(ImageIcon)*-アイコン付きのボタンを作成します。
  • * JButton.setText()*-ボタンにテキストを設定します。

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

import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
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);
      ImageIcon arrowIcon = null;

      java.net.URL imgURL = SwingTester.class.getResource("arrow.jpg");
      if (imgURL != null) {
         arrowIcon = new ImageIcon(imgURL);
      } else {
         JOptionPane.showMessageDialog(frame, "Icon image not found.");
      }
      JButton iconButton = new JButton(arrowIcon);
      iconButton.setText("Next");
      iconButton.setToolTipText("Move Ahead");
      iconButton.setVerticalTextPosition(AbstractButton.CENTER);
      iconButton.setHorizontalTextPosition(AbstractButton.LEADING);
      iconButton.setMnemonic(KeyEvent.VK_I);
      iconButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(frame, "Icon Button clicked.");
         }
      });

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

出力

アイコンとテキストでボタンを作成するリンク:/cgi-bin/printpage.cgi [__印刷]