java Swing做一个简单的彩色标签:
SwingDemo代码如下:
//
//做一个简单的彩色标签
//Created by lee_1310 on 2019.03.30 16:39
//CopyRight please @ https://blog.csdn.net/Lee_1310
//
import javax.swing.JFrame;
public class SwingDemo {
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
createGUI();
}
});
}
protected static void createGUI()
{
//创建myFrame对象
myFrame frame = new myFrame("Swing Demo!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置窗口大小
frame.setSize(600,400);
//显示窗口
frame.setVisible(true);
}
}
myFrame代码如下:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class myFrame extends JFrame{
//构造方法
public myFrame(String title)
{
super(title);
//内容面板
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(new ColorfulLabel("1",Color.YELLOW));
contentPane.add(new ColorfulLabel("2",Color.BLACK));
contentPane.add(new ColorfulLabel("3",Color.BLUE));
contentPane.add(new ColorfulLabel("4",Color.RED));
contentPane.add(new ColorfulLabel("5",Color.GRAY));
contentPane.add(new ColorfulLabel("6",Color.CYAN));
contentPane.add(new ColorfulLabel("7",Color.MAGENTA));
contentPane.add(new ColorfulLabel("8",Color.WHITE));
}
private static class ColorfulLabel extends JLabel
{
public ColorfulLabel(String text,Color bgColor)
{
//继承父类作为label显示的内容
super(text);
//设置label背景不透明,默认透明
setOpaque(true);
//背景颜色
setBackground(bgColor);
//设置最佳尺寸
setPreferredSize(new Dimension(120,60));
//设置水平对齐
setHorizontalAlignment(SwingConstants.LEFT);
}
}
}
运行结果