Java作為一種廣泛使用的編程語言,其圖形用戶界面(GUI)開發能力一直是其重要特性之一。Java提供了多種GUI開發工具包,如AWT、Swing和JavaFX,這些工具包使得開發者能夠創建豐富的桌面應用程序。本文將通過一個簡單的實例,分析如何使用Java Swing進行GUI開發,并探討其可視化效果。
我們將創建一個簡單的計算器應用程序,該應用程序具有基本的加減乘除功能。用戶可以通過點擊按鈕輸入數字和操作符,并在文本框中顯示結果。這個實例將展示如何使用Swing組件構建用戶界面,并處理用戶交互。
首先,我們需要創建一個主窗口(JFrame),并設置其大小和關閉操作。
import javax.swing.*;
public class Calculator {
public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
接下來,我們將在主窗口中添加文本框(JTextField)用于顯示輸入和結果,以及按鈕(JButton)用于輸入數字和操作符。
import javax.swing.*;
import java.awt.*;
public class Calculator {
public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(280, 40));
frame.add(textField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 10, 10));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (String button : buttons) {
JButton btn = new JButton(button);
buttonPanel.add(btn);
}
frame.add(buttonPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
}
為了處理按鈕點擊事件,我們需要為每個按鈕添加ActionListener。當按鈕被點擊時,相應的數字或操作符將被添加到文本框中。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator {
public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(280, 40));
frame.add(textField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 10, 10));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (String button : buttons) {
JButton btn = new JButton(button);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
textField.setText(textField.getText() + command);
}
});
buttonPanel.add(btn);
}
frame.add(buttonPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
}
最后,我們需要實現計算邏輯。當用戶點擊“=”按鈕時,程序將解析文本框中的表達式并計算結果。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator {
public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(280, 40));
frame.add(textField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 10, 10));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (String button : buttons) {
JButton btn = new JButton(button);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
String expression = textField.getText();
try {
double result = evaluateExpression(expression);
textField.setText(String.valueOf(result));
} catch (Exception ex) {
textField.setText("Error");
}
} else {
textField.setText(textField.getText() + command);
}
}
});
buttonPanel.add(btn);
}
frame.add(buttonPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
private static double evaluateExpression(String expression) {
return new Object() {
int pos = -1, ch;
void nextChar() {
ch = (++pos < expression.length()) ? expression.charAt(pos) : -1;
}
boolean eat(int charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
double parse() {
nextChar();
double x = parseExpression();
if (pos < expression.length()) throw new RuntimeException("Unexpected: " + (char)ch);
return x;
}
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) x += parseTerm(); // addition
else if (eat('-')) x -= parseTerm(); // subtraction
else return x;
}
}
double parseTerm() {
double x = parseFactor();
for (;;) {
if (eat('*')) x *= parseFactor(); // multiplication
else if (eat('/')) x /= parseFactor(); // division
else return x;
}
}
double parseFactor() {
if (eat('+')) return parseFactor(); // unary plus
if (eat('-')) return -parseFactor(); // unary minus
double x;
int startPos = this.pos;
if (eat('(')) { // parentheses
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = Double.parseDouble(expression.substring(startPos, this.pos));
} else {
throw new RuntimeException("Unexpected: " + (char)ch);
}
return x;
}
}.parse();
}
}
通過這個簡單的計算器實例,我們展示了如何使用Java Swing進行GUI開發。從創建主窗口到添加組件,再到處理用戶交互和實現計算邏輯,每一步都展示了Java GUI開發的強大功能和靈活性。希望這個實例能夠幫助讀者更好地理解Java GUI開發的基本概念和技術。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。