【Java】【组件及事件处理】计算器界面
作者:互联网
package com.itheima;
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame{
JTextField textField;
GridLayout gridLayout;
JButton button[][];
JPanel jPanel;
public MyFrame() {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init(){
button = new JButton[5][5];
BorderLayout borderLayout = (BorderLayout)getContentPane().getLayout();
borderLayout.setHgap(20);
borderLayout.setVgap(10);
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.TRAILING); //文本输入
textField.setPreferredSize(new Dimension(12,50)); //设置组件文本框大小
add(textField,BorderLayout.NORTH);
textField.setColumns(10);
gridLayout = new GridLayout(4,0);
gridLayout.setHgap(5); //设置组件的水平间距
gridLayout.setVgap(5); //设置组件的垂直间距
jPanel = new JPanel();
jPanel.setLayout(gridLayout);
add(jPanel,BorderLayout.CENTER);
String name[][] = {{"1","2","3","+"},{"4","5","6","-"},{"7","8","9","*"},
{".","0","=","÷"}};
button = new JButton[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
button[i][j] = new JButton(name[i][j]);
jPanel.add(button[i][j]);
}
}
}
}
Main类:
package com.itheima;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setBounds(100,100,290,282);
myFrame.setTitle("按钮数组实现计算器界面");
}
}
标签:事件处理,Java,button,jPanel,计算器,gridLayout,new,textField,MyFrame 来源: https://blog.csdn.net/weixin_48180029/article/details/112018906