• 追加された行はこの色です。
  • 削除された行はこの色です。
---
keywords: [Kotlin, Swing, Java]
description: KotlinでのSwingの使用方法に関するメモなど
author: aterai
pubdate: 2017-05-31
---
#contents

* 概要 [#summary]
- このページは`Kotlin`で`Swing`を使用する場合のサンプルの一覧です。

* 実行環境 [#s42e991c]
 $ sdk install kotlin
 $ kotlinc -version
 info: Kotlin Compiler version 1.1.2-2
 $ kotlinc hello.kt -include-runtime -d hello.jar && "$JAVA_HOME/bin/java" -jar hello.jar

* Swing + Kotlin サンプル [#swing]
** JTable [#JTable]
- メモ
-- `Class<?>`は`Class<Any>`
-- `Class<?>`は`Class<Any>`か`Class<Object>`
-- `Object#getClass()`は`javaClass`
-- オーバーライドの方法、`@Override`は`override`
-- 二次元配列
-- `apply`
- `Kotlin`
#code{{
import java.awt.*
import javax.swing.*
import javax.swing.table.*

fun makeUI(): JComponent {
  val columnNames = arrayOf("String", "Integer", "Boolean")
  val data = arrayOf(
      arrayOf("aaa", 12, true),
      arrayOf("bbb", 5, false),
      arrayOf("bbb",  5, false),
      arrayOf("CCC", 92, true),
      arrayOf("DDD", 0, false))
      arrayOf("DDD",  0, false))
  val model = object : DefaultTableModel(data, columnNames) {
    override fun getColumnClass(column : Int) : Class<Any> {
      return getValueAt(0, column).javaClass
    }
  }
  val table = JTable(model).apply {
    autoCreateRowSorter = true
  }
  return JPanel(BorderLayout(5, 5)).apply {
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
    add(JScrollPane(table))
  }
}
fun main(args : Array<String>) {
  EventQueue.invokeLater {
    JFrame("kotlin swing").apply {
      defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
      add(makeUI())
      size = Dimension(320, 240)
      setLocationRelativeTo(null)
      setVisible(true)
    }
  }
}
}}

- `Java`
#code{{
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

public class JTableExample {
  public JComponent makeUI() {
    String[] columnNames = {"String", "Integer", "Boolean"};
    Object[][] data = {
      {"aaa", 12, true}, {"bbb", 5, false},
      {"CCC", 92, true}, {"DDD", 0, false}
    };
    TableModel model = new DefaultTableModel(data, columnNames) {
      @Override public Class<?> getColumnClass(int column) {
        return getValueAt(0, column).getClass();
      }
    };
    JTable table = new JTable(model);
    table.setAutoCreateRowSorter(true);

    JPanel p = new JPanel(new BorderLayout());
    p.add(new JScrollPane(table));
    return p;
  }
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new JTableExample().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}
}}

** JTree [#JTree]
- `Kotlin`
#code{{
import java.awt.*
import javax.swing.*

fun makeUI(): JComponent {
  val tree = JTree()
  val p = JPanel(GridLayout(1, 0, 5, 5)).apply {
    add(JButton("expand").apply {
      addActionListener {
        expandAll(tree)
      }
    })
    add(JButton("collapse").apply {
      addActionListener {
        collapseAll(tree)
      }
    })
  }
  return JPanel(BorderLayout(5, 5)).apply {
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
    add(JScrollPane(tree))
    add(p, BorderLayout.SOUTH)
  }
}

fun expandAll(tree : JTree) {
  var row = 0
  while (row < tree.getRowCount()) {
    tree.expandRow(row)
    row++
  }
}

fun collapseAll(tree : JTree) {
  var row = tree.getRowCount() - 1
  while (row >= 0) {
    tree.collapseRow(row)
    row--
  }
}

fun main(args : Array<String>) {
  EventQueue.invokeLater {
    JFrame("kotlin swing").apply {
      defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
      add(makeUI())
      size = Dimension(320, 240)
      setLocationRelativeTo(null)
      setVisible(true)
    }
  }
}
}}

- `Java`
#code{{
import java.awt.*;
import java.util.*;
import javax.swing.*;

public class JTreeExample {
  public JComponent makeUI() {
    JTree tree = new JTree();
    JButton button1 = new JButton("expand A");
    button1.addActionListener(e -> expandAll(tree));
    JButton button2 = new JButton("collapse A");
    button2.addActionListener(e -> collapseAll(tree));
    JPanel p = new JPanel(new GridLayout(0, 1, 2, 2));
    Arrays.asList(button1, button2).forEach(p::add);
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(new JScrollPane(tree));
    panel.add(p, BorderLayout.SOUTH);
    return panel;
  }
  protected static void expandAll(JTree tree) {
    int row = 0;
    while (row < tree.getRowCount()) {
      tree.expandRow(row);
      row++;
    }
  }
  protected static void collapseAll(JTree tree) {
    int row = tree.getRowCount() - 1;
    while (row >= 0) {
      tree.collapseRow(row);
      row--;
    }
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new JTreeExample().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}
}}

** JCheckBox [#JCheckBox]
- メモ
-- `Smart Cast`、キャスト%%で`if`のネストが深くなるのを避けたいが...%%
- `Kotlin`
#code{{
import java.awt.*
import javax.swing.*

fun makeUI(): JComponent {
  val checkbox = JCheckBox("Always On Top", true).apply {
    addActionListener {
      val w = getTopLevelAncestor()
      if (w is Window) {
          w.setAlwaysOnTop(isSelected())
      }
    }
//     addActionListener { e ->
//       val c = e.getSource()
//       if (c is AbstractButton) {
//         val w = c.getTopLevelAncestor()
//         if (w is Window) {
//           w.setAlwaysOnTop(c.isSelected())
//         }
//       }
    }
  }
  return JPanel(BorderLayout()).apply {
    add(checkbox, BorderLayout.NORTH)
  }
}

fun main(args : Array<String>) {
  EventQueue.invokeLater {
    JFrame("kotlin swing").apply {
      defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
      add(makeUI())
      size = Dimension(320, 240)
      setLocationRelativeTo(null)
      setVisible(true)
    }
  }
}
}}

- `Java`
#code{{
import java.awt.*;
import javax.swing.*;

public class JCheckBoxExample {
  public JComponent makeUI() {
    JCheckBox checkbox = new JCheckBox("Always On Top", true);
    checkbox.addActionListener(e -> {
      AbstractButton b = (AbstractButton) e.getSource();
      Container c = b.getTopLevelAncestor();
      if (c instanceof Window) {
        ((Window) c).setAlwaysOnTop(b.isSelected());
      }
    });
    JPanel p = new JPanel(new BorderLayout());
    p.add(checkbox, BorderLayout.NORTH);
    return p;
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new JCheckBoxExample().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}
}}

* コメント [#comment]
#comment
#comment