DocumentListener Java,如何防止 JTextBox 中出现空字符串?

2023-11-21

enter image description hereI have been working on a personal project to get better with programming. My goal is to make it much more robust, I am just starting. I am a current computer science student. Anyway, I am working on making a portion of the program as shown. I calculates the hourly wage and provides some outputs I havent implemented yet. I'm using DocumentListener so it it will automatically calculate. I am getting an error when the the text is removed completely from a box.I tried to fix it with the if statement:

 if (tipMon.equals("") || tipMon == null) {
 tipMon.setText("0");
 }

这是我到目前为止所拥有的。它还没有完成,我对菜鸟代码表示歉意。我两个月前开始实际编码。

 import java.awt.GridLayout;
 import java.awt.event.ActionListener;
 import java.awt.event.ActionEvent;
 import java.awt.event.KeyListener;

 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JTextField;
 import javax.swing.JOptionPane;
 import javax.swing.event.DocumentEvent;
 import javax.swing.event.DocumentListener;
 import javax.swing.text.Document;
 import javax.swing.text.FieldView;

 public class deliveryDocListener extends JFrame implements ActionListener, 
DocumentListener{

private JLabel mon, tues, wed, thurs, fri, sat, sun, hourlyWage, blank, row2, monWage,
    tuesWage,wedWage,thursWage, friWage, satWage, sunWage, total, totalTips, totalHours, 
    totalHourlyEarnings, totalPay, weekPay;

private JTextField hourlyWageInput, tipMon, tipTues, tipWed, tipThurs, tipFri, tipSat, tipSun,
    hourMon, hourTues, hourWed, hourThurs, hourFri, hourSat, hourSun;


public deliveryDocListener(){
    super("Delivery Helper v0.1 Alpha");
    setLayout(new GridLayout(0,4));

    hourlyWage = new JLabel("Hourly Wage: ");
    add(hourlyWage);
    hourlyWageInput = new JTextField("7.25", 5);

    add(hourlyWageInput);
    blank = new JLabel();
    add(blank);
    blank = new JLabel();
    add(blank);

    row2 = new JLabel("Day of the Week");
    add(row2);
    row2 = new JLabel("Tips");
    add(row2);
    row2 = new JLabel("Hours Worked");
    add(row2);
    row2 = new JLabel("Hourly Earnings");
    add(row2);

    mon = new JLabel("Monday");
    add(mon);



    tipMon = new JTextField("0");

    Document tipMonListener = tipMon.getDocument();
    //Document class doc variable stores what happens in the getDocument()
    //method, getDocument() i think is what checked it real time we shall see
    tipMonListener.addDocumentListener(this);
    //add listener to he text field, this refers to most recent object (tipMon = new JTextField("0");"
    //notice how its purple is the same as new where the object got made?
    add(tipMon);

    hourMon = new JTextField("0");
    Document hourMonListener = hourMon.getDocument();
    hourMonListener.addDocumentListener(this);
    add(hourMon);


    monWage = new JLabel("0");
    add(monWage);

    tues = new JLabel("Tuesday");
    add(tues);
    tipTues = new JTextField("0");
    add(tipTues);
    hourTues = new JTextField("0");
    add(hourTues);
    tuesWage = new JLabel("0");
    add(tuesWage);

    wed = new JLabel("Wednesday");
    add(wed);
    tipWed = new JTextField("0");
    add(tipWed);
    hourWed = new JTextField("0");
    add(hourWed);
    wedWage = new JLabel("0");
    add(wedWage);

    thurs = new JLabel("Thursday");
    add(thurs);
    tipThurs = new JTextField("0");
    add(tipThurs);
    hourThurs = new JTextField("0");
    add(hourThurs);
    thursWage = new JLabel("0");
    add(thursWage);

    fri = new JLabel("Friday");
    add(fri);
    tipFri = new JTextField("0");
    add(tipFri);
    hourFri = new JTextField("0");
    add(hourFri);
    friWage = new JLabel("0");
    add(friWage);

    sat = new JLabel("Saturday");
    add(sat);
    tipSat = new JTextField("0");
    add(tipSat);
    hourSat = new JTextField("0");
    add(hourSat);
    satWage = new JLabel("0");
    add(satWage);

    sun = new JLabel("Sunday");
    add(sun);
    tipSun = new JTextField("0");
    add(tipSun);
    hourSun = new JTextField("0");
    add(hourSun);
    sunWage = new JLabel("0");
    add(sunWage);

    blank = new JLabel();
    add(blank);
    blank = new JLabel();
    add(blank);
    blank = new JLabel();
    add(blank);
    blank = new JLabel();
    add(blank);

    total = new JLabel("Total: ");
    add(total);
    totalTips = new JLabel("totalTipsOutput");
    add(totalTips);
    totalHours = new JLabel("totalHoursOutput");
    add(totalHours);
    totalHourlyEarnings = new JLabel("totalHourlyEarningsOutput");
    add(totalHourlyEarnings);

    blank = new JLabel();
    add(blank);
    blank = new JLabel();
    add(blank);
    blank = new JLabel();
    add(blank);
    blank = new JLabel();
    add(blank);

    blank = new JLabel();
    add(blank);
    blank = new JLabel();
    add(blank);
    totalPay = new JLabel("Gross Income: ");
    add(totalPay);
    weekPay = new JLabel("totalPayOutput");
    add(weekPay);

}

@Override
public void changedUpdate(DocumentEvent e) { 
    // TODO Auto-generated method stub

}

@Override
public void insertUpdate(DocumentEvent e) {
    //executes when someone enters text into input
    String tipMonStr = tipMon.getText();
    //monWage.setText(tipMonStr);
    String hourMonStr = hourMon.getText();

    double x = Double.parseDouble(tipMonStr);
    double y = Double.parseDouble(hourMonStr);
    double z = Double.parseDouble(hourlyWageInput.getText());

    if (tipMonStr.length() == 0) {
        tipMon.setText("0");
    }

    if (hourMonStr.length() == 0) {
        y = 0;
        hourMonStr = "0";
    }

    if (hourlyWageInput.getText().length() == 0) {
        z = 0;
        //String z = "0";
    }

    monWage.setText(Double.toString((z*y+x)/y));

    //bug when nothing in cell because no number (0) to use in math
}

@Override
public void removeUpdate(DocumentEvent e) {
    //executes when someone enters text into input
    String tipMonStr = tipMon.getText();
    //monWage.setText(tipMonStr);
    String hourMonStr = hourMon.getText();

    double x = Double.parseDouble(tipMonStr);
    double y = Double.parseDouble(hourMonStr);
    double z = Double.parseDouble(hourlyWageInput.getText());
    monWage.setText(Double.toString((z*y+x)/y));

    if (tipMon.equals("") || tipMon == null) {
        tipMon.setText("0");
    }

}


public void updateLog(DocumentEvent e, String action) {
    monWage.setText(Double.toString(5));
}

@Override
public void actionPerformed(ActionEvent arg0) {
    monWage.setText(Double.toString(5));

}

}


正如@HFOE 所建议的,InputVerifier是正确的选择,但是verify()“应该没有副作用。”相反,调用calcProduct() in shouldYieldFocus().

 /**
 * @see http://stackoverflow.com/a/11818946/230513
 */
private class MyInputVerifier extends InputVerifier {

    private JTextField field;
    private double value;

    public MyInputVerifier(JTextField field) {
        this.field = field;
    }

    @Override
    public boolean shouldYieldFocus(JComponent input) {
        if (verify(input)) {
            field.setText(String.valueOf(value));
            calcProduct();
            return true;
        } else {
            field.setText(ZERO);
            field.selectAll();
            return false;
        }

    }

    @Override
    public boolean verify(JComponent input) {
        try {
            value = Double.parseDouble(field.getText());
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

DocumentListener Java,如何防止 JTextBox 中出现空字符串? 的相关文章

随机推荐

  • 使用 cin 将输入作为函数参数传递

    我的程序 class test int k public void changeval int i k i int main test obj int i cin gt gt i obj changeval i return 0 有什么方法
  • char* 和 int* 之间的区别

    有什么区别char and int 当然 它们是不同类型的 但我怎么能写 char s1 hello world as hello world 它不是一个字符 而是一组字符 我不能写 s1 as char s1 h e l l o w o
  • Java中两个List的有效交集?

    问题很简单 我有两个列表 List
  • “.equals”和“==”有什么区别? [复制]

    这个问题在这里已经有答案了 我今天换了讲师 他对我说使用了一个奇怪的代码 他说最好用 equals当我问为什么时 他回答说 因为是这样 这是一个例子 if o1 equals o2 System out println Both integ
  • jQuery 上下文菜单 - 查找触发它的元素

    我正在尝试为我的页面编写一个上下文菜单选项 基本上 右键单击 div 会弹出一个选项菜单 可用于执行任务 我的问题是试图找到触发所有内容的原始元素 即右键单击的 div 我的 jQuery 代码或多或少是 this is what disp
  • 用 Java 创建自定义 JButton

    有没有办法创建一个JButton使用您自己的按钮图形而不仅仅是按钮内的图像 如果没有 是否有其他方法来创建自定义JButton在java中 当我第一次学习 Java 时 我们必须制作 Yahtzee 我认为创建自定义 Swing 组件和容器
  • 使用 Firebase 获取 downloadURL 不断抛出错误“XMLHttpRequest 未定义”

    当尝试获取刚刚上传到存储的图像的 downloadURL 时 我不断收到 XMLHttpRequest 未定义 消息 对这里发生的事情有什么想法吗 我可以检索元数据 但图像 url 未在方案中列出 Node import firebase
  • 将具有唯一 id 属性的对象数组转换为 Map

    我有一个对象数组 其中每个对象都有一个名为的唯一成员id 如何创建地图id如果地图的钥匙 您想将数组减少为地图 const arr id 1 id 2 id 2 const map arr reduce acc item gt acc se
  • 如何从应用程序客户端连接远程 EJB 模块

    我的计算机上的远程 Glassfish 服务器和应用程序客户端中有一个 EJB 模块 我想从应用程序客户端连接到远程 EJB 这是我的 EJB 界面 Remote public interface BookEJBRemote public
  • 使用cowplot和ggplot2在某些行周围绘制边框

    我想以某种方式表明多面板图中的某些行应该一起比较 例如 我想绘制这个图 如下图所示 用 PowerPoint 制作的面板周围有方框 这是我为使用第一个图而编写的代码 我使用了ggplot和cowplot require cowplot th
  • 引用变量存储在哪里[重复]

    这个问题在这里已经有答案了 我知道引用不会占用任何内存 它会指向它所引用的同一内存位置 例如 int i 10 int r a suppose i指向内存位置 1000 所以在这种情况下r也将指向内存位置 1000 但在 C 中 每当我们声
  • MongoCursor 中的 Limit 和 BatchSize 有什么区别?

    MongoDB 游标对象提供了BatchSize财产and and Limit属性 但我似乎找不到任何明确的信息来正确阐明两者之间的区别 我正在使用 Net 驱动程序 因为它物有所值 限制是您想要的结果总数 如果您的查询将返回 1000 个
  • 有人知道 OOP PHP 的良好培训资源吗?

    我想看看大家是否可以分享一些关于 PHP 语言的 OOP 的好的培训资源 有人知道 OOP 面向对象编程 PHP 的良好培训资源吗 我看过很多教程 大部分都是肤浅的 其中一些很糟糕 Please分享任何好的商业或免费 视频或书面内容 我喜欢
  • 如何手动设置 gradle-2.2.1-all.zip

    我想用这个命令运行我的单元测试 gradlew bat connectedInstrumentTest 但它尝试下载https services gradle org distributions gradle 2 2 1 all zip 我
  • 从 JavaScript 调用 ASP.NET MVC 操作方法

    我有这样的示例代码 div class cart a class button span Add to Cart span a div div class wishlist a Add to Wish List a div div clas
  • 如何在Scala中实例化Unit?

    我所希望的只是使用一些并发集 似乎根本不存在 Java用途java util concurrent ConcurrentHashMap
  • “保护”文本框值不被输入(HTML 表单)

    我想知道是否可以为 HTML 文本框分配一个值并保护它 我的意思是使其内容不可修改 这样当提交表单时我 确定 提交的是这个值 顺便说一句 我意识到更简单的方法是不 监听 此输入并仅分配它 但它会派上用场 能够执行上述操作 我希望这个问题足够
  • 使用jquery自动打印

    我有以下格式的数据 虚拟条目 id posGridView 当我处理销售时 会自动打印一张小收据 其中包含选定的列 而不是所有列 因为所有数据都在此网格视图中可用 所以如何使用 jquery 以任何格式动态打印它 Edited 实际上我想从
  • 单一职责原则对于验证意味着什么

    单一责任原则是否意味着您的验证规则应该位于实体外部 如果是这样 您是否为每个验证规则使用一个类 我通常将其解释为 实体 和实体的验证应该是单独的问题 我通常会使用可以验证整个实体的单个类 但我认为没有理由通过不允许该类使用其他类来限制其实现
  • DocumentListener Java,如何防止 JTextBox 中出现空字符串?

    I have been working on a personal project to get better with programming My goal is to make it much more robust I am jus