Java Swing : managing integers/doubles with Listeners and J*Fields

标签 java swing

已编辑

我可能只是盯着屏幕太久了,但我觉得有必要在 sleep 前提交这个问题,以防我的谵妄仍然存在......

我遇到的问题是我试图从 JTextField textField 获取 int/double 并将其转换为 (n) int/double 以便稍后在从监听器中检索它之后在监听器中使用。 ListenForText实现了KeyListener,具体来说是KeyTyped,通过toString()来获取,并存储在一个String txtFldAmnt中。之后,如果复制到编辑器,我会将 Integer.parseInt(txtFldAmnt) 的结果存储到 fldAmnt (fldAmnt = Integer.pareseInt(txtFldAmnt)) LINE 99 中。一旦将其转换为 int,我希望能够操作它,然后在第 173 行再次使用它,以在新窗口中显示 fldAmnt。老实说,我不太关心显示的是 int 还是 String,但我知道 JTextField 需要 String。我缺少什么魔法?答案总是受欢迎的,但我更喜欢有学习的机会。另外,由于我对 Java 相当陌生,非常欢迎题外话、批评和实现此代码的更好方法:)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class GUI extends JFrame{

/**
 * wtf is the serial version UID = 1L
 */
private static final long serialVersionUID = 1L;
private JButton wdBtn;
private JButton dpBtn;
private JButton xferBtn;
private JButton balBtn;
private JRadioButton chkRadio;
private JRadioButton savRadio;
private JTextField textField;
private static String txtFldAmnt;
private static int fldAmnt = 0;
private static Double chkBal = 0.00;
private static Double savBal = 0.00;


public static void main(String[] args){
    new GUI();
}


public GUI() {

    //default location and size
    this.setSize(300,182);
    this.setLocationRelativeTo(null);
    this.setResizable(false);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("ATM Machine");

    //add buttons
    wdBtn = new JButton("Withdraw");
    dpBtn = new JButton("Deposit");
    xferBtn = new JButton("Transfer");
    balBtn = new JButton("Show Balance");
    chkRadio = new JRadioButton("Checking");
    chkRadio.setSelected(false);
    savRadio = new JRadioButton("Savings");
    savRadio.setSelected(false);
    textField = new JTextField("", 20);
    final JLabel textLabel = new JLabel("Enter amount: ");
    textField.setToolTipText("Enter amount");

    //Listener class to pass button listeners
    ListenForButton lForButton = new ListenForButton();
    wdBtn.addActionListener(lForButton);
    dpBtn.addActionListener(lForButton);
    xferBtn.addActionListener(lForButton);
    balBtn.addActionListener(lForButton);
    chkRadio.addActionListener(lForButton);
    savRadio.addActionListener(lForButton);

    ListenForText textFieldListener = new ListenForText();
    textField.addKeyListener(textFieldListener);

    //Configure layouts
    JPanel PANEL = new JPanel();
    PANEL.setLayout(new FlowLayout(FlowLayout.CENTER));
    JPanel panel1 = new JPanel();
    panel1.setLayout(new GridLayout(2,2, 5, 10));
    JPanel panel2 = new JPanel();
    panel2.setLayout(new GridLayout(1,2,10,10));
    panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
    JPanel panel3 = new JPanel();
    panel3.setLayout(new GridLayout(2,1));

    //add buttons to their panels
    panel1.add(wdBtn);
    panel1.add(dpBtn);
    panel1.add(xferBtn);
    panel1.add(balBtn);
    panel2.add(chkRadio);
    panel2.add(savRadio);
    panel3.add(textLabel);
    panel3.add(textField);

    PANEL.add(panel1);
    PANEL.add(panel2);
    PANEL.add(panel3);

    this.add(PANEL);
    //this.setAlwaysOnTop(true);
    this.setVisible(true);
}
//implement listeners
private class ListenForText implements KeyListener {

    @Override
    public void keyTyped(KeyEvent e) {
        txtFldAmnt = (e.toString());
        fldAmnt = Integer.parseInt(txtFldAmnt);

    }

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

}
private class ListenForButton implements ActionListener {

    public void actionPerformed(ActionEvent e){

        //maybe do case/switch statements
        if (e.getSource() == wdBtn) {
            JFrame newFrame = new JFrame("Withdraw Title");
            newFrame.setResizable(false);
            newFrame.setLocationRelativeTo(null);
            newFrame.setSize(300, 91);

            JPanel panel = new JPanel();
            JLabel newLbl = new JLabel("Withdraw Frame", JLabel.CENTER);

            panel.add(newLbl);
            newFrame.add(panel);
            newFrame.setVisible(true);
        }
        if (e.getSource() == dpBtn) {
            JFrame newFrame = new JFrame("Deposit Title");
            /*
             * Set the newFrame.setSize(300,182); to this comment in the if statement to place
             * the window directly over current window
             */
            newFrame.setResizable(false);
            newFrame.setLocationRelativeTo(null);
            newFrame.setSize(300, 91);

            JPanel panel = new JPanel();
            JLabel newLbl = new JLabel("Deposit Frame", JLabel.CENTER);

            panel.add(newLbl);
            newFrame.add(panel);
            newFrame.setVisible(true);
        }
        if (e.getSource() == xferBtn) {
            JFrame newFrame = new JFrame("Transfer Title");

            newFrame.setResizable(false);
            newFrame.setLocationRelativeTo(null);
            newFrame.setSize(300, 91);

            JPanel panel = new JPanel();
            JLabel newLbl = new JLabel("Transfer Frame", JLabel.CENTER);

            panel.add(newLbl);
            newFrame.add(panel);
            newFrame.setVisible(true);
        }
        if (e.getSource() == balBtn){
            JFrame newFrame = new JFrame("Balance Title");

            newFrame.setResizable(false);
            newFrame.setLocationRelativeTo(null);
            newFrame.setSize(300, 91);

            JPanel panel = new JPanel();
            JTextField newLbl = new JTextField(Integer.toString(fldAmnt));

            panel.add(newLbl);
            newFrame.add(panel);
            newFrame.setVisible(true);

        }
    }
}
}

-干杯

编辑如下

感谢您的回答,我对可怕的描述感到抱歉...但我找到了解决方法,尽管我不确定它是否合适。 以上面的例子:

fldAmnt = Integer.pareseInt(txtFldAmnt)

我刚刚添加了一个 .getText()//虽然我重写了整个源代码

fldAmnt = Integer.pareseInt(txtFldAmnt.getText())

它对我的整个计划都很有效。

我希望不必在下面发布我的整个代码,但我还没有决定一个存储所有代码的好地方。 (欢迎提出建议:D)

但这里是: 导入 javax.swing.; 导入java.awt.GridLayout; 导入java.awt.event.; 导入 javax.swing.border.*;

public class ATM extends JFrame{
//buttons needed
JButton wBtn;
JButton dBtn;
JButton xBtn;
JButton bBtn;
//radios needed
JRadioButton cRadio;
JRadioButton sRadio;
//Text field needed
JTextField txt;
JLabel txtLabel;
static int withdraw = 0;
Double amount = 0.00;
Double cBal = 100.00;
Double sBal = 100.00;


double number1, number2, totalCalc;

public static void main(String[] args){

    new Lesson22();

}
public ATM(){
    this.setSize(400, 200);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("My Third Frame");

    wBtn = new JButton("Withdraw");

    dBtn = new JButton("Deposit");
    xBtn = new JButton("Transfer");
    bBtn = new JButton("Show Balance");
    cRadio = new JRadioButton("Checking");
    sRadio = new JRadioButton("Savings");
    txtLabel = new JLabel("Amount: $");
    txt = new JTextField("", 10);

    JPanel thePanel = new JPanel();

    // Create an instance of ListenForEvents to handle events

    ListenForButton lForButton = new ListenForButton();

    wBtn.addActionListener(lForButton);
    dBtn.addActionListener(lForButton);
    xBtn.addActionListener(lForButton);
    bBtn.addActionListener(lForButton);


    // How to add a label --------------------------

    // Creates a group that will contain radio buttons
    // You do this so that when 1 is selected the others
    // are deselected

    ButtonGroup operation = new ButtonGroup();

    // Add radio buttons to the group

    operation.add(cRadio);
    operation.add(sRadio);

    // Create a new panel to hold radio buttons

    JPanel operPanel = new JPanel();
    JPanel btnPanel1 = new JPanel();
    JPanel btnPanel2 = new JPanel();
    btnPanel1.setLayout(new GridLayout(1,2));
    btnPanel2.setLayout(new GridLayout(1,2));

    Border btnBorder = BorderFactory.createEmptyBorder();
    btnPanel1.setBorder(btnBorder);
    btnPanel1.add(wBtn);
    btnPanel1.add(dBtn);
    btnPanel2.setBorder(btnBorder);
    btnPanel2.add(xBtn);
    btnPanel2.add(bBtn);


    Border operBorder = BorderFactory.createBevelBorder(1);

    // Set the border for the panel

    operPanel.setBorder(operBorder);

    // Add the radio buttons to the panel

    operPanel.add(cRadio);
    operPanel.add(sRadio);


    // Selects the add radio button by default
    cRadio.setSelected(true);
    JPanel txtPanel = new JPanel();
    txtPanel.add(txtLabel);
    txtPanel.add(txt);


    thePanel.add(btnPanel1);
    thePanel.add(btnPanel2);
    thePanel.add(operPanel);
    thePanel.add(txtPanel);
    thePanel.setLayout(new GridLayout(4,2));
    this.add(thePanel);

    this.setVisible(true);

    txt.requestFocus();

}

private class ListenForButton implements ActionListener{

    // This method is called when an event occurs

    public void actionPerformed(ActionEvent e){
        /******************************************************
         * THIS IS FOR CHECKING
         *****************************************************/
        // Check if the source of the event was the button
        if(cRadio.isSelected()){
            if(e.getSource() == wBtn){
                try {
                    amount = Double.parseDouble(txt.getText());
                    cBal -= amount;
                }
                catch(NumberFormatException excep){
                    JOptionPane.showMessageDialog(ATM.this, 
                            "Please enter a valid number in multiples of 20", 
                            "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
            if(e.getSource() == bBtn){
                JFrame bFrame = new JFrame();
                bFrame.setSize(300, 182);
                bFrame.setLocationRelativeTo(null);
                JPanel panel = new JPanel();
                JLabel cLabel = new JLabel(Double.toString(cBal));
                JLabel CLBL = new JLabel("Checking: ");
                panel.add(CLBL);
                panel.add(cLabel);
                bFrame.add(panel);
                bFrame.setVisible(true);
            }

            if(e.getSource() == dBtn){
                amount = Double.parseDouble(txt.getText());
                cBal += amount;
            }
            if(e.getSource() == xBtn){
                amount = Double.parseDouble(txt.getText());
                if (sBal >= 0 && sBal >= amount){
                    cBal += amount;
                    sBal -= amount;
                }
                else if (sBal < amount) {
                    JOptionPane.showMessageDialog(ATM.this,
                            "INSUFFICENT FUNDS", "ERROR", 
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        /******************************************************
         * THIS IS FOR SAVINGS
         *****************************************************/
        if(sRadio.isSelected()){
            if(e.getSource() == wBtn){
                try {
                    amount = Double.parseDouble(txt.getText());
                    if(sBal >= 0 && sBal >= amount){
                        sBal -= amount;
                    }
                    else if (sBal < amount) {
                        JOptionPane.showMessageDialog(ATM.this,
                                "INSUFFICENT FUNDS", "ERROR", 
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
                catch(NumberFormatException excep){
                    JOptionPane.showMessageDialog(ATM.this, 
                            "Please enter a valid number in multiples of 20", 
                            "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
            if(e.getSource() == bBtn){
                JFrame bFrame = new JFrame();
                bFrame.setSize(300, 182);
                bFrame.setLocationRelativeTo(null);
                JPanel panel = new JPanel();
                JLabel sLabel = new JLabel(Double.toString(sBal));
                JLabel SLBL = new JLabel("Savings: ");
                panel.add(SLBL);
                panel.add(sLabel);

                bFrame.add(panel);
                bFrame.setVisible(true);
            }

            if(e.getSource() == dBtn){
                try{
                    amount = Double.parseDouble(txt.getText());
                    sBal += amount;
                }
                catch(NumberFormatException excep){
                    JOptionPane.showMessageDialog(ATM.this, 
                            "Please enter a valid number!", 
                            "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
            if(e.getSource() == xBtn){
                amount = Double.parseDouble(txt.getText());
                if (cBal >= 0 && cBal >= amount){
                    sBal += amount;
                    cBal -= amount;
                }
                else if (cBal < amount) {
                    JOptionPane.showMessageDialog(ATM.this,
                            "INSUFFICENT FUNDS", "ERROR", 
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }
}
}

...顺便说一下,谁能解释一下这个警告消息: 可序列化类 ATM 未声明 long 类型的静态最终 serialVersionUID 字段

如果不是,就不要打扰。有时间我会继续研究。

这仍然不完整,但感谢大家的帮助!

最佳答案

任何 JTextComponent 上的

KeyListener 都是一个坏主意。

要监视文本组件的更改,请使用 DocumentListener,要过滤文本组件可以处理的内容,请使用 DocumentFilter。请参阅Listening for Changes on a Document , Implementing a Document FilterDocumentFilter Examples了解更多详情。

就您而言,最好使用 JSpinnerJFormattedTextField 因为它们旨在处理(除其他外)数字

参见How to Use SpinnersHow to Use Formatted Text Fields了解更多详情

关于Java Swing : managing integers/doubles with Listeners and J*Fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33705120/

相关文章:

java - JPopupMenu 中的居中 JLabel

java - LocalDateTime Java - 获取下个月的同一天

java - 如何在 jOOQ 中使用别名

java - Mysql表不存在/JPA注解

Java:在子类化中使用通用通配符

java - 将 JButton 动态添加到 JPanel 中,无法与 Netbeans 一起使用

java - jsp 页面中的 swf 播放器

java - 父面板未正确重绘

java - JCombobox 列表背景颜色覆盖选定的背景项目颜色

java - JTable 重复行