我目前在一个做介绍摆动的班级。我们的任务是创建一个计算器 GUI。我制作了使用边框布局和网格布局的组合来请求的 GUI。我不确定如何赋予按钮功能,浏览了讲义,但没有看到它。
我在网上看到过示例,但看起来都一样,我认为它们没有帮助,因为我看到的那些使用单个按钮,我需要一种方法来区分我的按钮,因为每个按钮都有自己的操作。
要注意这个计算器不需要任何功能,我只需要它来记录按钮点击,一旦我弄清楚了这一点,我就会将其添加到字符串"输入"中,并将该视觉效果保留给用户。IE 如果用户(老师(点击 5 * 5 需要显示在屏幕顶部,但我不需要 25 的答案。
这是我的代码,它运行并具有我想要的 GUI 布局。
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JPanel;
public class GUI extends JFrame implements ItemListener{ //ActionListener
//JTextArea info = new JTextArea("this will calculate numbers");
JTextField f1 = new JTextField(10); //param = width
protected String input;
//*****************************************************************************************************************
//constructor
//@ args String, Int, Int
public GUI(String title, int width, int height ){
//gui.pack() *try this later*
setBounds(500, 170, width, height);// sets location x,y on screen at start of program also sets size of GUI x,y
setTitle(title); //sets title of
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //needed else x wont close properly
createGUI();
}
//separate gui logic from other logic
public void createGUI(){
//set layout you plan to use
setLayout(new BorderLayout());
//add(info, BorderLayout.NORTH);
add(f1, BorderLayout.NORTH);
//CENTER********************************************************************************************************
JPanel center = new JPanel();
center.setLayout(new GridLayout(4,3));
center.add(new JButton("1"));
center.add(new JButton("2"));
center.add(new JButton("3"));
center.add(new JButton("4"));
center.add(new JButton("5"));
center.add(new JButton("6"));
center.add(new JButton("7"));
center.add(new JButton("8"));
center.add(new JButton("9"));
center.add(new JButton("0"));
center.add(new JButton("."));
center.add(new JButton("C"));
add(center, BorderLayout.CENTER);
//EAST**********************************************************************************************************
JPanel east = new JPanel();
east.setLayout(new GridLayout(6,1));
east.add(new JButton("+"));
east.add(new JButton("-"));
east.add(new JButton("x"));
east.add(new JButton("/"));
east.add(new JButton("%"));
east.add(new JButton("="));
add(east, BorderLayout.EAST);
}
//main
public static void main(String[] args){
GUI calculator = new GUI("GUI Calculator",300,250);
calculator.setVisible(true);//makes calculator gui visible *make this line last or close to last*
}
//Must do this method or else class must be made abstract
public void itemStateChanged(ItemEvent event){
}
}
本质上,对于每个按钮,您希望为其分配一个ActionListener
,当用户激活按钮时,它将调用它的actionPerformed
,方法。
就个人而言,我会使用 Action
,这是一个自我连续的工作单元,但您可以使用内部类或匿名类,我会避免使用一种大型actionPerformed
方法,因为随着时间的推移它变得难以管理
有关详细信息,请参阅如何编写操作侦听器、如何使用操作以及如何使用按钮、复选框和单选按钮。
将ActionListener添加到按钮中;(