Java Swing: Get text value from JOptionPane - java

I'd like to create a new window which is used in POS system. The user input is for an amount of money the customer has and the window has to display the exchange amount. I'm new with JOptionPane feature (I have been using JAVAFX and it's different).
This is my code:
public static void main(String[] argv) throws Exception {
String newline = System.getProperty("line.separator");
int cost = 100;
int amount = Integer.parseInt(JOptionPane.getText()) // this is wrong! This needs to come from user input box in the same window.
JFrame frame = new JFrame();
String message = "Enter the amount of money"+newline+"The exchange money is: "+amount-cost;
String text = JOptionPane.showInputDialog(frame, message);
if (text == null) {
// User clicked cancel
}
Is there any suggestion?

use InputDialog for get userinput
public static void main(String[] argv) throws Exception {
//JFrame frame = new JFrame();
//frame.setVisible(true);
int cost = 100;
JLabel l=new JLabel("The exchange money is");
JPanel p=new JPanel(new GridLayout(1, 2, 10, 10));
p.setPreferredSize(new Dimension(400, 50));
JTextField t=new JTextField("Enter the amount of money");
t.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
try{
int amount=Integer.parseInt(t.getText());
l.setText("The exchange money is: \n" + (amount - cost));
}catch(Exception ex){
// ex.printStackTrace();
}
}
});
p.add(t);
p.add(l);
int option = JOptionPane.showConfirmDialog(null,p,"JOptionPane Example : ",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(option==0){
System.out.println("ok clicked");
}else{
System.out.println("cancel clicked");
}
}

What you need to do, is to create your own custom JOptionPane, that has it's own components, instead of using the build in one's.
Place a JTextField in it, and add a DocumentListener to that, so that when you change something on it, it can be reciprocated on to the status label, as need be.
Try this small example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JOptionPaneExample {
private JLabel label;
private JTextField tfield;
private JLabel statusLabel;
private static final int GAP = 5;
private void displayGUI() {
JOptionPane.showMessageDialog(null, getPanel());
}
private JPanel getPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1));
label = new JLabel("Enter something: ", JLabel.CENTER);
tfield = new JTextField(10);
tfield.getDocument().addDocumentListener(new MyDocumentListener());
JPanel controlPanel = new JPanel();
controlPanel.add(label);
controlPanel.add(tfield);
panel.add(controlPanel);
statusLabel = new JLabel("", JLabel.CENTER);
panel.add(statusLabel);
return panel;
}
private class MyDocumentListener implements DocumentListener {
#Override
public void changedUpdate(DocumentEvent de) {
updateStatus();
}
#Override
public void insertUpdate(DocumentEvent de) {
updateStatus();
}
#Override
public void removeUpdate(DocumentEvent de) {
updateStatus();
}
private void updateStatus() {
statusLabel.setText(tfield.getText());
}
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new JOptionPaneExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}

Try using this:
if( myJOptionPane.getValue() instanceOf String){
String myString = (String) myJOptionPane.getValue();
}
Then use the result of myString to do whatever you intend to do.

Related

Receiving a string in Java graphics from a text box

I started to make a graphic for program I built in which to insert a name and length of a song, how do I do it in graphics? I found out how to pick up a button but I do not understand how to absorb something inserted into a text box
import java.awt.*;
import java.awt.event.*;
public class Active extends Frame {
public void init() {
ActionListener al = new MyActionListener();
TextField tf = new TextField(20);
Button b;
setLayout(new FlowLayout());
setSize(1000, 1000);
b = new Button ("first");
b.setActionCommand("First");
b.addActionListener(al);
add(b);
b = new Button ("Second");
b.setActionCommand("Second");
b.addActionListener(al);
add(b);
setVisible(true);
add(tf);
}
public Active(String caption) {
super(caption);
init();
}
public static void main(String[] args) {
Active m = new Active("Active buttons");
}
}
the main:
import java.awt.*;
import java.awt.event.*;
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if(s.equals("First")) {
System.out.println("The first button was switched");
}
if(s.equals("Second")) {
System.out.println("The second button was switched");
}
}
}
I would write it with the Swing GUI Toolkit. Here is a short example of that:
public class MyPanel extends JPanel
{
private JTextField songNameField;
private JTextField songLengthField;
private JButton assignBtn;
public MyPanel()
{
this.songNameField = new JTextField();
this.songLengthField = new JTextField();
this.assignBtn = new JButton("Assign");
this.assignBtn.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent event)
{
String name = songNameField.getText();
int length = Integer.parseInt(parsesongLengthField.getText());
...
}
});
this.add(songNameField);
this.add(songLengthField);
this.add(assignBtn);
}
}

Card Layout - Get Input from previous Card

I need a running order of pages 1-5 pages. I am using the card layout to navigate between each page after entering data on each page. The navigation to the next page works via an Action Listener on each text field.
My question is how do I pass the input from each card/page to the next? I can System.out.println each TextFeilds data. But I can't grab this information in the next card/action listener. The reason I need this to happen is I'd like to compare the strings of each page and also display a label of page 1's input on page/card2.
I apologize in advance for the massive block of code... Most of you will recognise most of this code anyway as it's copied from the CardLayout sample java code. I have just added two cards just now until I get the basics of passing variables back and fourth.
All help is appreciated even a small push the the right direction.
import java.awt.*;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Scanner;
import javax.swing.*;
public class CardLayoutDemo implements ItemListener {
JPanel cards; //a panel that uses CardLayout
final static String TEXTPANEL = "Card1 with text";
final static String TEXTPANEL2 = "Card with JTextField";
public void addComponentToPane(Container pane) {
//Put the JComboBox in a JPanel to get a nicer look.
JPanel comboBoxPane = new JPanel(); //use FlowLayout
String comboBoxItems[] = { TEXTPANEL, TEXTPANEL2};
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
//Create the "cards".
JPanel card1 = new JPanel();
JTextField jtf=new JTextField("", 40);
jtf.setSize(40, 10);
card1.add(jtf);
JLabel lab1 = new JLabel("Page1 Text", JLabel.LEFT);
card1.add(lab1 = new JLabel("Page1"));
JPanel card2 = new JPanel();
JTextField jtf2=new JTextField("", 40);
jtf2.setSize(40, 10);
card2.add(jtf2);
JLabel lab2 = new JLabel("Page2 Text", JLabel.LEFT);
card2.add(lab2 = new JLabel("Page2 "));
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, TEXTPANEL);
cards.add(card2, TEXTPANEL2);
pane.add(cards, BorderLayout.CENTER);
jtf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String getText1 = jtf.getText();
System.out.println("PAGE1 ");
System.out.println(getText1);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, TEXTPANEL2);
jtf2.requestFocus();
jtf2.requestFocusInWindow();
}
//JOptionPane.showMessageDialog(null,"Action Listener is working");
});
//PAGE2
jtf2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String getText2 = jtf2.getText();
System.out.println("PAGE2 ");
System.out.println(getText2);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, TEXTPANEL);
jtf.requestFocus();
jtf.requestFocusInWindow();
jtf.setText("");
}
});
}//ADD COMPONENT TO PANE
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
// String getLoginUser1 = jtf.getText();
//System.out.println(getLoginUser1);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(600, 300));
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the content pane.
CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Here is another view on the problem. You could create some kind of cards manager and hold all required info inside of it. Here is an example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class CardLayoutDemo implements ItemListener {
private static class QuizManager {
final java.util.List<String> quizData = new ArrayList<>();
final java.util.List<JPanel> cards = new ArrayList<>();
final JPanel rootView;
public QuizManager(JPanel root){
rootView = root;
}
private JPanel createQuizPanel(String pageText, final int index) {
JPanel card = new JPanel();
JTextField jtf=new JTextField("", 40);
jtf.setSize(40, 10);
JLabel prev = new JLabel("", JLabel.LEFT);
card.add(prev);
card.add(jtf);
card.add(new JLabel(pageText, JLabel.LEFT));
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
QuizManager.this.onCardSubmited(card, index, jtf.getText());
}
});
card.addComponentListener(new ComponentAdapter() {
#Override
public void componentShown(ComponentEvent e) {
super.componentShown(e);
jtf.requestFocus();
jtf.requestFocusInWindow();
String text = QuizManager.this.getPrevStringFor(index);
if (text != null) {
prev.setText(text);
}
}
});
return card;
}
private String getPrevStringFor(int index) {
if (index == 0) return null;
return quizData.get(index-1);
}
private String buildPanelName(int index) {
return String.format("card-%d", index);
}
public QuizManager addCard(String title) {
int index = cards.size();
quizData.add(null);//not set yet, just allocating
JPanel card = createQuizPanel(title, index);
cards.add(card);//this array looks like redundant
rootView.add(card, buildPanelName(index));
return this;
}
private void showCard(int index) {
CardLayout cl = (CardLayout) (rootView.getLayout());
cl.show(rootView, buildPanelName(index));
}
public void show() {
showCard(0);
}
public void onCardSubmited(JPanel card, int cardIndex, String text) {
System.out.println("page " + cardIndex);
System.out.println("text : " + text);
quizData.set(cardIndex, text);
if (cardIndex < cards.size() - 1) {
showCard(cardIndex + 1);
} else {
System.out.println("WE FINISHED");
//add finalazing code here
}
}
}
JPanel cardsRoot;
public void addComponentToPane(Container pane) {
cardsRoot = new JPanel(new CardLayout());
QuizManager manager = new QuizManager(cardsRoot)
.addCard("First page")
.addCard("Second page")
.addCard("Third card")
.addCard("Forth card");
pane.add(cardsRoot, BorderLayout.CENTER);
manager.show();
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cardsRoot.getLayout());
cl.show(cardsRoot, (String)evt.getItem());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(600, 300));
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the content pane.
CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Take a look how easy would be to create many of cards.
You've got the variable declaration of key components buried within the addComponentToPane(...) method, limiting their scope to this method only, preventing you from getting the information you need. While the canonical solution for this sort of problem is to use an model-view-controller or MVC type pattern so that the model (the underlying program logic and data) is extracted out of the view (the GUI), you can do a quick and dirty solution just by giving your variables private class scope.
For instance, if the JTextField was called textField and was held in a JPanel that acts as a "card", say called cardPanel, you could create a class that looked something like so:
public class CardPanel extends JPanel {
// constants to give the GUI a bigger size
private static final int PREF_W = 300;
private static final int PREF_H = 100;
// our key JTextField declared at class level
private JTextField textField = new JTextField(20);
// a JLabel to display the previous cardpanel's text
private JLabel label = new JLabel(" ");
// create the JPanel
public CardPanel(String name) {
setName(name);
setBorder(BorderFactory.createTitledBorder("Panel " + name));
JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
labelPanel.add(new JLabel("Prior Card's Word: "));
labelPanel.add(label);
setLayout(new BorderLayout());
add(textField, BorderLayout.PAGE_START);
add(labelPanel, BorderLayout.CENTER);
}
// have to jump through this hoop if we want to JTextField to
// have focus when a card is swapped
public void setFocusOnTextField() {
textField.requestFocusInWindow();
textField.selectAll();
}
// to make our GUI larger
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
// allow outside classes to add a listener to the JTextField
public void addActionListener(ActionListener listener) {
textField.addActionListener(listener);
}
// allow outside classes to get text from the text field
public String getTextFieldText() {
return textField.getText();
}
// allow outside classes to put text into the JLabel
public void setLabelText(String text) {
label.setText(text);
}
}
And then we could use it like so:
public class MyCardLayoutDemo extends JPanel {
private static final String[] NAMES = {"One", "Two", "Three", "Four"};
private Map<String, CardPanel> namePanelMap = new HashMap<>();
private CardLayout cardLayout = new CardLayout();
private int nameIndex = 0;
public MyCardLayoutDemo() {
setLayout(cardLayout);
MyListener listener = new MyListener();
for (String name : NAMES) {
CardPanel cardPanel = new CardPanel(name);
cardPanel.addActionListener(listener);
add(cardPanel, name);
namePanelMap.put(name, cardPanel);
}
}
private class MyListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// get the current CardPanel
String name = NAMES[nameIndex];
CardPanel currentCard = namePanelMap.get(name);
// advance the name index to get the next CardPanel
nameIndex++;
nameIndex %= NAMES.length;
name = NAMES[nameIndex];
CardPanel nextCard = namePanelMap.get(name);
// get text from current CardPanel
String text = currentCard.getTextFieldText();
nextCard.setLabelText(text); // and put it into next one
// swap cards
cardLayout.show(MyCardLayoutDemo.this, name);
nextCard.setFocusOnTextField();
}
}
private static void createAndShowGui() {
MyCardLayoutDemo mainPanel = new MyCardLayoutDemo();
JFrame frame = new JFrame("My CardLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Appear automatically JTextField

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.

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;
}
}

How can i pass the data from one JPanel to other...?

I have a JFrame which contains 3 JPanels. I want to pass the JTextField value of one panel to other. Each panel is shown using JTabbedPane. I am getting null when i access the value of other text field. How can i access?
You don't show any code, and so it's impossible to know why you're getting "null" values. Two possible solutions if you want all three JPanels to hold JTextFields with the same content:
Put the shared JTextField outside of the JPanels held by the JTabbedPane and instead in a JPanel that holds the JTabbedPane, so that the field is always visible no matter what tab is displayed, or
Use several JTextFields but have them share the same Document or "model".
e.g.,
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.text.PlainDocument;
public class SharedField extends JTabbedPane {
private static final int TAB_COUNT = 5;
private static final int MY_WIDTH = 600;
private static final int MY_HEIGHT = 300;
PlainDocument doc = new PlainDocument();
public SharedField() {
for (int i = 0; i < TAB_COUNT; i++) {
JTextField tField = new JTextField(10);
tField.setDocument(doc);
JPanel panel = new JPanel();
panel.add(tField);
add("Panel " + i, panel);
// to demonstrate some of the JTextFields acting like
// a label
if (i % 2 == 1) { // if i is odd
tField.setEditable(false);
tField.setBorder(null);
}
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(MY_WIDTH, MY_HEIGHT);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("SharedField");
frame.getContentPane().add(new SharedField());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Edit 1
I see that you've cross-posted this on java-forums.org/ where you show some of your code:
pacage Demotool;
Class:MainFrame
This is the actionPerformed code of first panel
both str and scrTxt is (public static)
public void actionPerformed(ActionEvent e)
{
String act=e.getActionCommand();
if(act.equals("ADD"))
{
str=scrnTxt.getText();
System.out.println("Hi :"+str);
Demotool.DemoTool.jtp.setSelectedIndex(1);
}
}
using the belove code i tried to access the data but I am getting null String:
System.out.println("Hello:"+Demotool.MainFrame.str);
Problems:
Don't use static variables or methods unless you have a good reason to do so. Here you don't.
You're may be trying to access the MainFrame.str variable before anything has been put into it, making it null, or you are creating a new MainFrame object in your second class, one that isn't displayed, and thus one whose str variable is empty or null -- hard to say.
Either way, this design is not good. You're better off showing us a small demo program that shows your problem with code that compiles and runs, an sscce, so we can play with and modify your code and better be able to show you a decent solution.
One such decent solution is to add a DocumentListener to the JTextField so that changes to the text held by the JTextField are "pushed" into the observers that are listening for changes (your other classes).
For example, using DocumentListeners:
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
public class SharedField2 extends JTabbedPane {
private static final int LABEL_PANEL_COUNT = 4;
private static final int MY_WIDTH = 600;
private static final int MY_HEIGHT = 300;
public SharedField2() {
TextFieldPanel tfPanel = new TextFieldPanel();
LabelPanel[] labelPanels = new LabelPanel[LABEL_PANEL_COUNT];
add("TextFieldPanel", tfPanel);
for (int i = 0; i < labelPanels.length; i++) {
labelPanels[i] = new LabelPanel();
// add each label panel's listener to the text field
tfPanel.addDocumentListenerToField(labelPanels[i].getDocumentListener());
add("Label Panel " + i, labelPanels[i]);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(MY_WIDTH, MY_HEIGHT);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("SharedField2");
frame.getContentPane().add(new SharedField2());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class TextFieldPanel extends JPanel {
private JTextField tField = new JTextField(10);
public TextFieldPanel() {
add(tField);
}
public void addDocumentListenerToField(DocumentListener listener) {
tField.getDocument().addDocumentListener(listener);
}
}
class LabelPanel extends JPanel {
private DocumentListener myListener;
private JLabel label = new JLabel();
public LabelPanel() {
add(label);
myListener = new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
try {
label.setText(e.getDocument().getText(0,
e.getDocument().getLength()));
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
};
}
public DocumentListener getDocumentListener() {
return myListener;
}
}
One simple solution will be making JTextField global so all panel can access it.
Make sure all your panel can access JTextField that is textField is globally accessible.
Following code demonstrate this:
JTextField textField = new JTextField(25);
JLabel labelForPanel2 = new JLabel(),labelForPanel3 = new JLabel();
private void panelDemo() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", panel1);
tabbedPane.addTab("Tab 2", panel2);
tabbedPane.addTab("Tab 3", panel3);
panel1.add(textField);
panel2.add(labelForPanel2);
panel3.add(labelForPanel3);
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
labelForPanel2.setText(textField.getText());
labelForPanel3.setText(textField.getText());
}
});
frame.add(tabbedPane);
frame.setVisible(true);
}
I don't know what exactly are you going to achieve, but maybe try data binding?
Take a look at BetterBeansBinding library.

Categories

Resources