Use a JComboBox to call information from an array? - java

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

Related

How to use single ActionListener for JCheckBox and JTextField

I am writing an eJuice Calculator. Its nowhere near finished as you will see below. My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
This is a rough draft of code.
package ejuicecalculatorv2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EJuiceCalculatorV2 extends JFrame {
//Form Controls
private JCheckBox isPGbasedNic_CB = new JCheckBox("PG Based NIC");
private JCheckBox isPGbasedFlavor_CB = new JCheckBox("PG Based Flavor");
private JCheckBox isVGbasedNic_CB = new JCheckBox("VG Based NIC");
private JCheckBox isVGbasedFlavor_CB = new JCheckBox("VG Based Flavor");
private JTextField batchSize_TF = new JTextField(5);
private JLabel batchSize_LB = new JLabel("Batch Size:");
private JTextField baseNicStrength_TF = new JTextField(5);
private JLabel baseNicStrength_LB = new JLabel("Base NIC Strength:");
private JTextField targetNicStrength_TF = new JTextField(5);
private JLabel targetNicStrength_LB = new JLabel("Target NIC Strength:");
private JTextField totalNic_TF = new JTextField(5);
private JLabel totalNic_LB = new JLabel("Total NIC:");
private JTextField flavorStrength_TF = new JTextField(5);
private JLabel flavorStrength_LB = new JLabel("Flavoring Strength:");
private JTextField totalFlavor_TF = new JTextField(5);
private JLabel totalFlavor_LB = new JLabel("Total Flavoring:");
private JTextField vgRatio_TF = new JTextField(5);
private JLabel vgRatio_LB = new JLabel("VG Ratio:");
private JTextField pgRatio_TF = new JTextField(5);
private JLabel pgRatio_LB = new JLabel("PG Ratio:");
private JTextField additionalVG_TF = new JTextField(5);
private JLabel additionalVG_LB = new JLabel("Additional VG:");
private JTextField additionalPG_TF = new JTextField(5);
private JLabel additionalPG_LB = new JLabel("Additional PG:");
private JTextField totalVG_TF = new JTextField(5);
private JLabel totalVG_LB = new JLabel("Total VG:");
private JTextField totalPG_TF = new JTextField(5);
private JLabel totalPG_LB = new JLabel("Total PG:");
private JTextField vgBasedIng_TF = new JTextField(5);
private JLabel vgBasedIng_LB = new JLabel("Total VG Ingredients:");
private JTextField pgBasedIng_TF = new JTextField(5);
private JLabel pgBasedIng_LB = new JLabel("Total PG Ingredients:");
//Variables
private boolean _PGnicFlag;
private boolean _VGnicFlag;
private boolean _PGflavorFlag;
private boolean _VGflavorFlag;
private double baseNic;
private double targetNic;
private double totalNic;
private double flavorStrength;
private double totalFlavor;
private double batchSize;
private double totalPG;
private double totalVG;
private double additionalVG;
private double additionalPG;
private double pgBasedIng;
private double vgBasedIng;
private double pgRatio;
private double vgRatio;
public EJuiceCalculatorV2() {
super("EJuice Calculator V2");
setLayout(new FlowLayout());
//Add CheckBoxes
add(isPGbasedNic_CB);
add(isPGbasedFlavor_CB);
add(isVGbasedNic_CB);
add(isVGbasedFlavor_CB);
//Add TextFields and Labels
add(batchSize_LB);
add(batchSize_TF);
add(vgRatio_LB);
add(vgRatio_TF);
add(pgRatio_LB);
add(pgRatio_TF);
add(baseNicStrength_LB);
add(baseNicStrength_TF);
add(targetNicStrength_LB);
add(targetNicStrength_TF);
add(flavorStrength_LB);
add(flavorStrength_TF);
//Add ActionListeners
ActionListener actionListener = new ActionHandler();
isPGbasedNic_CB.addActionListener(actionListener);
isPGbasedFlavor_CB.addActionListener(actionListener);
isVGbasedNic_CB.addActionListener(actionListener);
isVGbasedFlavor_CB.addActionListener(actionListener);
batchSize_TF.addActionListener(actionListener);
vgRatio_TF.addActionListener(actionListener);
pgRatio_TF.addActionListener(actionListener);
baseNicStrength_TF.addActionListener(actionListener);
targetNicStrength_TF.addActionListener(actionListener);
flavorStrength_TF.addActionListener(actionListener);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event){
//if event.getSource() == JCheckBox then execute the following code.
if(checkBox.isSelected()){
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = true;
_VGnicFlag = false;
checkBox = isVGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = true;
_PGnicFlag = false;
checkBox = isPGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = true;
_PGflavorFlag = false;
checkBox = isPGbasedFlavor_CB;
checkBox.setSelected(false);
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = true;
_VGflavorFlag = false;
checkBox = isVGbasedFlavor_CB;
checkBox.setSelected(false);
}
}
else{
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = false;
_VGnicFlag = true;
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = false;
_PGnicFlag = true;
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = false;
_PGflavorFlag = true;
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = false;
_VGflavorFlag = true;
}
}
}
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run (){
new EJuiceCalculatorV2().setVisible(true);
}
});
}
}
My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
You have a bunch of control components, but none appear ones that would initiate an action from the GUI. Rather all of them, the JCheckBoxes and the JTextFields are there to get input, and you appear to be missing one final component, such as a JButton. I would add this component to your GUi, and I would add a single ActionListener to it and it alone. And then when pressed, it would check the state of the check boxes and the text components and then based on their state, give the user the appropriate response.
Also some, if not most or all of the JTextFields, I'd change to either JComboBoxes or JSpinners, to limit the input that the user can enter to something that is allowable since you don't want the user entering "yes" into the "Batch Size" JTextField.
For example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.JSpinner.DefaultEditor;
#SuppressWarnings("serial")
public class JuiceTwo extends JPanel {
private static final String[] FLAVORS = {"Flavor 1", "Flavor 2", "Flavor 3", "Flavor 4"};
private static final Integer[] ALLOWABLE_BATCH_SIZES = {1, 2, 5, 10, 15, 20};
private static final String[] ALLOWABLE_VG_RATIOS = {"1/4", "1/3", "1/2", "1/1", "2/1", "3/1", "4/1", "8/1", "16/1"};
private List<JCheckBox> flavorBoxes = new ArrayList<>();
private JComboBox<Integer> batchSizeCombo;
private JSpinner vgRatioSpinner;
public JuiceTwo() {
// JPanel to hold the flavor JCheckBoxes
JPanel flavorPanel = new JPanel(new GridLayout(0, 1)); // hold them in vertical grid
flavorPanel.setBorder(BorderFactory.createTitledBorder("Flavors"));
for (String flavor : FLAVORS) {
JCheckBox flavorBox = new JCheckBox(flavor);
flavorBox.setActionCommand(flavor);
flavorPanel.add(flavorBox);
flavorBoxes.add(flavorBox);
}
batchSizeCombo = new JComboBox<>(ALLOWABLE_BATCH_SIZES);
SpinnerListModel vgRatioModel = new SpinnerListModel(ALLOWABLE_VG_RATIOS);
vgRatioSpinner = new JSpinner(vgRatioModel);
JComponent editor = vgRatioSpinner.getEditor();
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).getTextField().setColumns(4);
}
JButton getSelectionButton = new JButton("Get Selection");
getSelectionButton.setMnemonic(KeyEvent.VK_S);
getSelectionButton.addActionListener(new SelectionActionListener());
add(flavorPanel);
add(Box.createHorizontalStrut(20));
add(new JLabel("Batch Size:"));
add(batchSizeCombo);
add(Box.createHorizontalStrut(20));
add(new JLabel("VG Ratio:"));
add(vgRatioSpinner);
add(Box.createHorizontalStrut(20));
add(getSelectionButton);
}
private class SelectionActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox flavorBox : flavorBoxes) {
System.out.printf("%s selected: %b%n", flavorBox.getActionCommand(), flavorBox.isSelected());
}
System.out.println("Batch Size: " + batchSizeCombo.getSelectedItem());
System.out.println("VG Ration: " + vgRatioSpinner.getValue());
System.out.println();
}
}
private static void createAndShowGui() {
JuiceTwo mainPanel = new JuiceTwo();
JFrame frame = new JFrame("JuiceTwo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
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.

java GUI JLabel

I need a little help on java temperature conversion GUI
so here is my code for result
public class ResultsPanel extends JPanel
{
private JLabel result;
private JPanel panel;
final int WIDTH_CONST=120;
final int HEIGHT_CONST=60;
public ResultsPanel()
{
setPreferredSize(new Dimension(WIDTH_CONST, HEIGHT_CONST));
setBorder(BorderFactory.createTitledBorder("Result"));
result = new JLabel();
add(result);
}
public void setResultLabel(String str)
{
result.setText(str);
}
public void setResultLabel()
{
result.setText("");
}
}
so what I'm trying to do is, that when i click on the convert button i want to label the result
and here is my button handler class:
private class ConvertButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//calculate and convert temperatures
//convert the temperature into String
ResultsPanel result = new ResultsPanel();
String temp; // temperature in string
result.setResultLabel(temp);
}
}
but it doesn't seem like it's printing out the result,
any help appreciated, thanks
update :
here is my tempGUI class:
public class TempGUI extends JFrame
{
private BannerPanel banner;
private TypePanel type;
private TemperaturePanel temperature;
private ResultsPanel results;
private JPanel buttonPanel;
private JButton convert;
private JButton clear;
private JButton exit;
public TempGUI()
{
setTitle("Temperature Concverter GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
banner = new BannerPanel();
type = new TypePanel();
temperature = new TemperaturePanel();
results = new ResultsPanel();
buildButtonPanel();
add(banner, BorderLayout.NORTH);
add(type, BorderLayout.WEST);
add(temperature, BorderLayout.CENTER);
add(results, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public void buildButtonPanel()
{
buttonPanel = new JPanel();
convert = new JButton("Convert");
clear = new JButton("Clear");
exit = new JButton("Exit");
convert.addActionListener(new ConvertButtonHandler());
clear.addActionListener(new ClearButtonHandler());
exit.addActionListener(new ExitButtonHandler());
buttonPanel.add(convert);
buttonPanel.add(clear);
buttonPanel.add(exit);
}
private class ConvertButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
double celsius = 0, fahrenheit = 0;
DecimalFormat decimalFormatter = new DecimalFormat("0,00");
TypePanel type = new TypePanel();
TemperaturePanel temp = new TemperaturePanel();
ResultsPanel result = new ResultsPanel();
String temp1 = "Test";
result.setResultLabel(temp1);
add(result);
}
}
private class ClearButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
ResultsPanel results = new ResultsPanel();
results.setResultLabel();
TemperaturePanel temp = new TemperaturePanel();
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
You're creating the ResultsPanel but you're not adding it to any frame. Thus, the ResultsPanel is not displayed. You will have to create a frame for the ResultsPanel or add it to an existing frame like this yourFrame.add(result).

Java Swing: Get text value from JOptionPane

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.

Refreshing/updating JTable with setValueAt doesn't work correctly

I'm working on a project for my college and I need two of JFrame. The first one is the Main menu and the second one visible when JButton(Run) pressed.
I need to paint a memory in both of JFrame, So I used JTable to show the memory.
Memory class is:
public class Memory extends JPanel{
private JPanel panel;
private JTable table;
private String[] array;
private JScrollPane scrollpane;
public Memory()
{
array = new String[256]
this.addMemoryGUI();
}
public final JPanel addMemoryGUI()
{
this.panel = new JPanel();
this.panel.setPreferredSize(new Dimension(315,490));
this.panel.setLayout(null);
this.add(panel);
String info[][] = new String[256][2];
for(int j=0;j<256;j++)
{
info[j][0] = j;
info[j][1] = null;
}
String[] title = new String[]{"Address","Value"};
DefaultTableModel model = new DefaultTableModel(info,title);
table = new JTable(model){
#Override
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );
table.getColumnModel().getColumn(1).setCellRenderer( centerRenderer );
JTableHeader header = table.getTableHeader();
header.setBackground(Color.GRAY);
this.scrollpane = new JScrollPane(this.table);
this.scrollpane.setBounds(0, 0,315, 490);
this.panel.add(this.scrollpane);
return panel;
}
public void setAddrValue(int addr,String value)
{
Memory.this.array[addr] = value;
this.table.setValueAt(value,addr , 1);
}
public String getAddrValue(int addr)
{
return Memory.this.array[addr];
}
public String[] getMemory()
{
return Memory.this.array;
}
public void deleteValue(int i)
{
array[i]=null;
this.table.setValueAt(null, i, 1);
}
}
I add this JTable into my main JFrame and another JComponents:
public class MainGUI extends JFrame{
private JTextField field1;
private JTextField field2;
private JButton button1;
private JButton button2;
private Memory mem;
public MainGUI()
{
this.GraphicComponents();
}
public final void GraphicComponents()
{
this.setTitle("Machine");
this.setSize(800, 620);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.field1=new JTextField();
this.field1.setBounds(10,50,70,20);
this.add(field1);
this.field2=new JTextField();
this.field2.setBounds(90,50,70,20);
this.add(field2);
this.button1=new JButton("Write Value");
this.button1.setBounds(170,50,130,20);
this.button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
MainGUI.this.mem.setAddrValue(MainGUI.this.field1.getText().toString(),MainGUI.this.field2.getText().toString() );
}
});
this.add(button1);
this.button2 = new JButton("Run");
this.button2.setBounds(500,550,100,30);
this.button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
ExecutionGUI exe = new ExecutionGUI(mem);
exe.setVisible(true);
}
});
this.add(button2);
this.mem = new Memory();
this.mem.setBounds(450, 30, 315, 490);
this.add(mem);
}
}
Here in this code, setValueAt() method work perfect and there is no any problem.
but when I use same code of JTabel in the second JFrame when I press run JButton but create new JTable not that in the Memory class and insert value to the JTable using setValueAt(), JTabel doesn't update.
Code of the second JFrame:
public class ExecutionGUI extends JFrame {
private JTextField field1;
private JTextField field2;
private JButton button1;
private JScrollPane scrollpane;
private JButton button2;
private Memory mem;
private JTable table;
private static DefaultTableModel model;
private String info[][];
private String[] title;
private Memory mem;
public ExecutionGUI(Memory mem)
{
this.mem = mem;
this.GraphicComponents();
}
public final void GraphicComponents()
{
this.setTitle("Run");
this.setBounds(200, 100, 800, 600);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.info = new String[256][2];
for(int j=0;j<256;j++)
{
info[j][0] = j;
if(mem.getAddrValue(j)==null)
{
}
else
{
info[j][1] = mem.getAddrValue(j);
}
}
title = new String[]{"Address","Value"};
model = new DefaultTableModel(info,title);
table = new JTable(model){
#Override
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table1.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );
table1.getColumnModel().getColumn(1).setCellRenderer( centerRenderer );
JTableHeader header = table.getTableHeader();
header.setBackground(Color.GRAY);
this.scrollpane = new JScrollPane(table);
this.scrollpane.setBounds(610, 30,170, 470);
this.add(this.scrollpane);
this.field1=new JTextField();
this.field1.setBounds(10,50,70,20);
this.add(field1);
this.field2=new JTextField();
this.field2.setBounds(90,50,70,20);
this.add(field2);
this.button1=new JButton("Write Value");
this.button1.setBounds(170,50,130,20);
this.button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
table.setValueAt(MainGUI.this.field2.getText().toString(),MainGUI.this.field1.getText().toString(),1 );
}
});
this.add(button1);
}
so I have a problem only with the second JFrame and I can't refresh JTable with new data.
I have tried more than one way to take right result but there is nothing.
Thanks for your help.

Categories

Resources