I am trying to make a program that I enter first name and last name and so on and then being about to view that information again.
I am using Java and Jframes
i have setup my interface with JTextfileds and Jlabels and a button
i am trying to make an array of objects so each array number will contain (firstname, lastname , and so on) and then i am going to print it out into a Jlist. i want to make it so when i prees my button it will input everything in my Jtextinputs in the first array
but i don't know how to do the array with objects i have started one but i need help thanks
i know that i need to use
ArrayList<> mylist = new ArrayList<Data>();
Data myTask = new Data("imput", "input");
myList.add(myTask);
But I don't understand how I use it
Thanks
that is my data.java file
package components;
Import Java.Io.Serializable;
public class Data implements Serializable {
static final long serialVersionUID = 1;
String name;
String description;
public Task(String Fname, String Lname) {
this.name = Fname;
this.description = Lname;
}
public String getName() {
return this.name;
}
public String getDescription() {
Return this.description;
}
interface file
public class DataDemo extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
//Name Label and TextField
protected static JLabel LbName;
protected static JTextField txtInputName;
//Description Label and TextField
protected static JLabel LbDescription;
protected static JTextField txtInputDescription;
//Submit Button
static JButton btnSubmit;
#SuppressWarnings("unchecked")
public DataDemo() {
//Name Label and TextField
LbName = new JLabel("Name:");
txtInputName = new JTextField(200);
//Description Label and TextField
LbDescription = new JLabel("Description:");
txtInputDescription = new JTextField(20);
//Submit Button
btnSubmit = new JButton("Done");
btnSubmit.addActionListener(this);
//Add Components to this container, using the default FlowLayout.
setLayout(null);
//Name
add(LbName);
add(txtInputName);
//Description
add(LbDescription);
add(txtInputDescription);
//button Submit
add(btnSubmit);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == btnSubmit)
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("DataDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
DataDemo newContentPane = new DataDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
//(x,y,with,height)
//Name interface position
LbName.setBounds(50, 70, 200, 25);
txtInputName.setBounds(200, 70, 200, 25);
//Description interface position
LbDescription.setBounds(50, 100, 200, 25);
txtInputDescription.setBounds(200, 100, 200, 25);
//button Submit
btnSubmit.setBounds(200, 150, 200, 25);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Did you try using
ArrayList<Data> mylist = new ArrayList<Data>();
That should allow you to create a proper Iterator and get your Data-Objects. Otherwise you will have to cast all Objects you retrieve from your list to Data, i.e.
ArrayList<> mylist = new ArrayList<>();
//add your Data-Objects here
for (Object o : mylist)
{
Data d = (Data) o;
//do something with d
}
Related
Please, how can I appear automatically some JTextField from what user choose in JComboBox ?
My example is simple. I have a JComboBox in my box with some operation. And depending on what the user choose from this JComboBox, I appear one or more JTextField.
I have this code:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CalculatriceFenetre fenetre = new CalculatriceFenetre();
fenetre.setVisible(true);
}
});
}
.
public class CalculatriceFenetre extends JFrame {
private JTextField field1, field2;
private JComboBox liste;
public CalculatriceFenetre() {
super();
build();
}
private void build() {
setTitle("Calculatrice");
setSize(400, 200);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(buildContentPane());
}
private JPanel buildContentPane() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(Color.white);
field1 = new JTextField();
field1.setColumns(10);
field2 = new JTextField();
field2.setColumns(10);
field2.setVisible(false);
panel.add(field1);
panel.add(field2);
liste = new JComboBox(new OperateursModel());
liste.addActionListener(new CustomActionListener());
panel.add(liste);
return panel;
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (liste.getSelectedItem().equals("op1")) {
field2.setVisible(true);
}
}
}
.
public class OperateursModel extends DefaultComboBoxModel {
private ArrayList<String> operateurs;
public OperateursModel(){
super();
operateurs = new ArrayList<String>();
operateurs.add("op1");
}
public String getSelectedOperateur(){
return (String)getSelectedItem();
}
#Override
public Object getElementAt(int index) {
return operateurs.get(index);
}
#Override
public int getSize() {
return operateurs.size();
}
#Override
public int getIndexOf(Object element) {
return operateurs.indexOf(element);
}
}
And depending on what the user choose from this JComboBox, I appear one or more JTextField.
Then you can write an ActionListener to handle the selection of an item from the combo box.
You can start by reading the section from the Swing tutorial on How to Use a Combo Box for a working example that uses an ActionListener.
In your case you want to add a text field to the frame so the code would be something like:
JTextField textField = new JTextField(10);
frame.add( textField );
frame.revalidate();
frame.repaint();
Also, there is no need for you to create a custom ComboBoxModel. You can just add items to the default model. Again, the tutorial will show you how to do this.
Like I mentioned, this is an easy approach for your question. Create all the JTextFields you need first and toggle its visibility instead of removing and adding it on run time.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DynamicTextFieldsApp
{
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("JTextField Toggler");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.add(new DisplayPanel());
f.pack();
f.setLocationRelativeTo(null);
}});
}
}
A simple JPanel with comboBox and several JTextFields.
class DisplayPanel extends JPanel
{
public static final int PLAYERS = 5;
private JComboBox cmbPlayerNumber;
private JTextField[] txtPlayerName;
private JLabel lblPlayerNumber;
public DisplayPanel(){
setPreferredSize(new Dimension(170, 240));
createComponents();
initComponents();
loadComponents();
setBoundsForComponents();
}
private void createComponents(){
cmbPlayerNumber = new JComboBox(new String[]{"1", "2", "3", "4", "5"});
txtPlayerName = new JTextField[PLAYERS];
lblPlayerNumber = new JLabel("Num of Players");
}
private void initComponents(){
for(int x=0; x<PLAYERS; x++){
txtPlayerName[x] = new JTextField("No Name " + (x+1));
txtPlayerName[x].setVisible(false);
}
cmbPlayerNumber.setSelectedIndex(-1);
cmbPlayerNumber.addActionListener(new CmbListener());
}
private void loadComponents(){
add(cmbPlayerNumber);
add(lblPlayerNumber);
for(int x=0; x<PLAYERS; x++)
add(txtPlayerName[x]);
}
private void setBoundsForComponents(){
setLayout(null);
lblPlayerNumber.setBounds(10, 0, 150, 30);
cmbPlayerNumber.setBounds(10, 30, 150, 30);
for(int x=0; x<PLAYERS; x++)
txtPlayerName[x].setBounds(10, (30*x)+70, 150, 30);
}
private class CmbListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int numOfPlayers = cmbPlayerNumber.getSelectedIndex() + 1;
for(int x=0; x<numOfPlayers; x++)
txtPlayerName[x].setVisible(true);
for(int x=numOfPlayers; x<PLAYERS; x++){
txtPlayerName[x].setVisible(false);
txtPlayerName[x].setText("No name " + (x+1));
}
}
}
}
And of course, you can work with some layout manager instead of null layout.
I'm trying to write a simple chatroom GUI using java, including a Jlist to show the online users. first a user chooses a display name so that the name will be displayed in the JList.
here is the code:
(the problem is only inside the createServer() method which sends Name as an argument to the handler constructor, in order to display it in the JList!)
public class GUI{
private JFrame frame;
private JButton btnSend, btnConnect;
private JTextArea txtChat;
private JTextField fldText, fldName;
private JList clientList;
private DefaultListModel listModel;
private JScrollPane sc, scClients;
private JPanel jpS2All, jpS2Client, jpS2Text;
private String Name;
class handler implements ActionListener, MouseListener{
private String Name = null;
void handler(String Name) {
this.Name = Name;
}
#Override
public void actionPerformed(ActionEvent e) {
chatroom();
}
#Override
public void mouseClicked(MouseEvent e) {
fldName.setText("");
listModel.addElement(Name);
}
}
public void creatServer() {
frame = new JFrame("login");
frame.setBounds(50, 50, 300, 200);
btnConnect = new JButton("connect");
frame.add(btnConnect, BorderLayout.EAST);
fldName = new JTextField("enter your name");
fldName.addMouseListener(new handler());
Name = fldName.getText();
btnConnect.addActionListener(new handler(Name));
frame.add(fldName, BorderLayout.CENTER);
frame.setVisible(true);
}
public void chatroom() {
frame = new JFrame("online friends");
frame.setBounds(100, 100, 400, 400);
jpS2All = new JPanel();
txtChat = new JTextArea();
txtChat.setRows(25);
txtChat.setColumns(25);
txtChat.setEditable(false);
sc = new JScrollPane(txtChat);
jpS2All.add(sc);
frame.add(jpS2All, BorderLayout.WEST);
////////////////////////
jpS2Text = new JPanel();
fldText = new JTextField();
fldText.setColumns(34);
fldText.setHorizontalAlignment(JTextField.RIGHT);
jpS2Text.add(fldText);
frame.add(jpS2Text, BorderLayout.SOUTH);
/////////
jpS2Client = new JPanel();
listModel = new DefaultListModel();
clientList = new JList(listModel);
clientList.setFixedCellHeight(14);
clientList.setFixedCellWidth(100);
scClients = new JScrollPane(clientList);
frame.add(jpS2Client.add(scClients), BorderLayout.EAST);
/////////
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
and finally in the main method:
public class Chat {
public static void main(String[] args) {
GUI gui = new GUI();
gui.creatServer();
}
}
This:
void handler(String Name) {
...
Should be
handler(String Name) {
...
To be a constructor, instead of a method. Also, you create a handler with two different parameter lists: empty, and the string. You need a constructor for both.
By the way, the code would be a lot easier to follow if it used the usual java naming conventions. Now they are inverted in a couple of places. Also, MouseListener has more methods that need to be implemented - consider extending MouseAdapter. Finally, you should create and access swing components only in the event dispatch thread.
Why would the order of Tabs in a JTabbedPane affect if the content of the tab works as expected?
I am writing my first advanced application and am having some trouble with my JTabbedPane.
Here's what I have:
public ProjectTracker() {
initialize();
newJobTab();
newUpdateTab();
newReportsTab();
}
newJobTab(), newUpdateTab() and newReportsTab() are placed into a JTabbed pane within the initialize() method. Each create an instance of a GUI class that I made. It basically has a bunch of Text fields, and comboboxes, etc. and they interact with a database to either populate the fields or collect info from the fields.
The functionality of the buttons on the tab are the main difference between the three. Individually, each tab works as I would expect it to. When I place them in the Tabbed pane, only the third tab works properly. If I switch around the order, it is the same deal. Whichever one is the third tab is the only one that functions the way I want.
Here is my revision to my original post...now with code.
public class SampleTracker {
private JFrame frmProjectTracker;
private JTabbedPane tabbedPane;
public String Title;
SampleTJV newJobPanel;
SampleTJV updatePanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleTracker window = new SampleTracker();
window.frmProjectTracker.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SampleTracker() {
initialize();
newJobTab();
newUpdateTab();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmProjectTracker = new JFrame();
frmProjectTracker.setBounds(100, 100, 662, 461);
frmProjectTracker.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmProjectTracker.getContentPane().setLayout(new FormLayout(new ColumnSpec[] {
ColumnSpec.decode("662px"),},
new RowSpec[] {
RowSpec.decode("50px"),
RowSpec.decode("389px"),}));
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frmProjectTracker.getContentPane().add(tabbedPane, "1, 2, fill, fill");
}
private void newJobTab(){
newJobPanel = new SampleTJV();
newJobPanel.UpdateButton.setText("Enter Job");
tabbedPane.addTab("Enter New Job", null, newJobPanel, null);
newJobPanel.UpdateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
newJobPanel.collectInfo();
Title = newJobPanel.Title;
//Here the connection to DB is made and the Title is written to DB
newJobPanel.newJobField.setText(Title);
}
});
}
private void newUpdateTab(){
updatePanel = new SampleTJV();
newJobPanel.UpdateButton.setText("Update Job");
tabbedPane.addTab("Update Job", null, updatePanel, null);
updatePanel.UpdateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
updatePanel.collectInfo();
Title = updatePanel.Title;
updatePanel.updateJobField.setText(Title);
}
});
}
}
public class SampleTJV extends JPanel {
private static final long serialVersionUID = 1L;
public static JTextField TitleField;
public String Title;
public JButton UpdateButton;
public JTextField newJobField;
public JTextField updateJobField;
/**
* Create the panel.
*/
public SampleTJV() {
setLayout(null);
TitleField = new JTextField();
TitleField.setColumns(10);
TitleField.setBounds(109, 6, 134, 28);
add(TitleField);
newJobField = new JTextField();
newJobField.setBounds(171, 79, 134, 28);
add(newJobField);
newJobField.setColumns(10);
UpdateButton = new JButton("Update Job");
UpdateButton.setBounds(267, 7, 112, 29);
add(UpdateButton);
JLabel lblNewJobResult = new JLabel("New Job Result");
lblNewJobResult.setBounds(47, 85, 112, 16);
add(lblNewJobResult);
JLabel lblUpdateJobResult = new JLabel("Update Job Result");
lblUpdateJobResult.setBounds(47, 125, 112, 16);
add(lblUpdateJobResult);
updateJobField = new JTextField();
updateJobField.setColumns(10);
updateJobField.setBounds(171, 119, 134, 28);
add(updateJobField);
}
public void collectInfo(){
Title = TitleField.getText();
}
}
The following is a copy error:
private void newUpdateTab(){
updatePanel = new SampleTJV();
newJobPanel.UpdateButton.setText("Update Job");
newJobPanel there is probably not intended.
Also wrong is a static GUI field:
static JTextField TitleField;
The problem was exactly what JB Nizet guessed earlier. It was static methods and variables which should have been instance variables.
In my sample code, SampleTJV, if you remove the word static from
public static JTextField TitleField;
the program works exactly as intended.
I am creating a GUI, and can't figure out how to store the JList user selections in an array. I tried List<<Sting>>, Object[] etc... JRadioButtons and other GUIs are fine, only JList is not working...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
private JTextField num3;
private JLabel label3;
private JButton button;
private JRadioButton radio2;
private JRadioButton radio3;
private ButtonGroup radioGroup;
private JList statesList;
String[] states = {"Alabama", "Alaska", "Wyoming"};
String expression;
String frequency;
// no args constructor
public Test() {
createUI();
}
private void createUI() {
Container contentPane = getContentPane();
contentPane.setLayout(null);
label3 = new JLabel();
label3.setText("Search Expression");
label3.setBounds(16, 120, 200, 21);
contentPane.add(label3);
num3 = new JTextField();
num3.setText("(any expression)");
num3.setBounds(16, 144, 150, 21);
num3.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(num3);
button = new JButton("Start!");
button.setBounds(90,430,126,24);
contentPane.add(button);
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event)
{
buttonActionPerformed(event);
}
}
);
// States Selection
statesList = new JList(states);
statesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
statesList.setVisibleRowCount(5);
statesList.setBounds(400, 16, 100, 50);
JScrollPane statesScroll = new JScrollPane(statesList);
statesScroll.setBounds(180, 16, 135, 400);
contentPane.add(statesScroll);
// Radio Buttons
radio2 = new JRadioButton();
radio3 = new JRadioButton();
radio3.setSelected(true);
radioGroup = new ButtonGroup();
radioGroup.add(radio2);
radioGroup.add(radio3);
radio2.setText("Quarterly");
radio3.setText("Yearly");
radio2.setBounds(16,360,90,23);
radio3.setBounds(16,385,75,23);
contentPane.add(radio2);
contentPane.add(radio3);
// set the content Pane window
setTitle("Search Engine");
setSize(750,500);
setVisible(true);
}
// Getting the user's TextField and JRadioButton input
private void buttonActionPerformed(ActionEvent event) {
expression = num3.getText();
if (radio2.isSelected())
frequency = "quarterly";
else frequency = "yearly";
System.out.println(expression+","+frequency);
// The above "expression" and "frequency" work fine. But JList does not
// work. What am I doing wrong? I tried Object[] instead of List<String>...
List<String> values = statesList.getSelectedValues();
return values==null ? null : values.toArray(new String[values.size()]);
}
// main thread
public static void main(String[] args) {
Test application = new Test();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This variant iterates the Object[] returned by getSelectedValues() to show expected values in the console. Next thing to fix is the layouts.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//public class Test extends JFrame {
public class Test {
private JTextField num3;
private JLabel label3;
private JButton button;
private JRadioButton radio2;
private JRadioButton radio3;
private ButtonGroup radioGroup;
private JList statesList;
String[] states = {"Alabama", "Alaska", "Wyoming"};
String expression;
String frequency;
// no args constructor
public Test() {
createUI();
}
private void createUI() {
JFrame f = new JFrame("Search Engine");
Container contentPane = f.getContentPane();
// This needs fixing NEXT!
contentPane.setLayout(null);
label3 = new JLabel();
label3.setText("Search Expression");
label3.setBounds(16, 120, 200, 21);
contentPane.add(label3);
num3 = new JTextField();
num3.setText("(any expression)");
num3.setBounds(16, 144, 150, 21);
num3.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(num3);
button = new JButton("Start!");
button.setBounds(90,430,126,24);
contentPane.add(button);
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
buttonActionPerformed(event);
}
});
// States Selection
statesList = new JList(states);
statesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
statesList.setVisibleRowCount(5);
statesList.setBounds(400, 16, 100, 50);
JScrollPane statesScroll = new JScrollPane(statesList);
statesScroll.setBounds(180, 16, 135, 400);
contentPane.add(statesScroll);
// Radio Buttons
radio2 = new JRadioButton();
radio3 = new JRadioButton();
radio3.setSelected(true);
radioGroup = new ButtonGroup();
radioGroup.add(radio2);
radioGroup.add(radio3);
radio2.setText("Quarterly");
radio3.setText("Yearly");
radio2.setBounds(16,360,90,23);
radio3.setBounds(16,385,75,23);
contentPane.add(radio2);
contentPane.add(radio3);
// set the content Pane window
f.setSize(750,500);
//f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setVisible(true);
}
// Getting the user's TextField and JRadioButton input
private void buttonActionPerformed(ActionEvent event) {
expression = num3.getText();
if (radio2.isSelected())
frequency = "quarterly";
else frequency = "yearly";
System.out.println(expression+","+frequency);
Object[] values = statesList.getSelectedValues();
for (Object state : values) {
System.out.println(state);
}
}
// main thread
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Test application = new Test();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Tips
Don't extend frame, just use an instance.
J2SE GUIs (Swing & AWT) should be created and updated on the EDT. See Concurrency in Swing - Initial Threads especially.
contentPane.setLayout(null); This will not work in the real world (read probably the next PC as 'the real world'). Use layout managers for a robust GUI. See Laying Out Components Within a Container for details, and also this nested layout example for grouping layouts according to need.
According to the documentation, getSelectedValues returns an object array.
Object[] values = statesList.getSelectedValues();
If you're positive they're all strings, you can just type cast them.
String[] values = (String[]) statesList.getSelectedValues();
Edit: Try this:
Object[] values = statesList.getSelectedValues();
String[] strings = new String[values.length];
for(int i = 0; i < values.length; i++) {
if(values[i] instanceof String) {
strings[i] = ((String) values[i]);
}
}
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;
}
}