您好,登錄后才能下訂單哦!
用Java編寫計算器,代碼展示!
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class ButtonArrayExample extends JFrame { // 繼承窗體類JFrame
/**
*/
private static final long serialVersionUID = 6626440733001287873L;
private JTextField textField;
public static void main(String args[]) {
try {
UIManager.setLookAndFeel("");
} catch (Throwable e) {
e.printStackTrace();
}
ButtonArrayExample frame = new ButtonArrayExample();
frame.setVisible(true); // 設置窗體可見,默認為不可見
}
public ButtonArrayExample() {
super(); // 繼承父類的構(gòu)造方法
BorderLayout borderLayout = (BorderLayout) getContentPane().getLayout();
borderLayout.setHgap(20);
borderLayout.setVgap(10);
setTitle("計算器"); // 設置窗體的標題
setBounds(100, 100, 290, 282); // 設置窗體的顯示位置及大小
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 設置窗體關閉按鈕的動作為退出
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.TRAILING);
textField.setPreferredSize(new Dimension(12, 50));
getContentPane().add(textField, BorderLayout.NORTH);
textField.setColumns(10);
final GridLayout gridLayout = new GridLayout(4, 0); // 創(chuàng)建網(wǎng)格布局管理器對象
gridLayout.setHgap(5); // 設置組件的水平間距
gridLayout.setVgap(5); // 設置組件的垂直間距
JPanel panel = new JPanel(); // 獲得容器對象
panel.setLayout(gridLayout); // 設置容器采用網(wǎng)格布局管理器
getContentPane().add(panel, BorderLayout.CENTER);
String[][] names = { { "1", "2", "3", "+" }, { "4", "5", "6", "-" }, { "7", "8", "9", "×" }, { ".", "0", "=", "÷" } };
JButton[][] buttons = new JButton[4][4];
for (int row = 0; row < names.length; row++) {
for (int col = 0; col < names.length; col++) {
buttons[row][col] = new JButton(names[row][col]); // 創(chuàng)建按鈕對象
buttons[row][col].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String text = textField.getText();
textField.setText(text + button.getText());
}
});
panel.add(buttons[row][col]); // 將按鈕添加到面板中
}
}
}
}
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。