2013-11-08 4 views
0

У меня следующий код ниже. Моя цель - разрешить каждой кнопке добавлять в текстовое поле, чтобы пользователь мог ввести номер телефона. Единственное, что я не могу заставить работать, - это поле, позволяющее вводить несколько текстовых файлов. Как только вы нажмете на другую кнопку, она заменяет его в текстовом поле, так что присутствует только одна цифра за раз. Как я могу исправить это, чтобы каждая кнопка добавляла его число без полной замены? Кроме того, почему мой пограничный менеджер не обращается к коду? Спасибо!!Настройка текста с помощью кнопок

import javax.swing.BorderFactory; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JTabbedPane; 
public class Keys 
{ 

    private JPanel phone; 

    public static void main (String[] args) 
    { 

    JFrame frame = new JFrame ("Keys"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JPanel phone = new JPanel(); 
    phone.setBorder (BorderFactory.createRaisedBevelBorder()); 

    JTabbedPane tp = new JTabbedPane(); 
    tp.addTab ("KeyPad", new KeyPad()); 

    frame.getContentPane().add(phone); 
    frame.getContentPane().add(tp); 
    frame.pack(); 
    frame.pack();frame.setVisible(true); 

    } 
} 






import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 


public class KeyPad extends JPanel 
{ 
    private JLabel resultLabel; 


    private JButton button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonclear; 

    public KeyPad() 
    { 

     setLayout (new GridLayout (5, 3)); 

     resultLabel = new JLabel ("---"); 
     button0 = new JButton ("0"); 
     button1 = new JButton ("1"); 
     button2 = new JButton ("2"); 
     button3 = new JButton ("3"); 
     button4 = new JButton ("4"); 
     button5 = new JButton ("5"); 
     button6 = new JButton ("6"); 
     button7 = new JButton ("7"); 
     button8 = new JButton ("8"); 
     button9 = new JButton ("9"); 
     buttonclear = new JButton ("Clear"); 

     button0.addActionListener (new ButtonListener0()); 
     button1.addActionListener (new ButtonListener1()); 
     button2.addActionListener (new ButtonListener2()); 
     button3.addActionListener (new ButtonListener3()); 
     button4.addActionListener (new ButtonListener4()); 
     button5.addActionListener (new ButtonListener5()); 
     button6.addActionListener (new ButtonListener6()); 
     button7.addActionListener (new ButtonListener7()); 
     button8.addActionListener (new ButtonListener8()); 
     button9.addActionListener (new ButtonListener9()); 
     buttonclear.addActionListener(new ButtonListenerC()); 


     add (resultLabel); 
     add (button0); 
     add (button1); 
     add (button2); 
     add (button3); 
     add (button4); 
     add (button5); 
     add (button6); 
     add (button7); 
     add (button8); 
     add (button9); 
     add (buttonclear); 


     setPreferredSize (new Dimension(250,250)); 
     setBackground (Color.green); 
    } 





    private class ButtonListener0 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("0");   
     } 
    } 


    private class ButtonListener1 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("1");   
     } 
    } 

    private class ButtonListener2 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("2");   
     } 
    } 


    private class ButtonListener3 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("3");   
     } 
    } 

    private class ButtonListener4 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("4");   
     } 
    } 

    private class ButtonListener5 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("5");   
     } 
    } 



    private class ButtonListener6 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("6");   
     } 
    } 





    private class ButtonListener7 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("7");   
     } 
    } 






    private class ButtonListener8 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("8");   
     } 
    } 




    private class ButtonListener9 implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText ("9");   
     } 
    } 


    private class ButtonListenerC implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 


      resultLabel.setText (" ");   
     } 
    } 





} 

ответ

1

В каждом из вашего метода actionPerformed если должно быть:

resultLabel.setText (resultLabel.getText()+"theNumber"); 

Там, кажется, много копирования/вставки в код. Постарайтесь понять, можете ли вы сделать его более простым.

+0

Хорошо, я это делаю несколько номеров теперь используют: resultLabel.setText (resultLabel.getText() + «3»), я согласен, однако, как кажется, гораздо больше, чем это должно быть, я не». Мне нужны все эти слушатели для каждой кнопки? Я думал, что каждая кнопка нуждается в ее собственной? – Lou44

+0

@ Lou44 Да, вам нужны все эти слушатели для каждой кнопки, но вы можете сделать свой код более простым. Пусть это поможет: http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html –

1

Вы можете сцепить новый текст на старый текст, делая что-то вроде этого:

resultLabel.setText(resultLabel.getText() + "3"); 

Это возвращает текущий текст, а затем добавляет «3» до конца этого.

0

Прежде всего, вы должны иметь только один ButtonListener, так как каждый ButtonListener делает то же самое (кроме числа он должен добавить следующий код должен работать:.

private class ButtonListener implements ActionListener 
{ 
    private String value = ""; 

    public ButtonListner(String value) { 
     this.value = value; 
    } 

    public void actionPerformed (ActionEvent event) 
    { 
     resultLabel.setText(resultLabel.getText() + value);   
    } 
} 

Вы можете инициализировать Ваш ButtonListeners следующим образом:

button0.addActionListener(new ButtonListener("0")); 
Смежные вопросы