I have this program with a fairly modest goal: There's a text field, and a set of keywords. Everytime the user types in the text field, my TestListener triggers and if the text in the field matches one of the predefined keywords, a new button needs to appear in a GridLayout that I've set up below the text field.
However, my issue is that in the context of the program I've written, I can't tell how to add a button to my grid once a keyword is found. Specifically, please have a look at the createAndShowGUI method, and the "keywords" method.
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.text.*; public class RecognizeText extends JPanel implements TextListener { private TextField textField; public RecognizeText() { super(new BorderLayout()); textField = new TextField(30); textField.addTextListener(this); JPanel labelPane = new JPanel(new FlowLayout()); labelPane.add(textField); add(labelPane, BorderLayout.NORTH); } public void textValueChanged(TextEvent e) { String currentText = textField.getText().toString(); if (keywords(currentText)) { playSound(currentText + ".wav"); textField.setText(""); } } public static void createAndShowGUI() { JFrame frame = new JFrame("Austin's Program"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // This 5x5 panel will store the buttons I intend to add. JPanel wordPanel = new JPanel(new GridLayout(5,5)); frame.add(new RecognizeText(), BorderLayout.NORTH); frame.add(wordPanel, BorderLayout.SOUTH); frame.setSize(new Dimension(600,600)); frame.setVisible(true); } public boolean keywords(String toCheck) { if (toCheck.equals("one")) { //THIS IS WHERE I DONT KNOW WHAT TO PUT return true; } if (toCheck.equals("two")) { return true; } if (toCheck.equals("three")) { return true; } return false; } // You can ignore this method entirely. It's unrelated to the issue. public static void playSound(String filename) { new PlaySound("Sounds/" + filename).start(); } public static void main(String[] args) { createAndShowGUI(); } }
I'm also interested in being able to add Action listeners to these buttons, however I'm fairly confident I can work that part out myself once I learn how to do this!