簡體   English   中英

JTextArea退格鍵和清除鍵

[英]JTextArea Backspace and Clear

我正在使用計算器GUI,需要編碼退格鍵和清除按鈕的幫助。

下面是代碼, names[0][3]是退格字符, names[0][4]是清除整個區域。

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

public class CalcGUI extends JFrame
{   
    private Container contents;
    private final JPanel entryPanel, buttonPanel;
    private final JTextArea entryTA;
    private final JButton equalJB;
    private JButton [][] buttons;
    private final String [][] names =
    {{"7", "8", "9", "\u2190", "C"},
     {"4", "5", "6", "+", "-"},
     {"1", "2", "3", "*", "/"},
     {"0", ".", "(", ")", "^"}};

    public CalcGUI()
    {
        super("Calculator");

        contents = getContentPane();
        contents.setLayout(new BorderLayout());

        buttons = new JButton [4][5];
        buttonPanel = new JPanel(new GridLayout(4, 5));

        ButtonHandler bh = new ButtonHandler();

        for (int i = 0; i < names.length; i++)
        {
            for (int j = 0; j < names[i].length; j++)
            {
                buttons[i][j] = new JButton(names[i][j]);
                buttons[i][j].addActionListener(bh);
                buttonPanel.add(buttons[i][j]);
            }
        }

        contents.add(buttonPanel, BorderLayout.CENTER);

        entryTA = new JTextArea(3, 1);
        entryTA.setLineWrap(true);
        entryPanel = new JPanel(new GridLayout(1, 1));
        entryPanel.add(entryTA); 
        contents.add(entryPanel, BorderLayout.NORTH);

        equalJB = new JButton("=");
        equalJB.addActionListener(bh);
        contents.add(equalJB, BorderLayout.SOUTH);

        setSize(300, 300);
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private class ButtonHandler implements ActionListener
    {
        @Override
        public void actionPerformed (ActionEvent ae)
        {  
            for (int i = 0; i < names.length; i++)
            {
                for (int j = 0; j < names[i].length; j++)
                {
                    if (ae.getSource() == buttons[i][j])
                    {
                        if (ae.getSource() != buttons[0][3]
                            && ae.getSource() != buttons[0][4]) 
                        {
                            entryTA.append(names[i][j]);
                        }
                    } 
                    //backspace
                    else if (ae.getSource() == buttons[0][3])
                    {
                        try 
                        {
                            Document doc = entryTA.getDocument();
                            if (doc.getLength() > 0)
                            {
                                doc.remove(doc.getLength() - 1, 1);
                            }
                        } 
                        catch (BadLocationException ble) 
                        {
                            ble.printStackTrace();
                        }
                    }
                    //clear - works, as per @Frostsoft's solution
                    else if (ae.getSource() == buttons[0][4])
                    {
                        entryTA.setText(""); 
                    }
                }
            }
        }
    }

    public static void main(String [] args)
    {
        CalcGUI calc = new CalcGUI();
    }
}

任何幫助或建議表示贊賞。 謝謝!

編輯:我認為問題是,它的退格直到doc.getLength > 0為假。 但是,刪除條件會導致引發異常。

Document doc = entryTA.getDocument();
if (doc.getLength() > 0)
{
    System.out.println(doc.getLength());
    doc.remove(doc.getLength() - 1, 1);
    System.out.println("removed");
}

對於輸入789 ,只按一次退格鍵JButton:

3
removed
2
removed
1
removed

Document#remove似乎只對我有用...

在這種情況下,我更喜歡使用Document#remove的原因是因為它不會創建一堆臨時String ,從而使效率更高,但是(速度稍快);)

退格

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class Test1 {

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

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

                final JTextArea ta = new JTextArea(10, 60);
                ta.setText("Bananas in pajamas are coming down the stairs,"
                                + "\n"
                                + "Bananas in pajamas are coming down in pairs,");

                JButton back = new JButton("Backspace");
                back.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            Document doc = ta.getDocument();
                            if (doc.getLength() > 0) {
                                doc.remove(doc.getLength() - 1, 1);
                            }
                        } catch (BadLocationException ex) {
                            ex.printStackTrace();
                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(ta));
                frame.add(back, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

考慮提供一個可運行的示例來演示您的問題。 這將減少混亂並改善響應

更新

問題出在你的循環中...

for (int i = 0; i < names.length; i++) {
    for (int j = 0; j < names[i].length; j++) {
        //...
        else if (ae.getSource() == buttons[0][3]) {
            try {
                Document doc = entryTA.getDocument();
                if (doc.getLength() > 0) {
                    doc.remove(doc.getLength() - 1, 1);
                }
            } catch (BadLocationException ble) {
                ble.printStackTrace();
            }
        } //clear - works, as per @Frostsoft's solution
        else if (ae.getSource() == buttons[0][4]) {
            entryTA.setText("");
        }
    }
}

在循環的每次迭代中,當按下退格按鈕時, else if (ae.getSource() == buttons[0][3]) {將為true ..., else if (ae.getSource() == buttons[0][4]) {當您按下清除按鈕時

相反,請從循環中刪除清除和退格檢查...

public void actionPerformed(ActionEvent ae) {
    for (int i = 0; i < names.length; i++) {
        for (int j = 0; j < names[i].length; j++) {
            if (ae.getSource() == buttons[i][j]) {
                if (ae.getSource() != buttons[0][3]
                                && ae.getSource() != buttons[0][4]) {
                    entryTA.append(names[i][j]);
                }
            }
        }
    }

    if (ae.getSource() == buttons[0][3]) {
        try {
            Document doc = entryTA.getDocument();
            if (doc.getLength() > 0) {
                doc.remove(doc.getLength() - 1, 1);
            }
        } catch (BadLocationException ble) {
            ble.printStackTrace();
        }
    } else if (ae.getSource() == buttons[0][4]) {
        entryTA.setText("");
    }

}

我會嘗試做entryTA.setText(""); 用於清除TextArea,然后使用entryTA.setText = (entryTA.getText()).substring(0, entryTA.getText().length()-1)刪除TextArea中的最后一個字符。 那只是我頭上的代碼,但它應該可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM