JTextArea ArrayList string data and JTextField input data not matching - java

so I am trying to have my program read a list of lines from a txt file. This is then displayed in a JTextArea. The user can input data using the JTextField and the goal is to display "Hooray" if the user matches the text in the JArea and "Wrong!" if they do not. Any help is appreciated.
public class TextArea1 {
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public ArrayList aList;
public String correctAnswer;
public static void main(String[] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
textField.addActionListener(new startTextFieldListener("correct answer"));
JButton startButton = new JButton("Start!");
startButton.addActionListener(new startButtonListener(aList));
text = new JTextArea(30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
startButtonListener(ArrayList passedInList) {
aList = passedInList;
}
#Override
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
ArrayList aList = new ArrayList();
try {
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
}
} catch (IOException e) {
System.out.println(e);
}
int sz = aList.size();
for (int k = 0; k < sz; k++) {
String correctAnswer = aList.get(k).toString();
text.append(aList.get(k).toString());
text.append("\n");
}
}
}
class startTextFieldListener implements ActionListener {
String correctAnswer;
startTextFieldListener(String answer) {
correctAnswer = answer;
}
#Override
public void actionPerformed(ActionEvent event) {
if (text.getText().equals(correctAnswer)) {
JOptionPane.showMessageDialog(null, "Hooray!");
} else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}

Ok Try this one:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class TextArea1{
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public ArrayList aList;
public String correctAnswer;
public static void main (String [] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
JButton startButton = new JButton ("Start!");
startButton.addActionListener(new startButtonListener());
text = new JTextArea (30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
ArrayList <String>aList = new ArrayList<>();
try {
try (BufferedReader input = new BufferedReader (new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
aList.add(line);
}
}
} catch (IOException e) {
System.out.println(e);
}
int sz = aList.size();
boolean result=false;
for(String t:aList){
if (t.equalsIgnoreCase(textField.getText())) {
JOptionPane.showMessageDialog(null, "Hooray! Loading File contents....");
int count=0;
for (int k = 0; k< sz; k++) {
text.append(aList.get(k).toString());
System.out.println(count);
count++;
// if(k<sz-1)
// text.append(", ");
text.append("\n");
}
result=true;
break;
}
else {
result=false;
}
}
if(!result){
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}
In this it will look for you text enter in textfield and if it matches it will add entire file content line by line. i have already tested. But remember i am not having sufficient time so ,i have not done regex pattern matching it is simple equal comparison with one line in you text file with text entered in textbox exactly.

Well, I have just modified your code so that you will get proper message when value in contain in list. look and modify accordingly.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class TextArea1{
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public String correctAnswer;
public static void main (String [] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
//textField.addActionListener(new startTextFieldListener("correct answer"));
JButton startButton = new JButton ("Start!");
startButton.addActionListener(new startButtonListener());
text = new JTextArea (30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
startButtonListener()
{
}
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
ArrayList aList = new ArrayList();
try {
try (BufferedReader input = new BufferedReader (new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
aList.add(line);
}
System.out.println("List ready to check. values in list are :"+aList);
}
} catch (IOException e) {
System.out.println(e);
}
if (aList.contains(text.getText())) {
JOptionPane.showMessageDialog(null, "Hooray!");
}
else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}
if this is correct then mark it as correct.

Minor mistake you added a new line each time you append to the textArea.. that why its not comparing due to the extra new line
if you have new line in you file no problem the arrayList has it already when you parse the file so no need to add new line.
solution:
public class TextArea1{
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public String correctAnswer;
public static void main (String [] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
//textField.addActionListener(new startTextFieldListener("correct answer"));
JButton startButton = new JButton ("Start!");
startButton.addActionListener(new startButtonListener());
text = new JTextArea (30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
startButtonListener()
{
}
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
String string = "";
try {
try (BufferedReader input = new BufferedReader (new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
string += line;
//aList.add(line);
}
System.out.println("List ready to check. values in list are :"+aList);
}
} catch (IOException e) {
System.out.println(e);
}
if (string.equals(textField.getText())) {
JOptionPane.showMessageDialog(null, "Hooray!");
}
else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}

Related

I'm getting Nullpointer exception for JTabbed pane index after execution [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am getting an error when im trying to write a code to automatically select a tab from tabbed pane when condition is true, but im getting an error with null pointer exception in while im trying to execute the code after compiling it!!
The problem is in the loadData(); method on setSelectedTab();
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
public class GUI extends JFrame implements ActionListener{
private static final long serialVersionUID = 1;
ArrayList<Ship> shiplist= new ArrayList<Ship>();
private int shipcount = 0;
private int index = 0;
private Ship shipob;
private JTextField ShipYear;
private JTextField ShipName;
private JTextField CrewSize;
private JTextField ShipType;
private JTextField NoOfPass;
private JTextField NoOfCabins;
private JTextField PerFull;
private JTextField CabinRate;
private JTextField SizeCat;
private JTextField PerFilled;
private JTextField LiquidType;
private JTextField Capacity;
private ObjectInputStream inStream;
private ObjectOutputStream outStream;
private JTabbedPane tab;
private CruiseShip cruiseShip;
private DryCargoShip dryShip;
private LiquidCargoShip liquidShip;
JLabel message=new JLabel();
public GUI()
{
setSize(2000,300);
setTitle("Ship Data");
Container content= getContentPane();
content.setBackground(Color.GRAY);
content.setLayout(new BorderLayout());
JMenuBar menu=new JMenuBar();
JMenuItem menue= new JMenuItem("Exit");
menue.addActionListener(this);
menu.add(menue);
setJMenuBar(menu);
this.addWindowListener(new WindowDestroyer());
JPanel panel1= new JPanel();
panel1.setBackground(Color.YELLOW);
panel1.setLayout(new GridLayout(2,2));
panel1.add(new JLabel("Ship Name:"));
ShipName= new JTextField(50);
panel1.add(ShipName);
panel1.add(new JLabel("Ship Year:"));
ShipYear= new JTextField(50);
panel1.add(ShipYear);
panel1.add(new JLabel("Crew Size:"));
CrewSize= new JTextField(50);
panel1.add(CrewSize);
panel1.add(new JLabel("Ship Type:"));
ShipType= new JTextField(50);
panel1.add(ShipType);
content.add(panel1, BorderLayout.NORTH);
JPanel panel2= new JPanel();
panel2.setLayout(new BorderLayout());
JPanel panel3= new JPanel();
panel3.setBackground(Color.CYAN);
panel3.setLayout(new FlowLayout());
JButton Button1= new JButton("Next");
Button1.addActionListener(this);
panel3.add(Button1);
JButton Button2= new JButton("Previous");
Button2.addActionListener(this);
panel3.add(Button2);
panel2.add(panel3,BorderLayout.WEST);
panel2.add(message,BorderLayout.EAST);
JTabbedPane tab=new JTabbedPane();
content.add(panel2, BorderLayout.SOUTH);
JPanel cs= new JPanel();
//JPanel z= new JPanel();
cs.setBackground(Color.ORANGE);
cs.setLayout(new GridLayout(2,2));
cs.add(new JLabel("No of Passenger: "));
NoOfPass= new JTextField(25);
cs.add(NoOfPass);
cs.add(new JLabel("No of Cabins: "));
NoOfCabins= new JTextField(25);
cs.add(NoOfCabins);
cs.add(new JLabel("Percentage Full: "));
PerFull= new JTextField(25);
cs.add(PerFull);
cs.add(new JLabel("Cabin Rate: "));
CabinRate= new JTextField(25);
cs.add(CabinRate);
tab.addTab("Cruise Ship", cs);
JPanel ds= new JPanel();
//JPanel x= new JPanel();
ds.setBackground(Color.ORANGE);
ds.setLayout(new GridLayout(1,2));
ds.add(new JLabel("Size Category : "));
SizeCat= new JTextField(25);
ds.add(SizeCat);
ds.add(new JLabel("Percentage Filled : "));
PerFilled= new JTextField(25);
ds.add(PerFilled);
tab.addTab("Dry Cargo Ship", ds);
JPanel ls= new JPanel();
//JPanel y= new JPanel();
ls.setBackground(Color.ORANGE);
ls.setLayout(new GridLayout(1,2));
ls.add(new JLabel("Liquid Type : "));
LiquidType= new JTextField(25);
ls.add(LiquidType);
ls.add(new JLabel("Capacity : "));
Capacity= new JTextField(25);
ls.add(Capacity);
tab.addTab("Liquid Cargo Ship", ls);
content.add(tab,BorderLayout.CENTER);
}
public static void main(String[] args)
{
GUI Gui = new GUI();
Gui.readData();
Gui.loadData();
Gui.index = 0;
Gui.met();
//Gui.shipcount= shiplist.size();
Gui.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Container container = getContentPane();
String string = e.getActionCommand();
if (string.equals("Next"))
{
nextShip();
}
else if (string.equals("Previous"))
{
previousShip();
}
else if (string.equals("Exit"))
{
writeData();
System.exit(0);
}
else
{
System.out.println("Error");
}
}
public void readData()
{
inStream=null;
try
{
inStream= new ObjectInputStream(new FileInputStream("shipdata.dat"));
try {
this.shipcount = 0;
do {
shiplist.add((Ship)inStream.readObject());
shipcount++;
} while (true);
}
catch (EOFException obj1)
{
System.out.println("Entered EOF");
}
catch (ClassNotFoundException obj2)
{
System.out.println("Class Error: " + obj2.getMessage());
}
this.inStream.close();
}
catch (FileNotFoundException obj3)
{
System.out.println("File Error: " + obj3.getMessage());
}
catch (IOException obj4)
{
System.out.println("IO Error in read file data: " + obj4.getMessage());
}
}
public void met()
{
shipcount= shiplist.size();
}
public void loadData() {
shipob = shiplist.get(index);
ShipName.setText(shipob.getShipName());
ShipYear.setText(shipob.getYear());
String a=""+shipob.getCrewSize();
CrewSize.setText(a);
ShipType.setText(shipob.getShipType());
if (shipob.getShipType().equals("Cruise Ship"))
{
System.out.println("In Cruise ship");
cruiseShip = (CruiseShip)shipob;
String b=""+cruiseShip.getCabinRate();
CabinRate.setText(b);
NoOfPass.setText(Integer.toString(cruiseShip.getNoOfPass()));
NoOfCabins.setText(Integer.toString(cruiseShip.getNoOfCabins()));
PerFull.setText(Double.toString(cruiseShip.getPerFull() * 100.0));
tab.setSelectedIndex(0); // ERROR IN SELECT INDEX - NULL POINTER EXCEPTION
}
else if (shipob.getShipType().equals("Dry Cargo Ship"))
{
System.out.println("In Dry ship");
dryShip = (DryCargoShip)shipob;
SizeCat.setText(dryShip.getSize());
String c=" "+dryShip.getPerFilled()*100.0;
PerFilled.setText(c);
try{
tab.setSelectedIndex(1);}
catch(Exception e){
System.out.println(e);
}
}
else if (shipob.getShipType().equals("Liquid Cargo Ship"))
{
System.out.println("In LC ship");
liquidShip = (LiquidCargoShip)shipob;
LiquidType.setText(liquidShip.getLiqType());
Capacity.setText(Integer.toString(liquidShip.getCapacity()));
tab.setSelectedIndex(2);
}
}
public void nextShip() {
if (index == shipcount - 1) {
message.setText("Already at last record ");
}
else {
message.setText("");
index++;
loadData();
}
}
public void previousShip() {
if (index == 0)
{
message.setText("Already at first record ");
}
else
{
message.setText("");
index--;
loadData();
}
}
public void writeData()
{
try {
outStream = new ObjectOutputStream(new FileOutputStream("shipdata.dat", false));
for (Ship ship : shiplist)
{
outStream.writeObject(ship);
}
outStream.flush();
outStream.close();
}
catch (IOException obj1) {
System.out.println("IO Error in writing the data: " + obj1.getMessage());
}
}
}
In the constructor you are initializing a local JTabbedPane and not the one that is declared in the class and accessed in the method loadData.
Please initialize the variable tab in a proper way, i.e.
this.tab=new JTabbedPane();
instead of
JTabbedPane tab=new JTabbedPane();

Java. Find couple of words or phrase from text file and display it

I've some kind of problem finding the words phrase while I enter it reverse/backwards. For example. I'm looking for a name and surname John Lovelock. The program finds the phrase and shows me it. While I enter Lovelock John it doesn't find me the match. How can I acquire this kind of fuction.
Heres what I've got :
public class Programa extends JFrame implements ActionListener {
private JTextArea text;
public static void main(String[] args) {
new Programa().setVisible(true);
}
public Programa() {
super("Redagavimas");
setSize(600, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
initialize();
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Paieska sarase");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Layout());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public void initialize(){
text = new JTextArea();
JScrollPane scroll = new JScrollPane(text);
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("Failas");
JMenuItem open = new JMenuItem("Atidaryti");
JMenuItem save = new JMenuItem("Issaugoti");
JMenuItem exit = new JMenuItem("Uzdaryti");
JMenuItem[] items = { open, save, exit};
for(JMenuItem item : items) {
item.addActionListener(this);
}
file.add(open);
file.add(save);
file.addSeparator();
file.add(exit);
bar.add(file);
add(scroll);
setJMenuBar(bar);
}
public class Layout extends JPanel {
private JTextField findText;
private JButton search;
private JTextArea text;
private JMenu menu;
private JMenuItem menuItem;
private JMenuItem exit;
private DefaultListModel<String> vieta;
private DefaultListModel<String> boob;
public Layout() {
setLayout(new BorderLayout());
JPanel boob = new JPanel(new GridBagLayout());
JPanel kvadratas = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
GridBagConstraints dbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
kvadratas.add(new JLabel("Rasti: "), gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
findText = new JTextField(20);
kvadratas.add(findText, gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 4;
search = new JButton("Ieskoti");
kvadratas.add(search, gbc);
text = new JTextArea();
JScrollPane scroll = new JScrollPane(text);
add(kvadratas, BorderLayout.NORTH);
vieta = new DefaultListModel<>();
JList list = new JList(vieta);
add(new JScrollPane(list));
ActionHandler handler = new ActionHandler();
search.addActionListener(handler);
findText.addActionListener(handler);
}
public class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
vieta.removeAllElements();
String searchText = findText.getText();
try (BufferedReader reader = new BufferedReader(new FileReader(new File("sarasas.txt")))) {
String text = null;
while ((text = reader.readLine()) != null) {
if (text.matches(searchText)) {
vieta.addElement(text);
}
}
} catch (IOException ee) {
ee.printStackTrace();
JOptionPane.showMessageDialog(Layout.this, "Nera failo", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
#Override
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Atidaryti")) {
open();
}else if(e.getActionCommand().equals("Issaugoti")) {
save();
} else if(e.getActionCommand().equals("Uzdaryti")) {
System.exit(0);
}
}
private void open(){
try{
BufferedReader atidarymas = new BufferedReader(new FileReader("sarasas.txt"));
String line;
while((line = atidarymas.readLine()) != null){
text.append(line + "\n");
}
atidarymas.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
private void save(){
try{
BufferedWriter irasymas = new BufferedWriter(new FileWriter("sarasas.txt"));
irasymas.write(text.getText());
irasymas.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
Maybe you should consider using this if (text.contains(searchText)) instead of this if (text.matches(searchText)) as this will allow you to search with only the name or surname. Also in order to search with changed order you should handle this in code. A dummy solution would be the following, of course there will be a better one:
public void actionPerformed(ActionEvent e) {
vieta.removeAllElements();
String searchText = findText.getText();
String[] words = searchText.split(" ");
StringBuilder sb = null;
if(words.length > 1) {
sb = new StringBuilder();
sb.append(words[1]).append(" ").append(words[0]);
}
try (BufferedReader reader = new BufferedReader(new FileReader(new File("sarasas.txt")))) {
String text = null;
while ((text = reader.readLine()) != null) {
if (text.contains(searchText) || (sb != null && text.contains(sb.toString()))) {
vieta.addElement(text);
}
}
} catch (IOException ee) {
ee.printStackTrace();
JOptionPane.showMessageDialog(Layout.this, "No file", "Error", JOptionPane.ERROR_MESSAGE);
}
}

Importing text into a JTable is not displaying

I have created a program where I can input data in JTextField and on hitting save button I use a JFileChooser to save the data in a .txt file where each JTextField is in a new line. I also created a button that pops up a JFileChooser to browse for that file and populate its corresponding cells.
I am new to GUIs, the code I wrote is not working. I tried different variations and cannot seem to get it. Can someone point me in the right direction please.
The input is
john
Doe
st. Jude
100
Here is the code
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import java.util.Scanner
import java.util.Vector;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.io.*;
//import javax.swing.filechooser;
import javax.swing.filechooser.FileFilter;
public class Charity
{
#SuppressWarnings("deprecation")
public static void main(String[] args)
{
JFrame frame = new JFrame("Learning Team Charity Program");
Container cp = frame.getContentPane();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Charities
final String[] charityArray = {"St.Jude", "CHOC", "Cancer Research", "AIDs Foundation", "Crohns Foundation"};
final JComboBox selector = new JComboBox(charityArray);
JPanel first = new JPanel();
first.setLayout(new FlowLayout());
first.add(selector);
// User input JLabels and JTextFields
JLabel nameLabel = new JLabel("First Name: ");
final JTextField name = new JTextField();
JLabel lastLabel = new JLabel("Last Name: ");
final JTextField lastname = new JTextField();
JLabel donationAmount = new JLabel("Donation Amount: ");
final JTextField donation = new JTextField();
JPanel second = new JPanel();
second.setLayout(new GridLayout(4,2));
second.add(nameLabel); second.add(name);
second.add(lastLabel); second.add(lastname);
second.add(donationAmount); second.add(donation);
// Donate & Exit Buttons
JButton donateButton = new JButton("Donate");
JButton saveButton = new JButton("Save");
JButton exitButton = new JButton("Exit");
JButton openButton= new JButton("Open File");
JPanel third = new JPanel();
third.setLayout(new FlowLayout());
third.add(donateButton);
third.add(saveButton);
third.add(openButton);
third.add(exitButton);
// JTable display
final DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("First Name");
model.addColumn("Last Name");
model.addColumn("Charity");
model.addColumn("Donation");
table.setShowHorizontalLines(true);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(true);
JScrollPane scrollPane = JTable.createScrollPaneForTable(table);
JPanel fourth = new JPanel();
fourth.setLayout(new BorderLayout());
fourth.add(scrollPane, BorderLayout.CENTER);
// Button Events
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(1);
}
});
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line;
while((line = br.readLine())!= null){
model.addRow(line.split(","));
}//end while
br.close();
}//end try
catch(Exception e2){
JOptionPane.showMessageDialog(null, "Buffer Reader Error");
}//end catch
}
}
private void setValueAt(String line, int row, int col) {
// TODO Auto-generated method stub
}
});
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser fileChooser = new JFileChooser();
int status = fileChooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text", ".txt", "txt"));
//fileChooser.setFileFilter(new FileFilter("txt"));
PrintWriter output;
try {
File file = fileChooser.getSelectedFile();
output = new PrintWriter(file +".txt");
for(int row = 0; row<table.getRowCount(); row++){
for(int col = 0; col<table.getColumnCount();col++){
output.println(table.getValueAt(row, col).toString());
}
output.println();
}
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
donateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat df = new DecimalFormat("##,###.00");
try
{
Object[] rows = new Object[]{name.getText(), lastname.getText(), selector.getSelectedItem(),
donation.getText()};
model.addRow(rows);
name.setText("");
lastname.setText("");
donation.setText("");
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Enter a Dollar Amount", "Alert", JOptionPane.ERROR_MESSAGE);
return;
}
}
});
// Frame Settings
frame.setSize(470,300);
//frame.setLocation(300,200);
cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
cp.add(first);
cp.add(second);
cp.add(third);
cp.add(fourth);
frame.setVisible(true);
}
}
I understand I have to pass a value in the parenthesis after the addRow.
People don't know what that means because the code you posted here doesn't have an addRow(...) method.
I see you posted a second question 2 hours later: https://stackoverflow.com/questions/30951407/how-to-properly-read-a-txt-file-into-a-a-row-of-a-jtable.
Keep all the comments in one place so people understand what is going on.
Also, posting a few random lines of code doesn't help us because we don't know the context of how the code is used. For example, I have no idea what how you created the "model" variable. I don't know if you ever added the model to the table.
Post a proper SSCCE when posting a question so we have the necessary information. The file chooser is irrelevant to the problem because we don't have access to your real file. So instead you need to post hard coded data. An easy way to do this is to use a StringReader.
Here is a working example that shows how to read/parse/load a file into a JTable:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.io.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
try
{
DefaultTableModel model = new DefaultTableModel(0, 4);
String data = "1 2 3 4\na b c d\none two three four";
BufferedReader br = new BufferedReader( new StringReader( data ) );
String line;
while ((line = br.readLine()) != null)
{
String[] split = line.split(" ");
model.addRow( split );
}
JTable table = new JTable(model);
add( new JScrollPane(table) );
}
catch (IOException e) { System.out.println(e); }
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
All you need to do is change the code to use a FileReader instead of the StringReader.
I figured it out. Thanks for all those that tried to help.
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
//BufferedReader br = new BufferedReader(new FileReader(myFile));
Scanner br = new Scanner(new FileReader(myFile));
String line;
while((line = br.nextLine())!= null){
Object[] myRow = new Object[]{line,br.nextLine(), br.nextLine(), br.nextLine()};
model.addRow(myRow);
// line = br.readLine();
if(br.nextLine()== " "){
line=br.nextLine();
}
}//end while
br.close();
}//end try
catch(Exception e2){
return;
}//end catch
}
}
});

java JFame will not work when started by actionPerformed

I have been googling an sherthing for an solution to this problem a lot but can't find any answer how to fix this. My problem is that when i start a new jframe from an actionevent from pressing a button the class white the JFrame opens but then the programs starts to freeze and the pop up windows stays blank.
Her is the cod i apologize if there is some bad programing or some words in swedish:
The start upp class:
import java.util.ArrayList;
public class maineClassen {
ArrayList<infoClass> Infon = new ArrayList<>();
public static void main (String [] args)
{
referenser referens = new referenser();
Startskärmen ss = new Startskärmen(referens);
}
}
The "startskärm" the first screen to com to:
public class Startskärmen extends JFrame implements ActionListener {
referenser referens;
ArrayList<infoClass> Infon;
JButton öppna = new JButton("open");
JButton ny = new JButton("create new");
JButton radera = new JButton("erase");
JScrollPane pane = new JScrollPane();
DefaultListModel mod = new DefaultListModel();
JList list = new JList(mod);
JScrollPane sp = new JScrollPane(list);
JLabel texten = new JLabel("pre-alpha 0.1");
public Startskärmen(referenser re)
{
//references should be sent by itself or received
referens = re;
Infon = referens.getInfoReferens();
//build up the window
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.LINE_AXIS));
labelPanel.setBorder(BorderFactory.createEmptyBorder(10,10,0,10));
labelPanel.add(texten);
JPanel scrollPanel = new JPanel();
scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.LINE_AXIS));
scrollPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
scrollPanel.add(sp);// man kan ocksä sätta in --> pane <--
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(öppna);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(ny);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(radera);
Container contentPane = getContentPane();
contentPane.add(labelPanel,BorderLayout.NORTH);
contentPane.add(scrollPanel, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.PAGE_END);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setSize(500, 500);
//adda action listener
ny.addActionListener(this);
öppna.addActionListener(this);
radera.addActionListener(this);
//skapaNyIC();
}
infoClass hh;
public void skapaNyIC()
{
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ny)
{
skapaNyIC();
}
else if(e.getSource() == öppna)
{
JOptionPane.showMessageDialog(texten,"This function doesn't exist yet");
}
else if(e.getSource() == radera)
{
JOptionPane.showMessageDialog(texten, "This function doesn't exist yet");
}
}
}
The class where the information will be stored and that creates the window (class) that will show the info:
public class infoClass {
ArrayList<infoClass> Infon;
private infoClass ic;
private String namn = "inget namn existerar";
private String infoOmInfo = null;
private int X_Rutor = 3;
private int Y_Rutor = 3;
private String[] information = new String[X_Rutor + Y_Rutor];
//info om dessa värden
public infoClass()
{
}
public void referenser(infoClass Tic)
{
ic = Tic;
infonGrafiskt ig = new infonGrafiskt(ic);
}
public void referenser(ArrayList<infoClass> Tic)
{
ic = Tic.get((Tic.size() - 1 ));
System.out.println("inna");
infonGrafiskt ig = new infonGrafiskt(ic);
ig.setVisible(true);
System.out.println("efter");
}
public String namnPåInfon()
{
return namn;
}
//namnen
public String getName()
{
return namn;
}
public void setNamn(String n)
{
namn = n;
}
//xkordinaterna
public int getX_Rutor()
{
return X_Rutor;
}
public void setX_Rutor(int n)
{
X_Rutor = n;
}
//y kordinaterna
public int getY_Rutor()
{
return Y_Rutor;
}
public void setY_Rutor(int n)
{
Y_Rutor = n;
}
//informationen
public String[] getInformationen()
{
return information;
}
public void setInformationen(String[] n)
{
information = n;
}
//infoOmInfo
public String getinfoOmInfo()
{
return infoOmInfo;
}
public void setinfoOmInfo(String n)
{
infoOmInfo = n;
}
}
The class that will show the info created by the window a bow:
public class infonGrafiskt extends JFrame implements ActionListener{
infoClass ic;
infonGrafiskt ig;
//tillrutnätet
JPanel panel = new JPanel(new SpringLayout());
boolean pausa = true;
//sakerna till desigen grund inställningar GI = grund inställningar
JButton GIklarKnapp = new JButton("Spara och gå vidare");
JTextField GInamn = new JTextField();
JLabel GINamnText = new JLabel("Namn:");
JTextField GIxRutor = new JTextField();
JLabel GIxRutorText = new JLabel("Antal rutor i X-led:");
JTextField GIyRutor = new JTextField();
JLabel GIyRutorText = new JLabel("Antal rutor i Y-led:");
JLabel GIInfo = new JLabel("Grund Inställningar");
// de olika framm:arna
JFrame GIframe = new JFrame("SpringGrid");
JFrame frame = new JFrame("SpringGrid");
//info om denna infon som finns här
JTextArea textArea = new JTextArea();
JScrollPane infoOmClasen = new JScrollPane(textArea); //hadde text area förut
JLabel infoRutan = new JLabel("Informatin om denna resuldatdatabank:");
//namnet på informationsdatabanken
JLabel namnetPåInfot = new JLabel("Namnet på denna resuldatdatabas.");
JButton ändraNamn = new JButton("Ändra namn");
JButton sparaAllt = new JButton("Spara allt");
public infonGrafiskt(infoClass Tic)
{
//få startinfo
namnOchRutor();
ic = Tic;
//skapar om rutan
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.PAGE_AXIS));
p1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
namnetPåInfot.setFont(new Font("Dialog",1,22));
p1.add(namnetPåInfot);
//pausa programet tills grundinställningarna är instälda
int m =1;
try {
while(m ==1)
{
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
//Create the panel and populate it. skapar den så alla kommer åt den
//JPanel panel = new JPanel(new SpringLayout());
for (int i = 0; i < ic.getX_Rutor()*ic.getY_Rutor(); i++) {
JTextField textField = new JTextField(Integer.toString(i));
panel.add(textField);
}
//Lay out the panel.
SpringUtilities.makeGrid(panel,
ic.getY_Rutor(), ic.getX_Rutor(), //rows, cols
5, 5, //initialX, initialY
5, 5);//xPad, yPad
//set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//p1.add(ändraNamn);
JPanel p2 = new JPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.PAGE_AXIS));
p2.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
p2.add(infoRutan);
infoOmClasen.setPreferredSize(new Dimension(0,100));
p2.add(infoOmClasen);
JPanel p3 = new JPanel();
p3.setLayout(new FlowLayout());
p3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
p3.setLayout(new BoxLayout(p3, BoxLayout.LINE_AXIS));
p3.add(ändraNamn);
p3.add(sparaAllt);
//Set up the content pane.
panel.setOpaque(true); //content panes must be opaque
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
frame.add(p1);
frame.add(p2);
frame.add(panel);//frame.setContentPane(panel);
frame.add(p3);
//Display the window.
frame.pack();
sparaAllt.addActionListener(this);
ändraNamn.addActionListener(this);
}
private void namnOchRutor()
{
System.out.println("inna 2");
//sättigång action listner
GIklarKnapp.addActionListener(this);
frame.setVisible(false);
//frameStart.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GIframe.setLayout(new BoxLayout(GIframe.getContentPane(), BoxLayout.PAGE_AXIS));
JPanel GIP0 = new JPanel();
GIP0.setLayout(new BoxLayout(GIP0,BoxLayout.LINE_AXIS));
GIP0.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP0.add(GIInfo);
GIInfo.setFont(new Font("Dialog",1,22));
JPanel GIP1 = new JPanel();
GIP1.setLayout(new BoxLayout(GIP1,BoxLayout.LINE_AXIS));
GIP1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP1.add(GINamnText);
GIP1.add(Box.createRigidArea(new Dimension(10, 0)));
GIP1.add(GInamn);
JPanel GIP2 = new JPanel();
GIP2.setLayout(new BoxLayout(GIP2,BoxLayout.LINE_AXIS));
GIP2.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP2.add(GIxRutorText);
GIP2.add(Box.createRigidArea(new Dimension(10, 0)));
GIP2.add(GIxRutor);
JPanel GIP3 = new JPanel();
GIP3.setLayout(new BoxLayout(GIP3,BoxLayout.LINE_AXIS));
GIP3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP3.add(GIyRutorText);
GIP3.add(Box.createRigidArea(new Dimension(10, 0)));
GIP3.add(GIyRutor);
JPanel GIP4 = new JPanel();
GIP4.setLayout(new BoxLayout(GIP4,BoxLayout.LINE_AXIS));
GIP4.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP4.add(GIklarKnapp);
System.out.println("inna 3");
//lägga till sakerna gurund instllnings framen
GIframe.add(GIP0);
GIframe.add(GIP1);
GIframe.add(GIP2);
GIframe.add(GIP3);
GIframe.add(GIP4);
//desigen
System.out.println("inna 4");
GIframe.pack();
GIframe.setVisible(true);
System.out.println("inna5");
}
/*public static void main (String [] args)
{
infoClass i = new infoClass();
infonGrafiskt ig = new infonGrafiskt(i);
}*/
public void referenserna( infonGrafiskt Tig)
{
ig = Tig;
}
private void skrivTillbaka()
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
((JTextField)children[i]).setText(tillfäligString[i]);
System.out.println(tillfäligString[i]);
}
}
namnetPåInfot.setText(ic.getName());
textArea.setText(ic.getinfoOmInfo());
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == GIklarKnapp)
{
//skicka x och y antal ett och så
ic.setNamn(GInamn.getText());
ic.setX_Rutor(Integer.parseInt(GIxRutor.getText()));
ic.setY_Rutor(Integer.parseInt( GIyRutor.getText()));
namnetPåInfot.setText(ic.getName());
pausa = false;
GIframe.setVisible(false);
frame.setVisible(true);
}
if(e.getSource() == sparaAllt)
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
tillfäligString[i] = ((JTextField)children[i]).getText();
System.out.println(tillfäligString[i]);
}
}
ic.setInformationen(tillfäligString);
ic.setNamn(namnetPåInfot.getText());
ic.setinfoOmInfo(textArea.getText());
}
if(e.getSource() == ändraNamn)
{
skrivTillbaka();
}
}
}
so my problem now is that i can't create a new "infoclass" that will show the info in the "infoGrafikst" class. with the code:
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
that am triggered by an button click.
Sorry for all the cod, but didn't know how to show my problem in another way.
Thanks a lot. I did find out that it was this code
int m =1;
try {
while(m ==1) {
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
that made it not work...
Well I haven't gone through your code may be beacuse I am too lazy to read pages of code.Well i think the new window you are creating must be interfering with EDT.
Well i have done a short example which may help you, and its smooth:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FrameLaunch {
void inti(){
final JFrame f=new JFrame();
final JFrame f2=new JFrame();
final JTextArea ja=new JTextArea();
JButton b =new JButton("press for a new JFrame");
f2.add(b);
f2.pack();
f2.setVisible(true);
b.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e) {
f2.setVisible(false);
f.setSize(200,200);
ja.setText("THIS IS NOT FROZEN");
f.add(ja);
f.setVisible(true);
f.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
});
}
public static void main(String[] args)
{
FrameLaunch frame = new FrameLaunch();
frame.inti();
}
}

Use a JComboBox to call information from an array?

How can I get a selection from a JComboBox to correlate to a number of array selections?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
class ContactsReader extends JFrame
{
public JPanel mainPanel;
public JPanel buttonPanel;
public JPanel displayPanel;
public JLabel titleLabel;
public JLabel nameLabel;
public JLabel ageLabel;
public JLabel emailLabel;
public JLabel cellPhoneLabel;
public JLabel comboBoxLabel;
public JButton exitButton;
public JTextField nameTextField;
public JTextField ageTextField;
public JTextField emailTextField;
public JTextField cellPhoneTextField;
public JComboBox<String> contactBox;
public String[] getContactNames;
public String[] displayContactNames;
public File contactFile;
public Scanner inputFile;
public String selection;
public ContactsReader()
{
super("Contacts Reader");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildPanel();
add(mainPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}
public void buildPanel()
{
titleLabel = new JLabel("Please enter contact information");
mainPanel = new JPanel(new BorderLayout());
buttonPanel();
displayPanel();
mainPanel.add(titleLabel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(displayPanel, BorderLayout.CENTER);
}
public void buttonPanel()
{
//create submit and exit buttons
exitButton = new JButton("Exit");
exitButton.addActionListener(new exitButtonListener());
buttonPanel = new JPanel(); //create button panel
buttonPanel.add(exitButton); //add exit button to panel
}
public void displayPanel()
{
String nameHolder;
int count = 0;
nameLabel = new JLabel("Name");
ageLabel = new JLabel("Age)");
emailLabel = new JLabel("Email");
cellPhoneLabel = new JLabel("Cell Phone #");
comboBoxLabel = new JLabel("Select a Conact");
nameTextField = new JTextField(10);
nameTextField.setEditable(false);
ageTextField = new JTextField(10);
ageTextField.setEditable(false);
emailTextField = new JTextField(10);
emailTextField.setEditable(false);
cellPhoneTextField = new JTextField(10);
cellPhoneTextField.setEditable(false);
try{
contactFile = new File("ContactData.txt");
inputFile = new Scanner(contactFile);
}
catch (Exception event){}
while (inputFile.hasNext())
{
nameHolder = inputFile.nextLine();
count++;
}
inputFile.close();
String getContactNames[] = new String[count];
String displayContactNames[] = new String[count/4];
try{
contactFile = new File("ContactData.txt");
inputFile = new Scanner(contactFile);
}
catch (Exception event){}
for (int i = 0; i < count; i++)
{
if (inputFile.hasNext())
{
nameHolder = inputFile.nextLine();
getContactNames[i] = nameHolder;
if (i % 4 == 0)
{
displayContactNames[i/4] = getContactNames[i];
}
}
}
inputFile.close();
contactBox = new JComboBox<String>(displayContactNames);
contactBox.setEditable(false);
contactBox.addActionListener(new contactBoxListener());
displayPanel = new JPanel(new GridLayout(10,1));
displayPanel.add(comboBoxLabel);
displayPanel.add(contactBox);
displayPanel.add(nameLabel);
displayPanel.add(nameTextField);
displayPanel.add(ageLabel);
displayPanel.add(ageTextField);
displayPanel.add(emailLabel);
displayPanel.add(emailTextField);
displayPanel.add(cellPhoneLabel);
displayPanel.add(cellPhoneTextField);
}
private class exitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0); //set exit button to exit even when pressed
}
}
private class contactBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//get selection from dropdown menu
selection = (String) contactBox.getSelectedItem();
}
}
public static void main(String[] args)
{
new ContactsReader(); //create instance of Contact Reader
}
}
I want the selection to send the name, age, email, and cell phone # to the corresponding text fields. I can figure out to get a selection but don't know how to make it choose the correct array selections and send it to the text fields.
Don't have the JComboBox hold just Strings, but rather have it hold objects of a custom class that contain all the information that you will need when it's selected. Then use the object selected to populate your JTextFields.
For instance, consider creating a class, say called Contact,
public class MyContact {
String name;
Date dateOfBirth; // in place of age
String email;
String cellPhone;
//...
}
And then create a JComboBox<MyContact>
When an item is selected, call the corresponding getXXX() getter method to extract the information to fill the JTextField. You will want to give the JComboBox a custom CellRenderer so that it displays the contacts nicely.
For example:
import java.awt.Component;
import java.awt.event.*;
import javax.swing.*;
public class MyComboEg extends JPanel {
private static final MyData[] data = {
new MyData("Monday", 1, false),
new MyData("Tuesday", 2, false),
new MyData("Wednesday", 3, false),
new MyData("Thursday", 4, false),
new MyData("Friday", 5, false),
new MyData("Saturday", 6, true),
new MyData("Sunday", 7, true),
};
private JComboBox<MyData> myCombo = new JComboBox<MyData>(data);
private JTextField textField = new JTextField(10);
private JTextField valueField = new JTextField(10);
private JTextField weekendField = new JTextField(10);
public MyComboEg() {
add(myCombo);
add(new JLabel("text:"));
add(textField);
add(new JLabel("value:"));
add(valueField);
add(new JLabel("weekend:"));
add(weekendField);
myCombo.setRenderer(new DefaultListCellRenderer(){
#Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
String text = value == null ? "" : ((MyData)value).getText();
return super.getListCellRendererComponent(list, text, index, isSelected,
cellHasFocus);
}
});
myCombo.setSelectedIndex(-1);
myCombo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// MyData myData = (MyData) myCombo.getSelectedItem();
MyData myData = myCombo.getSelectedItem();
textField.setText(myData.getText());
valueField.setText(String.valueOf(myData.getValue()));
weekendField.setText(String.valueOf(myData.isWeekend()));
}
});
}
private static void createAndShowGui() {
MyComboEg mainPanel = new MyComboEg();
JFrame frame = new JFrame("MyComboEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyData {
private String text;
private int value;
private boolean weekend;
MyData(String text, int value, boolean weekend) {
this.text = text;
this.value = value;
this.weekend = weekend;
}
public String getText() {
return text;
}
public int getValue() {
return value;
}
public boolean isWeekend() {
return weekend;
}
}

Categories

Resources