Reputation: 11
i'm trying to get what's entered into the JTextField on button press, then store that in a string which I then use to update my JList. The only problem is that when I hit the button press nothing happens, yet the testing text I tried appeared perfectly fine. Anyone have any ideas? Cheers.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextField;
public class MainPanel {
JList list;
JTextField pushTextEntry;
Stack lifoStack = new Stack();
String pushTextListener;
Boolean b = false;
String a;
JComponent mainPanel(final JFrame newFrame) throws IOException {
////////////////////////////////////////////////////////////
final GridBagConstraints gbLayout = new GridBagConstraints();
final JComponent panel = new JLabel();
panel.setLayout(new GridBagLayout());
gbLayout.weightx = 1.0;
gbLayout.weighty = 1.0;
gbLayout.gridx = 1;
gbLayout.gridy = 1;
gbLayout.anchor = GridBagConstraints.SOUTHEAST;
gbLayout.insets = new Insets(15,15,215,45);
JButton Push = new JButton("Push");
panel.add(Push, gbLayout);
pushTextEntry = new JTextField(5);
gbLayout.insets = new Insets(15,15,215,120);
panel.add(pushTextEntry,gbLayout);
gbLayout.insets = new Insets(15,15,130,45);
JButton Pop = new JButton(" Pop ");
panel.add(Pop, gbLayout);
gbLayout.insets = new Insets(15,15,40,45);
JButton Reset = new JButton("Reset");
panel.add(Reset, gbLayout);
////////////////////////////////////////////////////////////
Push.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
for (int i = 1; i <= 10; i++)
{
pushTextListener = pushTextEntry.getText();
lifoStack.add(pushTextListener);
}
}
});
String listData[] = {
"test",
pushTextListener
};
list = new JList(listData);
gbLayout.insets = new Insets(60,15,160,140);
panel.add(list,gbLayout);
return panel;
}
}
Upvotes: 1
Views: 875
Reputation: 51323
You shoud use the DefaultListModel
to update the data. The ListModel
will notify the JList
when it changes and the JList
will update automatically.
final DefaultListModel listModel = new DefaultListModel();
listModel.addElement("test");
list = new JList(listModel);
Push.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 1; i <= 10; i++) {
pushTextListener = pushTextEntry.getText();
listModel.addElement(pushTextListener);
}
}
});
Upvotes: 2