【演算法視覺化】第一章 Java GUI程式設計基礎
阿新 • • 發佈:2018-12-14
1.1 使用JFrame
import javax.swing.*; import java.awt.*; public class Main { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new JFrame("Welcome");//視窗標題 frame.setSize(500, 500);視窗寬和高 frame.setResizable(false);是否允許使用者改變視窗大小,這裡false是不允許 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 當點選視窗的關閉符號能使整個JFrame框架都正確關閉 frame.setVisible(true);// 建立視窗 }); } }
1.2 建立JFrame子類
import java.awt.*; import javax.swing.*; public class AlgoFrame extends JFrame{ private int canvasWidth;// 可繪製圖形區域的寬 private int canvasHeight;// 可繪製圖形區域的高 public AlgoFrame(String title, int canvasWidth, int canvasHeight){ super(title);// 呼叫父類構造方法,即傳入標題 this.canvasWidth = canvasWidth; this.canvasHeight = canvasHeight; setSize(canvasWidth, canvasHeight); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 當點選視窗的關閉符號能使整個JFrame框架都正確關閉 setResizable(false);// 是否允許使用者改變視窗大小,這裡false是不允許 setVisible(true);// 建立視窗 } //構造方法 public AlgoFrame(String title){ this(title, 1024, 768); } public int getCanvasWidth(){return canvasWidth;} public int getCanvasHeight(){return canvasHeight;} }
1.3 設定畫布與圖形繪製基礎
import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class AlgoFrame extends JFrame { private int canvasWidth;// 可繪製圖形區域的寬 private int canvasHeight;// 可繪製圖形區域的高 /* * 定義建構函式 */ public AlgoFrame(String title, int canvasWidth, int canvasHeight) { super(title);// 呼叫父類構造方法,即傳入標題 this.canvasWidth = canvasWidth; this.canvasHeight = canvasHeight; AlgoCanvas canvas = new AlgoCanvas();// 建立內容面板物件 setContentPane(canvas);// 設定內容面板 pack();// 自動根據內容面板大小,調整視窗大小 setResizable(false);// 是否允許使用者改變視窗大小,這裡false是不允許 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 當點選視窗的關閉符號能使整個JFrame框架都正確關閉 setVisible(true);// 建立視窗 } public int getCanvasWidth() { return canvasWidth; } public int getCanvasHeight() { return canvasHeight; } /* * 定義內容面板類,作為內部類供AlgoFrame使用 */ private class AlgoCanvas extends JPanel { @Override public void paintComponent(Graphics g) {// 繪製元件 super.paintComponent(g); /* * 繪製一個圓 在螢幕座標系中位置(50,50),注意與數學座標系相區分 寬400 長400 */ g.drawOval(50, 50, 400, 400); } @Override public Dimension getPreferredSize() {// 返回畫布大小 return new Dimension(canvasWidth, canvasHeight); } } }
JFrame(框架):MenuBar(選單欄)+Content Pane(內容視窗,是一個容器)
Content Pane:可以新增元件,如按鈕列表等等,但本課程不使用
JPanel:充當內容面板,進行圖形繪製