1. 程式人生 > 其它 >3 彩色標籤(練習)

3 彩色標籤(練習)

技術標籤:JavaSwing基礎swing

(練習)彩色標籤

程式碼(版本1):

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 Demo {
	
	public static void main(String[] args)
{ MyFrame frame = new MyFrame("Demo"); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } class MyFrame extends JFrame{ Container contentPane; public MyFrame(String title) { super(title); contentPane = getContentPane
(); contentPane.setLayout(new FlowLayout()); makeLabel("1", Color.RED); makeLabel("2", Color.BLUE); makeLabel("3", Color.GREEN); makeLabel("4", Color.GRAY); } public void makeLabel(String text, Color color) { JLabel label = new JLabel(text);
//設定背景為非透明 label.setOpaque(true); //設定背景尺寸 label.setPreferredSize(new Dimension(60, 30)); //設定背景顏色 label.setBackground(color); //設定文字水平 label.setHorizontalAlignment(SwingConstants.CENTER); contentPane.add(label); } }

程式碼(版本2):

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 Demo2 {

	public static void main(String[] args) {
		MyFrame2 frame = new MyFrame2("Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300, 300);
		frame.setVisible(true);
	}
}

class MyFrame2 extends JFrame{
	
	public MyFrame2(String title) {
		super(title);
		
		Container contentPane = this.getContentPane();
		contentPane.setLayout(new FlowLayout());
		contentPane.add(new ColorfulLabel("1", Color.BLUE));
		contentPane.add(new ColorfulLabel("2", Color.RED));
		contentPane.add(new ColorfulLabel("3", Color.GREEN));
		contentPane.add(new ColorfulLabel("4", Color.GRAY));
	}
	
	private class ColorfulLabel extends JLabel{
		public ColorfulLabel(String text, Color color) {
			this.setText(text);
			this.setOpaque(true);
			this.setHorizontalAlignment(SwingConstants.CENTER);
			this.setPreferredSize(new Dimension(60, 30));
			this.setBackground(color);
		}
	}
}

輸出:
在這裡插入圖片描述