【发布时间】:2014-04-24 03:16:26
【问题描述】:
我试图让用户输入到框架中的数字乘以 2 或除以 3,具体取决于他们决定单击的按钮。我很难找出这样做的逻辑。我知道这需要在 actionperformed 方法中进行。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quiz4 extends JFrame ActionListener
{
// Global Variable Declarations
// Our list input fields
private JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
private JTextField valueField = new JTextField(25);
// create action buttons
private JButton multiButton = new JButton("x2");
private JButton divideButton = new JButton("/3");
private JScrollPane displayScrollPane;
private JTextArea display = new JTextArea(10,5);
// input number
private BufferedReader infirst;
// output number
private NumberWriter outNum;
public Quiz4()
{
//super("List Difference Tool");
getContentPane().setLayout( new BorderLayout() );
// create our input panel
JPanel inputPanel = new JPanel(new GridLayout(1,1));
inputPanel.add(valueLabel);
inputPanel.add(valueField);
getContentPane().add(inputPanel,"Center");
// create and populate our diffPanel
JPanel diffPanel = new JPanel(new GridLayout(1,2,1,1));
diffPanel.add(multiButton);
diffPanel.add(divideButton);
getContentPane().add(diffPanel, "South");
//diffButton.addActionListener(this);
} // Quiz4()
public void actionPerformed(ActionEvent ae)
{
} // actionPerformed()
public static void main(String args[])
{
Quiz4 f = new Quiz4();
f.setSize(1200, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ // Quit the application
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} // main()
} // end of class
【问题讨论】:
-
为每个按钮添加一个 ActionListener,然后在 actionPerformed(ActionEvent arg0) 方法中添加您想要完成的操作。
-
在 actionPerformed 中,我如何将输入编码为乘以 2 或除以 3?
-
我给你举个更简单的例子,但对按钮使用相同的逻辑,可以吗?
标签: java user-interface division multiplication