JTextArea Filters and/or Inputs of time (00:00:00) Java

后端 未结 3 1467
误落风尘
误落风尘 2021-01-26 12:47

There\'s a section of my program where the user should have the ability to edit an amount of time. There will be a default amount of time already set but the user should be able

3条回答
  •  臣服心动
    2021-01-26 13:37

    I think you'll want to use a JFormattedTextField. I've written a simple example. Just run it, type something into the box, and hit tab to change focus (and thus update the label).

        import java.awt.*;
        import java.awt.event.*;
        import java.text.*;
        import java.util.*;
        import javax.swing.*;
        import javax.swing.event.*;
        import javax.swing.text.*;
    
        public class MyPanel extends JPanel implements DocumentListener {
          private JFormattedTextField ftf;
          private JLabel output;
          private DateFormat myFormat;
    
          public MyPanel() {
            this.setFocusable(true);
    
            myFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);
    
            ftf = new JFormattedTextField(myFormat);
            ftf.setValue(new Date());
            this.add(ftf);
    
            output = new JLabel("--:--:--");
            this.add(output);
    
            ftf.getDocument().addDocumentListener(this);
          }
    
          public void update() {
            // get the time
            Date date = (Date)ftf.getValue();
    
            // display it
            output.setText(myFormat.format(date));
          }
    
          public void changedUpdate(DocumentEvent e) { update(); }
          public void insertUpdate(DocumentEvent e) { update(); }
          public void removeUpdate(DocumentEvent e) { update(); }
    
          public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setSize(640, 480);
    
            frame.add(new MyPanel());
    
            frame.setVisible(true);
          }
        }
    

提交回复
热议问题