I am trying to get some text displayed inside JTextField
, the text should be taken from an ArrayList
to which i add text using the addText
method. I also want to be able to cycle through the Strings in the ArrayList
using buttons.
Text
class
import java.util.ArrayList;
public class Text {
private String text;
public Text (String text)
{
this.text=text;
}
public String getText()
{
return text;
}
}
TextDisplay
class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class TextDisplay
{
private JFrame frame;
private JTextField text;
private JButton next;
private JButton back;
private ArrayList<Text> someText;
public TextDisplay ()
{
makeFrame();
someText= new ArrayList<Text>();
}
public void addText(String text)
{
Text sText = new Text(text);
someText.add(sText);
}
private void makeFrame()
{frame = new JFrame("text");
Container contentPane = frame.getContentPane();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 0));
text = new JTextField();
text.setEditable(false);
contentPane.add(text, BorderLayout.NORTH);
back = new JButton("back");
panel.add(back);
next = new JButton("next");
panel.add(next);
contentPane.add(panel,BorderLayout.WEST);
frame.pack();
frame.setVisible(true);
}
}
Can someone explain or show an example to me of how to achieve this?
First you need to add an ActionListener
to your button, then add the logic of getting the value from the ArrayList
.
For Example:
int index = -1;
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
index++;
text.setText(someText.get(index).getText());
}
});
Then you could add a variable index to get the next element in the ArrayList
and then update that variable when you get the element.