This is my first time with Java. How do I clear the text in a textarea with button? My code for entering etc. is like this:
enter = new JButton("Enter");
enter.setActionCommand("enter");
enter.addActionListener(this);
delete = new JButton("Clear");
delete.setActionCommand("delete");
// delete.addActionListener(questionarea.setText(""));
//Create and set JPanels
topPanel = new JPanel();
deletePanel = new JPanel();
bottomPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 1));
bottomPanel.setLayout(new GridLayout(1, 3));
deletePanel.setLayout(new GridLayout(1, 3));
//Area for user input
questionarea = new JTextArea();
questionarea.setFont(new Font("Silom", Font.PLAIN, 50));
questionarea.setEditable(false);
//Adding components to panel
topPanel.add(questionarea, BorderLayout.CENTER);
bottomPanel.add(enter);
deletePanel.add(delete);
//Adding panels to JFrame
add(timerPanel);
add(bottomPanel);
add(deletePanel);
I used the textarea here where I enter numbers to answer a simple addition or subtraction question:
public void generateRandomProblem()
{
if(prob == 0)
{
opert = ' ';
Answer = A B;
}
else
{
opert = '-';
Answer = A - B;
}
String q = "" A " " opert " " B " = ";
questionarea.setText(q);
}
CodePudding user response:
You want to put setText("")
inside button listener...
delete = new JButton("Clear");
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
questionarea.setText("");
}
});