Swing大杂烩

Swing是古老的Java图形工具库。主要用于桌面应用开发。典型的例子是IntelliJ IDEA

Swing布局之BoxLayout

FooApp.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package bj.demo;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.FontUIResource;
import java.awt.*;

/**
* Created by BaiJiFeiLong@gmail.com at 2018/5/2 15:36
*/
public class FooApp {
public static void main(String[] args) throws Exception {
setUIFont(new FontUIResource("consolas", Font.PLAIN, 14));
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new JFrame() {{
setTitle("app");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 300);
setContentPane(new Box(BoxLayout.Y_AXIS) {{
setBorder(new EmptyBorder(10, 10, 10, 10));
add(new Box(BoxLayout.X_AXIS) {{
add(new JList<String>() {{
setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
setListData(new String[]{"hello", "world"});
}});
add(new JLabel("...") {{
setMaximumSize(new Dimension(Integer.MAX_VALUE / 2, Integer.MAX_VALUE));
}});
setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
}});
add(new Box(BoxLayout.X_AXIS) {{
add(new JButton("x"));
add(new JButton("x"));
add(new JSlider());
}});
}});
setVisible(true);
}};
}

private static void setUIFont(javax.swing.plaf.FontUIResource f) {
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof javax.swing.plaf.FontUIResource)
UIManager.put(key, f);
}
}
}

Linux下Swing中文乱码

在当前JRE(非JDK)目录下创建文件夹fonts/fallback,比如/usr/lib/jvm/java-8-openjdk/jre/lib/fonts/fallback,扔一个ttc格式的中文字体