2012-02-26 3 views
3

私は休憩に費やされた時間を求めるGUIウィンドウを持っています。たとえば、「続行」ボタンをクリックすると、1:15 - int hours = 1およびint mins = 15になります。 JComboBoxとJButtonを一緒に使うことはできないので、私が得られる結果は時間も分もかかります(私は思っています)。また、ユーザーが番号を入力したのか、無効な入力を入力したのかを確認する方法もわかりません。フォーマットされたテキストフィールドとJComboBoxを合わせて

@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 

--EDIT--
更新actionPerformedメソッドあなたがたActionListenerができるようにするには、アクションリスナに表示されているコンボボックスへの有効な参照を必要とする

+0

あなたはあなたの質問をseparetlyする必要があります。 – Kiwy

+0

@Hurdler:私はちょうどあなたが望むものに自分のコードを改良しました。無効な入力を入力するとメッセージが表示されます。追加することはできません。整数を入力するだけです。今すぐコード:-) –

答えて

7

:ここでは、コードですそのメソッドを呼び出して、そのメソッドが保持している値を抽出します。現在、JComboBoxはクラスのコンストラクタで宣言されているため、コンストラクタでのみ表示され、その他の場所では表示されません。これを解決するには、コンボボックスがクラスフィールドである必要があります。つまり、クラス自体で宣言され、メソッドやコンストラクタではありません。例えば

最初:

try{ 
    Integer.parseInt(myString); 
catch(Exception e){ 
    System.out.print("not a number"); 
} 

秒:解析数のテストのために

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()); 
    } 

} 
+0

はい、私はポイントを参照してください、ありがとう。私が得ることができない唯一のものは、ボタンをクリックした後にComboBoxから値を印刷する方法です。値を選択した後、ボタンをクリックした後@ – Hurdler

+0

@Hurdler:コードを書いたのは2度です。JComboBoxに追加されたActionListenerから1回取得し、2度目にActionListenerはJButtonに追加されました。おそらくJComboBoxにActionListenerを追加したくないのでしょうか?あなたの割り当て要件の詳細がすべてわからないので、わかりません。 –

+0

私は別のアクションを聞くために、別々のActionListenersを用意する必要があると思いました。それは自分のためだから、どうやって行っても問題ありませんが、JButtonをクリックして両方の値を取得して渡すと意味があると思います。 – Hurdler

3

、次の2つのソリューションを持っていると私は、クリーンな方法は、正規表現を使用することだと思います。

// \d mean every digit charater you can find a full description [here][1] 
Pattern p = Pattern.compile("\\d"); 
Matcher m = p.matcher(myString); 
if(m.matches()){ 
    //it's a number 
}else{ 
    //it's not a number 
} 

regexpを強くしたい場合はを見てください。

良い夜&幸運

PS:グラフィックス要素beetween相互作用を作るとそこに問題はない、あなたは自分のグラフィカルオブジェクトの参照を維持する必要があります。

+0

この解決策では、1桁の数字のみを入力できます。しかし、さらに重要なことは、無効な入力を入力した場合は最後の有効な値を返し、 "2w2"を入力した場合は - たとえば - 2を返します。 – Hurdler

2

このスニペットを確認し、NumberFormatの情報を提供し、[続行]ボタンのクリックで時間を表示するコメントを追加しました。あなたが適用したい検査のタイプから、私は単純なJTextFieldでこれを行うためにJFormattedTextFieldを必要としませんでした。

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.event.*; 
import javax.swing.text.*; 
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 JComboBox timeList; 
    private JTextField hoursField; 

    public FormattedTextFields() 
    { 
     super(new BorderLayout()); 

     hoursLabel = new JLabel(hoursString); 
     minsLabel = new JLabel(minsString); 
     hoursField = new JTextField(); 
     //hoursField.setValue(new Integer(hours)); 
     hoursField.setColumns(10); 
     hoursLabel.setLabelFor(hoursField); 
     minsLabel.setLabelFor(minsLabel); 
     Document doc = hoursField.getDocument(); 
     if (doc instanceof AbstractDocument) 
     { 
      AbstractDocument abDoc = (AbstractDocument) doc; 
      abDoc.setDocumentFilter(new DocumentInputFilter()); 
     } 

     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" }; 

     /* 
     * Declared timeList as an Instance Variable, so that 
     * it can be accessed inside the actionPerformed(...) 
     * method. 
     */ 
     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) 
    { 

     String time = ""; 
     if (e.getActionCommand().equalsIgnoreCase("cnt")) 
     { 
      hours = Integer.parseInt(hoursField.getText()); 
      time = hours + " : " + ((String) timeList.getSelectedItem()); 
      System.out.println(time); 
     } 
    } 

    /* 
    * This class will check for any invalid input and present 
    * a Dialog Message to user, for entering appropriate input. 
    * you can let it make sound when user tries to enter the 
    * invalid input. Do see the beep() part for that inside 
    * the class's body. 
    */ 
    class DocumentInputFilter extends DocumentFilter 
    { 
     public void insertString(FilterBypass fb 
        , int offset, String text, AttributeSet as) throws BadLocationException 
     { 
      int len = text.length(); 
      if (len > 0) 
      { 
       /* Here you can place your other checks 
       * that you need to perform and do add 
       * the same checks for replace method 
       * as well. 
       */ 
       if (Character.isDigit(text.charAt(len - 1))) 
        super.insertString(fb, offset, text, as); 
       else 
       { 
        JOptionPane.showMessageDialog(null, "Please Enter a valid Integer Value." 
                  , "Invalid Input : ", JOptionPane.ERROR_MESSAGE); 
        Toolkit.getDefaultToolkit().beep(); 
       } 
      }            
     } 

     public void replace(FilterBypass fb, int offset 
          , int length, String text, AttributeSet as) throws BadLocationException 
     { 
      int len = text.length(); 
      if (len > 0) 
      { 
       if (Character.isDigit(text.charAt(len - 1))) 
        super.replace(fb, offset, length, text, as); 
       else 
       { 
        JOptionPane.showMessageDialog(null, "Please Enter a valid Integer Value." 
                  , "Invalid Input : ", JOptionPane.ERROR_MESSAGE); 
        Toolkit.getDefaultToolkit().beep(); 
       } 
      }            
     } 
    } 

} // end class 
+0

ありがとうございます。しかし、私は 'hoursFormat = NumberFormat.getIntegerInstance(); 'が提供するものを「より強く」チェックしたいと思います。たとえば、" 2w2 "と入力すると2を返します。' JOptionPane。数字以外の値を入力し、フィールドセットを0に戻した後、showMessageDialog(null、 "Numbers only please。");が直ちにトリガーされました。 – Hurdler

+0

@Hurdler:この新しいスニペットでは、表示され、エラーメッセージが表示され、数字以外を入力することはできません。 2を入力してwを入力した場合と同様に、wをタイプしたときにエラーメッセージが表示され、JTextFieldの中に2つだけ残されます。 –

+1

お手数をおかけしていただきありがとうございます。それは私が探していたものです。しかし、あなたがキウィー指摘したように、私は別々の投稿でこれらの質問をしていたはずです。今私は2つの答えを受け入れることができないからです...質問のタイトルと一貫性を持たせるためには、それにもかかわらず、あなたの助けは非常に高く評価されます。私はそれがあなたと大丈夫だと思います。もう一度ありがとう – Hurdler

関連する問題