2013-04-02 5 views
1

내가 만들고자하는 프로그램에는 세 개의 텍스트 필드가 여러 버튼 (각 숫자를 나타내는)과 함께 표시됩니다. 키보드를 사용하지 않고 버튼을 클릭하여 입력 할 수있게하려고합니다.버튼을 사용하여 텍스트 필드에 입력하는 방법은 무엇입니까?

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

public class GUI extends JFrame { 

    private JButton[] numPad = new JButton[10]; 
    private JTextField totalBill = new JTextField(); 
    private JTextField totalPeople = new JTextField(); 
    private JTextField tipPercentage = new JTextField(); 
    private JTextField tipAmount = new JTextField(); 
    private JTextField grandTotal = new JTextField(); 
    private JTextField totalPerPerson = new JTextField(); 
    private JButton doneButton = new JButton("Done"); 
    private JButton clearButton = new JButton("Clear"); 
    //////////////////////////////////////////////////////////////////////// 
    private JPanel superContainer; 
    private JPanel container; 
    private JPanel panel1 = new JPanel(); 
    private JPanel panel2 = new JPanel(); 

    public GUI() { 

      //Set JFrame title. 
      super("Tip Calculator"); 

      superContainer = new JPanel(); 
      superContainer.setLayout(new BoxLayout(superContainer, BoxLayout.Y_AXIS)); 

    //Create a container to hold two GridLayouts beside one another. 
      container = new JPanel(); 
      container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS)); 

    //Create panels to be placed in container panel. 
      panel1.setPreferredSize(new Dimension(500, 250)); 
      panel1.setLayout(new GridLayout(4,3,10,10)); 
      panel2.setPreferredSize(new Dimension(500, 250)); 
      panel2.setLayout(new GridLayout(7,2,10,10)); 

      //Populate all the JButtons for the numPad. 
      for (int i=0; i<=9; i++) { 
       numPad[i] = new JButton(Integer.toString(i)); 
      } 

      //Place each numPad button on the first JPanel. 
      for (int i=1; i<=9; i++) { 
       panel1.add(numPad[i]); 
      } 
      panel1.add(numPad[0]); 

      //Populate second GridLayout. 
      panel2.add(new JLabel("Total Bill: ")); 
      panel2.add(totalBill); 
      panel2.add(new JLabel("Total People: ")); 
      panel2.add(totalPeople); 
      panel2.add(new JLabel("Total Percentage: ")); 
      panel2.add(tipPercentage); 
      panel2.add(doneButton); 
      panel2.add(clearButton); 
      panel2.add(new JLabel("Tip Amount: ")); 
      panel2.add(tipAmount); 
      panel2.add(new JLabel("Grand Total: ")); 
      panel2.add(grandTotal); 
      panel2.add(new JLabel("Total/Person: ")); 
      panel2.add(totalPerPerson); 
      grandTotal.setEditable(false); 
      tipAmount.setEditable(false); 
      totalPerPerson.setEditable(false); 


      //Add the first GridLayout panel to the container. 
      container.add(panel1); 
      //Create a space between the GridLayout panels. 
      container.add(Box.createRigidArea(new Dimension(30,0))); 
      //Add the second GridLayout panel to the container. 
      container.add(panel2); 

      //Same as above but with title ontop and container panel below. 
      superContainer.add(new JLabel("Title")); 
      superContainer.add(Box.createRigidArea(new Dimension(0,30))); 
      superContainer.add(container); 

      //The panel the JFrame uses. 
      this.setContentPane(superContainer); 

      TheHandler handler = new TheHandler(); 
      doneButton.addActionListener(handler); 
      clearButton.addActionListener(handler); 

    } 

    private class TheHandler implements ActionListener { 

      public void actionPerformed(ActionEvent e) { 

        if (e.getSource()==doneButton) { 
          tipAmount.setText(Double.toString(Double.parseDouble(totalBill.getText()) * (Double.parseDouble(tipPercentage.getText())/100))); 
          grandTotal.setText(Double.toString(Double.parseDouble(tipAmount.getText()) + Double.parseDouble(totalBill.getText()))); 
          totalPerPerson.setText(Double.toString(Double.parseDouble(grandTotal.getText())/Double.parseDouble(totalPeople.getText()))); } 
        else if (e.getSource()==clearButton) { 
          grandTotal.setText(""); 
          tipAmount.setText(""); 
          totalPerPerson.setText(""); 
          totalBill.setText("0"); 
          tipPercentage.setText("0"); 
          totalPeople.setText("1"); 
          totalBill.requestFocus(); 
          totalBill.selectAll(); } 

      } 


    } 

} 

인터넷을 검색 한 후, 나는 다음과 같은 코드를 건너 온 : 지금까지, 나는이 가지고있는 유일한 문제는

private class AddDigit extends TextAction { 
     private String digit; 

     public AddDigit(String digit) { 

      super(digit); 
      this.digit = digit; 

     } 

     public void actionPerformed(ActionEvent e) { 

      JTextComponent component = getFocusedComponent(); 
      component.replaceSelection(digit); 

     } 

    } 

, 내가 어떻게 (내가 찾은 코드를 사용하는 단서가 없다 두 번째 블록 인 코드).

Where I got the code from.

+1

그래서 사용자가 수동으로 필드에 값을 입력하는 대신 num pad를 "클릭"할 수 있습니까? 또는 숫자 패드를 키보드 숫자 패드와 같이 작동 시키려면 숫자를 입력하면 해당 단추가 트리거됩니까? – MadProgrammer

+0

@Reimeus 첫 번째 코드 블록이 제 코드입니다. 두 번째 블록이 첫 번째 블록과 어떻게 작동하는지 궁금합니다. – DTHCND

+0

@MadProgrammer 그래서 키보드를 사용하여 숫자판을 클릭 할 수 있습니다. – DTHCND

답변

3

는 "기대"하지 않으면 사용자가 버튼을 키보드를 사용하여 이동 한 후 나는 단순히 그들을 unfocusable 만들 것입니다. 이렇게하면 사용자가 버튼을 클릭 할 수 있지만 현재 활성 필드가 포커스를 잃지 않습니다. 사용자는 ...

enter image description here

import java.awt.BorderLayout; 
import java.awt.Component; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.KeyboardFocusManager; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.text.JTextComponent; 

public class TestNumPad { 

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

    public TestNumPad() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     public TestPane() { 
      setLayout(new GridBagLayout()); 
      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.gridwidth = GridBagConstraints.REMAINDER; 
      JTextField field = new JTextField(10); 
      add(field, gbc); 
      add(new NumPad(), gbc); 
      field.requestFocusInWindow(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 
    } 

    public class NumPad extends JPanel { 

     private ActionHandler actionHandler; 

     public NumPad() { 
      setLayout(new GridLayout(4, 3)); 
      actionHandler = new ActionHandler(); 
      for (int index = 1; index < 10; index++) { 
       add(createButton(index)); 
      } 
      add(new JPanel()); 
      add(createButton(0)); 
      add(new JPanel()); 
     } 

     protected JButton createButton(int index) { 
      JButton btn = new JButton(String.valueOf(index)); 
      btn.setFocusable(false); 
      btn.addActionListener(actionHandler); 
      return btn; 
     } 

     public class ActionHandler implements ActionListener { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       Object source = e.getSource(); 
       if (source instanceof JButton) { 
        JButton btn = (JButton) source; 
        try { 
         int value = Integer.parseInt(btn.getText().trim()); 
         Component comp = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); 
         if (comp instanceof JTextComponent) { 
          JTextComponent tc = (JTextComponent) comp; 
          tc.setText(tc.getText() + value); 
         } 
        } catch (Exception exp) { 
         exp.printStackTrace(); 
        } 
       } 
      } 
     } 
    } 
} 
+0

감사! 위대한 작품! – DTHCND

+0

""가짜 좋은 방법입니다;) – MadProgrammer

1
를 필드에 직접 입력하거나 숫자 키패드를 클릭 할 수 있습니다

당신이해야 할 일의 본질은에 있습니다 :
1. 것은 번호를 추가하는 방법을 만들 텍스트 상자의 끝으로
2. 메서드에 현재 버튼의 값을 전달하여 해당 메서드를 호출하는 이벤트 리스너를 각 버튼에 추가합니다. 예를 들어

:

// Method to Append Number to Textbox 
public void addNumberToTextBox(int currentVal) { 
    txtOutputBox.Value = txtOutputBox.Value + currentVal 
} 

// Initialize Some Buttons 
JButton btnOne = new JButton("1"); 
JButton btnTwo = new JButton("2"); 
JButton btnThree = new JButton("3"); 

// Add an ActionListener to the buttons 
ButtonHandler handler = new ButtonHandler(); 
btnOne.addActionListener(handler); 
btnTwo.addActionListener(handler); 
btnThree.addActionListener(handler); 

// Class to deal with when a button is pressed 
private class ButtonHandler implements ActionListener { 
    public void actionPerformed(ActionEvent e) { 
     // Converst the number to int 
     int num = Integer.parseInt(e.getSource().Value); 
     // Call the method 
     addNumberToTextBox(num);      
    } 
} 
1

내가 어떻게 당신은 액션에서 버튼을 생성 한 다음 GUI에 버튼을 추가

을 발견 코드를 사용하는 단서가 없다. 예 :

JButton one = new JButton(new AddDigit("1")); 

코드는 포커스가있는 마지막 텍스트 필드에 텍스트를 추가합니다.

관련 문제