JComboBox getSelectedItem - java

New to java and i am unable to see why my action listener is not working on the jcombobox. I think i have followed the other examples on the net to getSelectedItem, but nothing is happening.
FYI, my project is a unit converter (using MVC..hopefully, but that is not my priority).
Any assistance is greatly appreciated.
Thanks, Simon.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class UnitConverterView extends JFrame{
//variables and components
private static final long serialVersionUID = -4673040337179571462L;
private JComboBox<String> unitCategory;
private JTextField fromValue = new JTextField(7);
private JComboBox<String> convertFrom;
private JLabel equalsLabel = new JLabel(" = ");
private JTextField toValue = new JTextField(7);
private JComboBox<String> convertTo;
//constructor
UnitConverterView(){
//set up the view and components
JPanel unitPanel = new JPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600,300);
String[] categories = {"Length","Weight","Speed","Temperature"};
unitCategory = new JComboBox<>(categories);
String[] tofromValues = {" "};
convertFrom = new JComboBox<>(tofromValues);
convertTo = new JComboBox<>(tofromValues);
unitPanel.add(unitCategory);
unitPanel.add(fromValue);
unitPanel.add(convertFrom);
unitPanel.add(equalsLabel);
unitPanel.add(toValue);
unitPanel.add(convertTo);
this.add(unitPanel);
}
//get value to convert from
public int getMeasurement() {
return Integer.parseInt(fromValue.getText());
}
//listen for unitCategory to be selected
void addUnitCategoryListener(ActionListener listenForUnitCategory) {
unitCategory.addActionListener(listenForUnitCategory);
}
class UnitCatListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
/*String unitSelected = (String) unitCategory.getSelectedItem();
if (e.getSource() == unitCategory) {
String unitName = (String) unitCategory.getSelectedItem();
System.out.println("UnitName = " + unitName);
changeText(unitName);
}*/
JComboBox cb = (JComboBox)e.getSource();
String unitName = (String) cb.getSelectedItem();
System.out.println("UnitName = " + unitName);
}
void changeText(String name) {
toValue.setText(name);
}
}
}

You have declared a method addUnitCategoryListener() for registering listener to the combobox, but you never called this method. That's why the listener is never registered.
Add the below line at the end of your constructor, then you should be fine:
addUnitCategoryListener(new UnitCatListener());

To simply solve your problem, call the method you created to register the listener on the component. Add this to your constructor:
addUnitCategoryListener(new UnitCatListener());
However, there are a few things you'll want to know:
An ItemListener will usually do a better job than an ActionListener for a JComboBox. The previous one does not fire events if the user selects the already selected item (basically, does nothing). Usually there is nothing you need to do in these cases.
You don't need an extra method just to register the listener, you can directly add to your constructor the line
unitCategory.addActionListener(new UnitCatListener());
and remove your custom method.
The methods changeText and getMeasurement are never used.
Use parametrized types: instead of JComboBox use JComboBox<String>.
You don't need the equalsLabel as a field - a local variable will do - since you do not need to reference it anywhere later (unless you plan on changing a property of the label at runtime).

Related

How to pass JLabel to another class

I am trying to pass a simple string from a purchase class by throwing it in a getter, then trying to retrieve it from another class called pconfirm. Then trying to set the text of a label in that form to the amount being passed.
Purchase.java
private JLabel lblamnt;
public String amount() {
String gtext = lblamnt.getText();
return gtext;
}
Pconfirm.java
private JLabel lblgamnt;
public Pconfirm() {
Purchase purchase = new Purchase();
lblgamnt.setText("Test" + purchase.amount());
}
When i pass it it shows nothing.
I was under the presumption that you call it by Purchase.amount().
You need to have an actual object to use the method amount()
In your Purchase class constructor hopefully you give access to the JLabel or the ability to set the text like so
Purchase.java
public void setTextOfJLabel(String text)
{
lblamnt.setText(text);
}
Then you could do the following in
Pconfirm.java
private JLabel lblgamnt;
private Purchase purchObjName;
public Pconfirm() {
purchObjName = new Purchase();
purchObjName.setTextOfJLabel("The Purchase JLabel text");
lblgamnt.setText("Pconfirm JLabel text and " + purchObjName.amount());
}
Unless you explicitly set the text before calling amount your text of the JLabel will be null. You could also do something where every Purchase JLabel text is the same until changed by the user using the method I provided and you can set a default text like this
Purchase.java
private final String defaultJLabelText = "Purchase Default Text";
public Purchase()
{
lblamnt = new JLabel();
lblamnt.setText(defaultJLabelText);
}

How to get value from textfield and pass it to jtable in an another frame

my code and save button is this. I want to pass to another frames' jTable. but i get errors. can you figure it out?
It says:
Multiple markers at this line
- DefaultTableModel cannot be resolved to a type
- The static field Reservations.booked should be accessed in a static way
I already set it into public static but no changes occured.
btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Reservations re = new Reservations();
re.setVisible(true);
re.textField.setText(txtEvent.getText());
String d1 = txtEvent.getText();
String d2 = textReg.getText();
Object[] row = {d1, d2};
re.DefaultTableModel des = (DefaultTableModel)re.booked.getModel();
des.addRow(row);
}
Reservations re is not static . It should also declares as static variable if you want to use it as a static context

Passing data from one jframe to another jframe java

I have two JFrames.One Jframe has one Jtabel , when i selectedrow and press the JButton, second Jframe set string acd get text from jframe1
code in jframe1
int i = tblschdule.getSelectedRow() ;
String a = (String) tblschdule.getValueAt(i, 0) ;
String b = (String) tblschdule.getValueAt(i, 1) ;
Fisimonitoring form1 = new Fisimonitoring();
form1.acd=a;
form1.setVisible(true);
jframe2
public String acd;
code form1.acd=a; not work, String acd always null. how to solve it ?
your question is very incomplete bt here is an example to send data to another
frame
//a jframe
public class Aframe extends javax.swing.JFrame {
private Bframe bframe;
private void sendActionPerformed(java.awt.event.ActionEvent evt) {
if (bframe==null) {
bframe = new Bframe();
}
String text = jTable1.getValueAt(jTable1.getSelectedRow(),jTable1.getSelectedColumn()).toString();
bframe.setText(text);
bframe.setVisible(true);
}
}
//b jframe
public class Bframe extends javax.swing.JFrame {
public void setText(String text){
this.textField.setText(text);
}
}
in your case if you have already opened Bjframe you should make sure that same instance of Bjframe is shared by Ajframe.
It's quiet late for this answer but the solution for your problem is pretty simple.
You Need to send the value across the frame's.
Like if you are on jFrame1 and on click you are calling JFrame2
function actionPerformedOnButtonClick(){
String text = valueOfTheLabel;
new YourFrameName(text).setVisible(true);
}
And on JFrame2, You need to write a parameterized contructor like this..
public JFrame2(String textFromFrame1) {
initComponents();
}
And You can Access It on Frame2.

Getting data from an object in an ArrayList into GUI

I have an input file which has several fields separated by whitespace like this:
10 416-555-6666 Burgess 15
15 905-777-8888 Thomas 10
20 905-111-2222 Morris 5
I have a separate class file 'Record' which is related to the input file that has ID, telephone, Name, Years of Work.
In my main method, I've created an ArrayList of 'Record' objects called employeeList. The ArrayList is filled by a while loop that splits the read input file into their categories, defined by the Record constructor.
My next task is to create a GUI which can display and cycle through the input file, but I'm having trouble designing a way in which the 'Record' objects are being displayed in the Text fields. I've attached an image below to show what I'm trying to get:
example drawing
The next employee button would cycle to the next item on the ArrayList, being the next record object. I've attached my code below and would appreciate any suggestions on what to do next (making a GUI that displays the items ArrayList).
package javaapplication4;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
import javax.swing.*;
import java.awt.*;
public class App {
private JFrame f;
private JPanel p;
private JButton b1;
private JLabel lab;
private JTextArea empID;
private JTextArea telephone;
private JTextArea name;
private JTextArea yearsWorked;
public App() {
gui();
}
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("Emp.txt");
Scanner in = new Scanner(inputFile);
ArrayList<Record> employeeList = new ArrayList<Record>();
while(in.hasNextLine()) {
String line = in.nextLine();
String[] peopleInfo = line.split("\\s+");
int empId = Integer.parseInt(peopleInfo[0]);
String telephone = peopleInfo[1];
String name = peopleInfo[2];
int years_of_Work = Integer.parseInt(peopleInfo[3]);
employeeList.add(new Record(empId, telephone, name, years_of_Work));
}
new App();
}
public void gui() {
f = new JFrame("UpdateEmp");
f.setVisible(true);
f.setSize(600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p = new JPanel();
b1 = new JButton("Test");
lab = new JLabel();
empID = JTextField();
telephone = JTextField();
name = JTextField();
yearsWorked = new JTextField();
p.add(b1);
p.add(lab);
f.add(p);
}
}
You will need to move your list of records to the class that needs access to it (App) rather than being a local variable in the main method. You will also need an instance variable to record the index of the current record:
class App {
private final List<Record> records = new ArrayList<>();
private int currentRecord = 0;
...
}
I would suggest moving your logic for reading the records to a method of App so that you don't need to pass it around. Your main method should be very simple. Something like:
App app = new App();
app.readRecords();
app.showGui();
To show the records you will need methods to set the fields you've created as well as 'next' and 'previous' methods.
private void showRecord() {
assert currentRecord >= 0 && currentRecord < records.size();
Record record = records.get(currentRecord);
telephoneField.setText(record.getTelephone());
...
}
private void previous() {
if (currentRecord > 0) {
currentRecord--;
showRecord();
}
}
private void next() {
if (currentRecord < records.size() - 1) {
currentRecord++;
showRecord();
}
}

Problems with JComboBox

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class Test1{
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
Test1 b = new Test1();
}
public Test1(){
String degrees[] = {"AAS1","AAS2","AAS1","AAS3"};
JFrame frame = new JFrame("Creating a JComboBox Component");
JPanel panel = new JPanel();
combo = new JComboBox(degrees);
combo.setEditable(true);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
txt = new JTextField(10);
txt.setText("1");
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
txt.setText(String.valueOf(combo.getSelectedIndex()+1));
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
} }
As you see from the code above. I have JComboBox with 4 items. If there are no items that are same everything is OK.
But in my example ("AAS1","AAS2","AAS1","AAS3") first and third items are same, and I have problems in this case.
When I select any item I want to get it's index in JTextField, but when I select third item I get index of first item.
Has any idea?
That's because JComboBox is using equals to check the item equality. In your case, those two String are equal so it returns the first index that match. If you really need to do that, you might need to define your own item class like this:
private static class MyItem {
private String value;
public MyItem(String value) {
this.value = value;
}
public String getValue() {
return value;
}
#Override
public String toString() {
return value; //this is what display in the JComboBox
}
}
And then add the item like this:
MyItem degrees[] = {new MyItem("AAS1"),new MyItem("AAS2"),new MyItem("AAS1"),new MyItem("AAS3")};
JComboBox combo = new JComboBox(degrees);
Create a class like that:
class ComboItem{
private String name;
public ComboItem(String name){
this.name = name;
}
public String toString() {
return name;
}
}
and create your combobox:
comboBox = new JComboBox(new ComboItem[]{
new ComboItem("AAS1"),
new ComboItem("AAS2"),
new ComboItem("AAS1"),
new ComboItem("AAS3")
});
You have to separate how the equals is calculated on the Strings items and the effective representation. I think that this can be done just by creating a specific class for your purpose and use it instead that String.
Since this could be homework I'm not going to give exact result, just think about how the JComboBox internally chooses the index specified.
try using combo.getSelectedItem() instead. Since its two different strings in the String Array, you should be able to do a reference comparison and tell a difference between the two.

Categories