【Java】【Swing】 タブ ~ JTabbedPane ~

サンプル

SampleTab.java

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

public class SampleTab extends JFrame implements ActionListener {
  /** serialVersionUID. */
  private static final long serialVersionUID = 1L;

  private JTabbedPane tabbedPane;
  private JTextField indexText;

  public static void main(String[] args) {
    SampleTab tab = new SampleTab();
    tab.setVisible(true);
  }

  public SampleTab() {
    this.tabbedPane = new JTabbedPane(JTabbedPane.RIGHT);

    // Tab 1
    int width = 300;
    JPanel firstTabPanel = new JPanel();
    FlowLayout firstTabFlowLayout = new FlowLayout(FlowLayout.LEFT);
    firstTabFlowLayout.setVgap(3);
    firstTabFlowLayout.setHgap(5);
    firstTabPanel.setLayout(firstTabFlowLayout);
    firstTabPanel.add(new JLabel("ID :  "));
    firstTabPanel.add(new TextField(25));
    firstTabPanel.add(this.createSeparator(width, 0));
    firstTabPanel.add(new JLabel("Name : "));
    firstTabPanel.add(new TextField(25));
    firstTabPanel.add(this.createSeparator(width, 0));
    firstTabPanel.add(new JLabel("Email :"));
    firstTabPanel.add(new TextField(25));
    firstTabPanel.add(this.createSeparator(width, 0));
    firstTabPanel.add(new JLabel("Tel : "));
    firstTabPanel.add(new TextField(10));
    firstTabPanel.add(this.createSeparator(width, 0));
 
    // ボタンをセンタリング表示のためにパネルを追加
    JPanel firstTabEndPanel = new JPanel();
    firstTabEndPanel.setLayout(new FlowLayout());
    firstTabEndPanel.setPreferredSize(new Dimension(width - 18, 50));
    firstTabEndPanel.add(new JButton("Register"));
    firstTabPanel.add(firstTabEndPanel);
    
    // Tab 2
    JPanel secondTabPanel = new JPanel();
    secondTabPanel.add(new JLabel("Name:"));
    secondTabPanel.add(new JTextField("", 10));

    this.tabbedPane.addTab("Tab 1", firstTabPanel);
    this.tabbedPane.addTab("Tab 2", secondTabPanel);
    this.tabbedPane.setToolTipTextAt(0, "ToolTip 1");
    this.tabbedPane.setToolTipTextAt(1, "ToolTip 2");
    
    this.getContentPane().add(this.tabbedPane, BorderLayout.CENTER);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setBounds(500, 200, 350, 200);
    this.setTitle("This is a Title");
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    int index = Integer.parseInt(indexText.getText());
    tabbedPane.setSelectedIndex(index);
  }
  
  private JSeparator createSeparator(int width, int hight) {
    JSeparator separator = new JSeparator(JSeparator.HORIZONTAL);
    separator.setPreferredSize(new Dimension(width, hight));
    return separator;
  }
}