- 圖標、按鈕
JLabel標籤,通過Icon接口創建圖標(並給定圖標大小顏色等)
//非正確代碼233
import javax.swing.JLabel;
public class MyImage extends JFrame {
public MyImage() {
Container container = getContentPane();
JLable jl = new JLabel("JAVA STUDY",JLabel.CENTER);//創建標籤
URL url = MyImage.class.getResource("imageButton.jpg");
Icon icon = new ImageIcon(url);//實例化Icon對象
jl.setlcon(icon);//爲標籤設置圖片
jl.setHorzontalAlignment(SwingConstants.CENTER);
jl.setOpaque(true);////標籤不透明
container.add(jl);
setSize(300,300);
setVisble(true);//窗體可見
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
new MyImage();
}
}
佈局管理器
絕對佈局
絕對佈局就是硬性指定組件位置。
使用之前需要取消佈局管理器setLayout(null);//取消佈局管理區
import java.awt.Container;
import java.awt.*;
import javax.swing.*;
import javax.swing.JButton;
public class AbsolutePosition extends JFrame {
public AbsolutePosition() {
setTitle("JAVA Study");//窗體標題
setLayout(null);//取消佈局管理區
setBounds(0,0,800,850);
Container c = getContentPane();//創建容器對象
JButton b1 = new JButton("Point me1");
JButton b2 = new JButton("Point me2");
b1.setBounds(10,30,80,30);//位置and大小
b2.setBounds(60,70,100,20);
c.add(b1);
c.add(b2);
setVisible(true);//使窗體可見
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new AbsolutePosition();
}
}
運行結果,這裏的JButton按了沒laun用,233,還沒搞東西。待下面加東西。
流佈局管理器
默認劇中排列,也可設置爲向左對齊(0),向右對齊(2);
import java.awt.Container;
import java.awt.*;
import javax.swing.*;
public class FLowLayoutPosition extends JFrame {
public FLowLayoutPosition() {
setTitle("吳明窗體");
Container c = getContentPane();
setLayout(new FlowLayout(2,10,10));//組件向右對齊,設置水平垂直間隔
for(int i=0;i<10;i++)
c.add(new JButton("button"+i));
setSize(300,200);
setVisible(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);//關閉方式
}
public static void main(String[] args) {
new FLowLayoutPosition();
}
}
佈局管理器還有:
邊界佈局管理器BorderLayout,邊界佈局管理器的特點使可以把組件安排在東南西北中五個地方
網格佈局管理器GridLayout
按行按列進行排列。每個組件的大小相同。
常用面板
JPanel面板
可以聚焦一些組件來佈局。ddd
JScrollpane面板
這個面板在當我們的內容在窗體顯示不下時使用,它帶滾動條。但是隻能放一個組件。
可以把多個組件放在JPanel上面然後把JPanel看作整體放在JScrollpane上面
import java.awt.*;
import javax.swing.*;
public class JSscroo extends JFrame {
public JSscroo() {
Container c = getContentPane();
JTextArea ta = new JTextArea(20,50);
JScrollPane sp =new JScrollPane(ta);
c.add(sp);
setTitle("隨便叫個什麼");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new JSscroo();
}
}