java-swing-layoutmanage(布局管理器)
package com.etc.layoutmanage;
import javax.swing.*;
import java.awt.*;
/**
* LayoutMange 布局管理器:容器如何排列子控件;
* <p>
* FlowLayout 流布局:默认从左到右,当一行排满时继续下一行;
*/
public class MyFrame extends JFrame {
public MyFrame(String title) {
super(title);
Container container = getContentPane();
// 创建一个流布局
LayoutManager layout = new FlowLayout(FlowLayout.LEFT);
container.setLayout(layout);
ColorfulLabel c1 = new ColorfulLabel("1", Color.gray);
ColorfulLabel c2 = new ColorfulLabel("2", Color.CYAN);
ColorfulLabel c3 = new ColorfulLabel("3", Color.green);
ColorfulLabel c4 = new ColorfulLabel("4", Color.orange);
ColorfulLabel c5 = new ColorfulLabel("5", Color.YELLOW);
container.add(c1);
container.add(c2);
container.add(c3);
container.add(c4);
container.add(c5);
}
private static class ColorfulLabel extends JLabel {
public ColorfulLabel(String text, Color bgColor) {
super(text);
setOpaque(true);
setBackground(bgColor);
setPreferredSize(new Dimension(50, 50));
setHorizontalAlignment(SwingConstants.CENTER);
}
}
}
package com.etc.layoutmanage;
import javax.swing.*;
public class SwingDemo {
private static void createGIU() {
MyFrame frame = new MyFrame("Swing Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createGIU();
}
});
}
}