Swing関係の自分用のメモ、ネタ帳です。また、以前ここで頂いたコメントは、Comments/Swingに移動しました。

調整中のネタ帳

JComponent

  • JColorChooser pallet save load XMLEncoder
  • JComboBox tooltips right side
  • JEditorPane HTML Image Lazy loading
  • JList ListCellRenderer html performance
  • JMenuBar Slide in/out animation
  • JMenuItem JPopupMenu JButton Drag
  • JOptionPane KeyEventDispatcher
  • JOptionPane scroll
  • JPasswordField Focus Blur effect transparent
  • JPasswordField Formatter and password last char
  • JProgressBar Bootstrap center string
  • JPopupMenu scroll JScrollPane
  • JRadioButton + JTextField
  • JScrollBar BlockIncrement
  • JScrollPane VetoableChangeListener
  • JSlider Sound MIDI seekbar
  • JSlider status Range restriction
  • JSpinner multiple line
  • JSplitPane show hide tab
  • JTabbedPane ScrollButton Layout
  • JTabbedPane Tearaway tabs
  • JTabbedPane content Rounded corners like nimbus
  • JTabbedPane tab height animation
  • JTable VerticalTableHeader
  • JTable cell Editable and auto completion JComboBox suggest in TableCell
  • JTable git graph JLayer
  • JTable multiple rows editor
  • JTextArea two-column format
  • JTextField Focus Animation
  • JTextField(search) in JButton(Tab, ButtonBar)
  • JTextPane Parallax
  • JToolBar target JLayer
  • JToolBar transparent top
  • JToolTip speech Balloon tooltip left center right
  • JToolTip JWindow Focus Drag
  • JTree JList(1.8.0) Nimbus Selection Rectangle
  • JTree Table
  • JTree under Node only sort
  • JTree AbstractLayoutCache.NodeDimensions FixedHeightLayoutCache

その他

  • File createTempFile
  • File getTotalSpace, getFreeSpace, getUsableSpace
  • Font CID Cmap
  • LocalDate DateFormatter sample
  • MetalTheme Arrow Color
  • UIDefaults ProxyLazyValue
  • Image BufferedImage#getScaledInstance() - 1

Java 9 AWT, Swing 新機能

DefaultLookup

Java 9

  • Swing/AuxiliaryLookAndFeel
    AuxiliaryLookAndFeel\src\java\example\AuxiliaryWindowsComboBoxUI.java:59: warning: [unchecked] unchecked 
    method invocation: constructor <init> in class BasicComboPopup is applied to given types
           super(combo);
                ^
     required: JComboBox<Object>
     found: JComboBox
    AuxiliaryLookAndFeel\src\java\example\AuxiliaryWindowsComboBoxUI.java:59: warning: [unchecked] unchecked 
    conversion
           super(combo);
                 ^
     required: JComboBox<Object>
     found:    JComboBox
  • Swing/BasicComboPopup
    BasicComboPopup\src\java\example\MainPanel.java:52: warning: [deprecation] modelToView(int) in JTextComponent has been deprecated
                       Rectangle rect = jtp.modelToView(jtp.getCaretPosition());
                                           ^
    BasicComboPopup\src\java\example\MainPanel.java:109: warning: [unchecked] unchecked method invocation: 
    constructor <init> in class BasicComboPopup is applied to given types
           super(cb);
                ^
     required: JComboBox<Object>
     found: JComboBox
    BasicComboPopup\src\java\example\MainPanel.java:109: warning: [unchecked] unchecked conversion
           super(cb);
                 ^
     required: JComboBox<Object>
     found:    JComboBox
  • Swing/ElementAttribute
    ElementAttribute\src\java\example\MainPanel.java:137: warning: [deprecation] 
    viewToModel(JTextComponent,Point,Bias[]) in TextUI has been deprecated
               int pos = editor.getUI().viewToModel(editor, e.getPoint(), bias);
                                       ^
  • Swing/GetLineText
    C:\Users\terai\jst\GetLineText\src\java\example\MainPanel.java:170: warning: [deprecation] viewToModel(Point) 
    in JTextComponent has been deprecated
           int pos = textArea.viewToModel(new Point(0, y));
                             ^
  • Swing/InputVerifierFocusOrder
    InputVerifierFocusOrder\src\java\example\MainPanel.java:73: warning: [deprecation] 
    shouldYieldFocus(JComponent) in InputVerifier has been deprecated
               @Override public boolean shouldYieldFocus(JComponent input) {
                                        ^
    InputVerifierFocusOrder\src\java\example\MainPanel.java:76: warning: [deprecation] 
    shouldYieldFocus(JComponent) in InputVerifier has been deprecated
                   return super.shouldYieldFocus(input);
                               ^
  • Swing/InternalFrameDropTarget
    InternalFrameDropTarget\src\java\example\MainPanel.java:11: error: package javax.activation is not visible
    import javax.activation.*;
               ^
     (package javax.activation is declared in module java.activation, which is not in the module graph)
  • Swing/MenuItemAcceleratorAlignment
    MenuItemAcceleratorAlignment\src\java\example\MainPanel.java:285: warning: [deprecation] 
    getKeyModifiersText(int) in KeyEvent has been deprecated
                   accText.append(KeyEvent.getKeyModifiersText(modifiers)).append(acceleratorDelimiter);
  • Swing/PasswordView
    PasswordView\src\java\example\MainPanel.java:75: warning: [deprecation] 
    drawEchoCharacter(Graphics,int,int,char) in PasswordView has been deprecated
           @Override protected int drawEchoCharacter(Graphics g, int x, int y, char c) {
                                   ^

投稿日メモ

  • 投稿時間が不明な記事一覧
    • buckupやアクセスログから調査可能な記事は、スクリプトや手動で復元したが、以下はwikihomeから移転した日時しか残っていない
Swing/DeviceName5377696E672F4465766963654E616D652003-09-08
Swing/GridBagLayout5377696E672F477269644261674C61796F75742003-09-15
Swing/MinimumFrame5377696E672F4D696E696D756D4672616D652003-09-22
Swing/Preferences5377696E672F507265666572656E6365732003-09-29
Swing/ResourceMenuBar5377696E672F5265736F757263654D656E754261722003-10-06
Swing/SystemColor5377696E672F53797374656D436F6C6F722003-10-20
Swing/FontChange5377696E672F466F6E744368616E67652003-10-27
Swing/FileHistory5377696E672F46696C65486973746F72792003-11-10
Swing/FileFilter5377696E672F46696C6546696C7465722003-11-17
Swing/LookAndFeel5377696E672F4C6F6F6B416E644665656C2003-11-24
Swing/ScrollIncrement5377696E672F5363726F6C6C496E6372656D656E742003-12-01
Swing/RecursiveFileSearch5377696E672F52656375727369766546696C655365617263682003-12-15
Swing/TabbedPane5377696E672F54616262656450616E652003-12-22
Swing/SortableTable5377696E672F536F727461626C655461626C652004-01-05
Swing/StyleConstants5377696E672F5374796C65436F6E7374616E74732004-01-12
Swing/StripeTable5377696E672F5374726970655461626C652004-01-19
Swing/EventListener5377696E672F4576656E744C697374656E65722004-01-26
Swing/FixedWidthColumn5377696E672F46697865645769647468436F6C756D6E2004-02-02
Swing/ColorTab5377696E672F436F6C6F725461622004-02-09
Swing/DnDList5377696E672F446E444C6973742004-02-16
Swing/MoveRow5377696E672F4D6F7665526F772004-02-23

Swing関係のバグのメモ

テスト中のコードなど

TreeNodeを再帰的に検索してStreamを生成

import java.awt.*;
import java.awt.event.*;
import java.util.Collections;
import java.util.Enumeration;
import java.util.stream.Stream;
import javax.swing.*;
import javax.swing.tree.*;

public class TreeNodeStreamTest {
  public JComponent makeUI() {
    JTree tree = new JTree();
    TreeNode root = (TreeNode) tree.getModel().getRoot();

    System.out.println("-- flatMap concat --");
    stream1(root).forEach(System.out::println);

    System.out.println("-- concat flatMap --");
    stream2(root).forEach(System.out::println);

    System.out.println("-- map reduce --");
    stream3(root).forEach(System.out::println);

    System.out.println("-- preorderEnumeration --");
    Enumeration<?> e = ((DefaultMutableTreeNode) root).preorderEnumeration();
    Collections.list(e).stream()
      .filter(TreeNode.class::isInstance).map(TreeNode.class::cast)
      .forEach(System.out::println);

    JPanel p = new JPanel(new BorderLayout());
    p.add(new JScrollPane(tree));
    return p;
  }

  public static Stream<TreeNode> children(TreeNode node) {
    return Collections.list((Enumeration<?>) node.children()).stream()
      .filter(TreeNode.class::isInstance).map(TreeNode.class::cast);
  }

  public static Stream<TreeNode> stream1(TreeNode p) {
    return children(p).flatMap(c -> Stream.concat(Stream.of(c), stream1(c)));
  }

  public static Stream<TreeNode> stream2(TreeNode p) {
    return Stream.concat(Stream.of(p), children(p).flatMap(TreeNodeStreamTest::stream2));
  }

  public static Stream<TreeNode> stream3(TreeNode p) {
    return children(p).map(TreeNodeStreamTest::stream3).reduce(Stream.of(p), Stream::concat);
  }

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

Swingのサンプルに関するメモ(引用)

目標にしようと思っているけど、なかなか難しそう…。

シンプルで、小さなサンプル(Simple Client Applications)

「チュートリアル」「小さなサンプル」「レビュー」

  • 社内ライブラリのチュートリアル
    社内にはそのライブラリで作られたアプリケーションが色々あり, ライブラリを使う時はその中から欲しいコード片を掘り起こすのが常だった.苦労の多い作業だった. オブジェクトの初期化, 設定, 利用のシーケンスはコード内に分散しており, それを漏れなく抜き出すのは難しい. コードの質も玉石混合で, バグを持ったままコピペされることもあった. 私達の目的は, 極端に言えば便利で正しいコピペ素材を提供することだった.

Examples should be exemplary (例は典型的であるべき)

  • Interested in Writing New Tutorial Demos for Sun?についてたコメントを引用
    • 開発者はサンプルコードに頼って(コピペして)いる
    • Examples should be exemplary
      He references a research study that found that a bug in one of the original JDK applet examples was replicated in 75% of applets attempting similar goal in their sampling of applets found on the internet. This underscores the fact that developers rely on example code, even, unfortunately, to the point that we copy bugs too. This is sometimes described as "Monkey see, monkey do", or "Rape and Paste".

コピー指向プログラミング

  • http://ameblo.jp/argv/entry-10144604985.html
    • あらかじめ完成度の高い「コピー元」を用意する
    • コピー元を品質の高いコードに集中させることで、「バグのコピー」や「似て非なるバージョンの散在」を防ぐ。
    • 「コピーされたもの」が分かるようにする
      • 例えば、コピー元のコードに特殊なコメントを埋め込む(もちろん、コピー先でも消さないでおく)などして、後からコピー先を検索しやすくする。これは、不具合修正や仕様変更などの際に、影響範囲(全てのコピー先)を特定しやすくするためである。

Best Practice for Swing coding

  • Alexander Potochkin's Blog: Why I don't use Swing hacks (in production code)についてたコメントを引用
    • For deities sake, coordinate your documentation and example in one single place. And make sure they demonstrate best practice.
    • 米Microsoft、コードサンプル集「All-In-One Code Framework」 - SourceForge.JP Magazine
      http://weblogs.java.net/blog/alexfromsun/archive/2007/09/why_i_dont_like.html:title=Best Practice for Swing coding>
      The problem with the "Swing Hacks" book is that it contains solutions in search for problems. And that is just the wrong motivation to add a hack to production code. 
      
      There are other, good motivations to add hacks to production code. Let's start with a better definition of the word hack: 
      A creative circumvention of a limitation 
      And unfortunately Swing has many limitations which hurt in the real world. If your customer insists that you make something happen "or else ..." you have a very good motivation for a hack. I do not agree that a programmer has to understand all implications of a hack. Swing is such a complex system, itself full of ugly hacks, bugs, and badly documented, that this is just not feasible. 
      
      When it comes to Swing then part of the problem is not only that Swing is so limited, but also that the limitations don't get fixed. This is an attitude problem at Sun. Sun lacks the understanding and imagination of what is needed on the desktop. Many Sun people still seem to live in SunView (ups, I am showing my age here) lala-land. Sun thinks it's always right. 
      
      Sun has totally failed to establish a best-practice for Swing coding. The examples that ship with the JDK are some of the worst Swing code. What is even worse, while Sun employees were busy writing shiny conference demos, no one at Sun could be arsed to clean up the JDK example mess during the last ten years. This is not an isolated case. The Swing tutorial examples are equally bad. They can't even be bothered to use JavaDoc for documentation and typically demonstrate badly structured code for badly structured GUIs. 
      
      Sun also has fragmented and hidden GUI information in unbelievable ways. For example, try to find a single page listing all Swing system properties. Good luck. In general, some Swing information comes with the JDK. Some can be found in the TSC (which is on life support). Others on ominous pages like JDCTechTips, Almanac (blech!), Code samples, Online Training article, Java.net articles, multi-media samples, technical articles, 2D examples in four places (did you know Sun has a half-finished Postscript Interpreter in Java http://java.sun.com/products/java-media/2D/samples/postscript/PostscriptDemo.zip?). Then there are dev.java.net examples, JDC, SDN, whatnot. I have probably forgot another ten places where Sun hides Swing, 2D, media, GUI or desktop information. 
      
      No one at Sun seems to coordinate the stuff. Instead everyone at Sun seems to run the his own show, trying to establish an own kingdom. For deities sake, coordinate your documentation and example in one single place. And make sure they demonstrate best practice. 
      
      Posted by: ewin on September 28, 2007 at 02:58 PM
      

Swing 修正予定・検討メモ

実際にやるかどうかは未定ですが、今後Swing Tipsを改良したいと思っていることをメモしています(順不同)。

  • Swing Tipsのみ分離して、Markdown、静的サイト生成に移行できないか検討中
    • https://ateraimemo.com/index.html で、Jekyll BootstrapDISQUSのテスト中
    • Jekyll、タグ付け
    • inline<code>タグ
      • JDK 1.6.0_10などのアンダーライン
      • new JPanel()などの翻訳拒否 <code>で翻訳されないはず
  • https://sites.google.com/site/javaswingtips/ は、500ページ近く手動でアップロードすることになりそうなので無理かも
  • ソースコード
    • Wiki中のサンプルコードでクラスなどをjavadocに自動リンク
    • 日本語、文字コード
  • gistプラグインでの行番号がズレてしまう 修正済み
  • 簡単にコンパイル、実行
    • Ant(build.xml)、バッチファイル、シェルスクリプトの改良
      • build.xml の整理
    • NetBeans (Eclipse) .classpath、.projectの追加
    • src.zipのファイル名を、それぞれ適当なものに変更?
  • 各Tipsの難易度表示
    • こちらで適当に評価するか、ユーザに評価してもらうか…
    • レーティングバー
  • Web Start
    • 「プログラムの追加と削除」に登録されない方法を探す
      • キャッシュを無効にする
    • UI操作無しで全部削除できる方法を探す
      • javaws -uninstall
    • 起動時にスプラッシュスクリーンを表示しない方法を探す
      • javaws -Xnosplash <jnlp>

変更済み

  • スパム対策
    • 英数のみのコメント禁止 別の対策を導入 再度英数のみのコメント禁止
  • ソースコード、FindBugs, PMD
  • ソースコード、Ubuntuなどでも実行できるように
    • e.isPopupTrigger()を使ってJPopupMenuを表示している箇所(JDK 5 以前のソース)を、すべてsetComponentPopupMenuに変更する。
  • ソースコード、1.5以上対応に変更
  • Color クラスにおける定数の大文字化
  • ソースコード、codeプラグインで色分け
  • ソースコード、build.xmlなどをすべてUTF-8化
  • バッチファイルの代わりにantのタスクを使うように変更
    • antのbuild.xmlにrunタスクを追加、ただしバッチファイルも残すことに
  • sampleをexampleに統一
  • Swing/JarFileAntの下に移動する
  • 分類: JTree JButton
  • TableSorter.javaをJDK6のTableRwoSorterに置き換える
    • ソートする意味のないサンプルで使用しているTableSorter.javaは削除
  • スクリーンショット
    • すべて撮り直す(prefixのコロン:)
    • screenshot一覧ページの分割、画像サイズ削減
    • キャッシュ一覧で探しやすいように、タイトルの頭に「サ:」(サンプル)を付けていたのを、「JST 」(Java Swing Tips)に変更
    • 日本標準時ではない…
  • 分類
    • JTableのTipsを分割
    • ソースを一つにまとめる(ワンクリックで全ソースコードを表示したい)ためにTestModel.javaを検索してpackageプライベートなクラスに変更中
      >find . -type f -name TestModel.java -ls | gawk "{print $7, $11}" | sort
    • Look&Feel関係でpublic クラスでないとダメなのは…、放置。

Bugリンクメモ