格式化文本字段和JComboBox在一起

Hur*_*ler 3 java user-interface swing combobox jformattedtextfield

我有一个GUI窗口,询问休息时间.我想得到的结果是,例如,1:15 - int hours = 1和int mins = 15 - 单击继续按钮后.我得到的结果要么是小时,要么是分钟,因为我不能让JComboBox和JButton一起工作(我想).另外,我不太清楚如何检查用户是输入了数字还是输入了无效的输入.这是代码:

@SuppressWarnings("serial")
public class FormattedTextFields extends JPanel implements ActionListener {

    private int hours;
    private JLabel hoursLabel;
    private JLabel minsLabel;
    private static String hoursString = " hours: ";
    private static String minsString = " minutes: ";
    private JFormattedTextField hoursField;
    private NumberFormat hoursFormat;

    public FormattedTextFields() {

        super(new BorderLayout());
        hoursLabel = new JLabel(hoursString);
        minsLabel = new JLabel(minsString);
        hoursField = new JFormattedTextField(hoursFormat);
        hoursField.setValue(new Integer(hours));
        hoursField.setColumns(10);
        hoursLabel.setLabelFor(hoursField);
        minsLabel.setLabelFor(minsLabel);

        JPanel fieldPane = new JPanel(new GridLayout(0, 2));

        JButton cntButton = new JButton("Continue");
        cntButton.setActionCommand("cnt");
        cntButton.addActionListener(this);
        JButton prevButton = new JButton("Back");

        String[] quarters = { "15", "30", "45" };

        JComboBox timeList = new JComboBox(quarters);
        timeList.setSelectedIndex(2);
        timeList.addActionListener(this);

        fieldPane.add(hoursField);
        fieldPane.add(hoursLabel);
        fieldPane.add(timeList);
        fieldPane.add(minsLabel);
        fieldPane.add(prevButton);
        fieldPane.add(cntButton);

        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        add(fieldPane, BorderLayout.CENTER);
    }

    private static void createAndShowGUI() {    
        JFrame frame = new JFrame("FormattedTextFieldDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new FormattedTextFields());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {    
        if (e.getActionCommand().equalsIgnoreCase("cnt")) {

        hours = ((Number) hoursField.getValue()).intValue();
        minutes = Integer.parseInt(timeList.getSelectedItem().toString());

        // \d mean every digit charater
        Pattern p = Pattern.compile("\\d");
        Matcher m = p.matcher(hoursField.getValue().toString());
        if (m.matches()) {
            System.out.println("Hours: " + hours);
            System.out.println("Minutes: " + minutes);
        } else {
            hoursField.setValue(0);
            JOptionPane.showMessageDialog(null, "Numbers only please.");
        }
        }
    }

} // end class
Run Code Online (Sandbox Code Playgroud)

--EDIT--
更新了ActionPerformed方法

Hov*_*els 7

你需要的组合框,在动作监听可见的ActionListener添加到能够调用它的方法,并提取其持有的价值的有效参考.目前,您的JComboBox在类的构造函数中声明,因此仅在构造函数中可见,而在其他位置不可见.要解决这个问题,组合框需要是一个类字段,这意味着它在类本身中声明,而不是某些方法或构造函数.

例如:

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

public class Foo002 extends JPanel implements ActionListener {

   JComboBox combo1 = new JComboBox(new String[]{"Fe", "Fi", "Fo", "Fum"});
   public Foo002() {

      JComboBox combo2 = new JComboBox(new String[]{"One", "Two", "Three", "Four"});
      JButton helloBtn = new JButton("Hello");

      helloBtn.addActionListener(this); // I really hate doing this!

      add(combo1);
      add(combo2);
      add(helloBtn);
   }

   private static void createAndShowGUI() {
      JFrame frame = new JFrame("FormattedTextFieldDemo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(new Foo002());
      frame.pack();
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            createAndShowGUI();
         }
      });
   }

   @Override
   public void actionPerformed(ActionEvent e) {
      // this works because combo1 is visible in this method 
      System.out.println(combo1.getSelectedItem().toString());

      // this doesn't work because combo2's scope is limited to 
      // the constructor and it isn't visible in this method.
      System.out.println(combo2.getSelectedItem().toString());
   }

}
Run Code Online (Sandbox Code Playgroud)