How to pass JLabel to another class - java

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

Related

how to create jTextField.checkEmpty()

I have a jTextField and I want to check whether or not its values are empty.
So far, I can do it this way:
public static JTextField checkEmpty(JTextField jTextField) {
if (jTextField.getText().equals(" ") || jTextField.getText().isEmpty()) {
return null;
} else {
return jTextField;
}
}
However, I want to do it in the manner seen below:
JTextField jTextField = new JTextField();
jTextField.checkEmpty();
This would work by returning a jTextField if it is not empty, and throw an exception or show showMessageDialog otherwise.
I'm not sure if this is possible, so any help would be appreciated.
With all that said, the actual idea is I want to create a validation class for a swing component in my project. If I can make this work then I can put it in my validation class.
Thank you.
You need to implement your own class that extend the JTextField class and add method you want.
First: you should extend JTextField like:
class MyJTextField extends JTextField
{
public MyJTextField( String defVal, int size )
{
super( defVal, size );
}
public MyJTextField()
{
super( "", size );
}
}
Second: you should add your checkEmpty() method, and you don't need the JTextField argument:
public MyJTextField checkEmpty() {
if (this.getText().equals("") ||
this.getText().isEmpty())
{
// throw your exception.
// print message or whatever you need
return null;
} else {
return this;
}
}
Then: you can use it like this:
MyJTextField jTextField = new MyJTextField();
jTextField.checkEmpty();

Display string method by pressing a button in GUI

How would I be able to display this method in a GUI, just by pressing a button in the GUI
private String questionFredricton(){
Object qFredricton = cities.get(1);
String displayFredricton = "Where is " + qFredricton + " located?";
String ansFredricton = provinces.get(1);
return displayFredricton + ansFredricton;
}
I'm guessing something like this??
nextQuestion is my button
private void nextQuestionActionPerformed(java.awt.event.ActionEvent evt) {
print(questionFredricton());
}
I don't want to use use setText() or append() in my button because my strings are being displayed in separate textAreas, already defined in my method. If I do use setText/appnd, it puts all the strings in one box, which is not what I want.
for example by doing:
outputTextQuestion.setText(questionFredricton());//not what I want
Thanks in advance!
I do not think I fully understand what your asking but you could return a custom object rather then a string in your method. The object would have getters and setters for each string value you want to use. Your actionPerformed method then could get the values you need and do whatever with them.
public class MyFredriction
private String display;
private String answer;
public MyFredriction(String display, String answer) {
this.display = display;
this.answer = answer;
}
//TODO public String getDisplay()
//TODO public String getAnswer()
}

JComboBox getSelectedItem

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).

How can I create a generic setter for JTextField?

I am able to expose a private JTextField by doing this:
public void setTextField(String value) {
someTF.setText(value);
}
It would be a lot of work if I have a lot of JTextFields. I tried doing this but failed. No error it's just not setting the right value on specified JTextField.
public class SomeView {
private JTextField someTF = new JTextField(10);
...
public void initComponents() {
...
}
public void setTextField(JTextField jTF, String value) {
jTF.setText(value);
}
}
public class SomeViewTable implements ...{
public void mousePressed(MouseEvent e) {
if (e.getSource() == someButton) {
JTextField someTF = new JTextField(10);
String value = "Some Value";
SomeView sv = new SomeView();
sv.initComponents();
sv.setTextField(someTF, value);
}
}
}
Im expecting this to happen in SomeView class when I called method sameTextField
someTF.setText("Some Value");
Is this possible, what rules in java am I breaking here?
In your listener, you are creating a local variable:
JTextField someTF = new JTextField(10);
...
sv.setTextField(someTF, value);
But what you want is to set the text field of SomeView. So remove the first line, and replace the second with:
sv.setTextField(sv.someTF, value);
Now, to answer the more global question of how to expose many private JTextFields through one method, one possibility could be to assign a string ID to each of them, and store them all in a HashMap:
Map<String,JTextField> map = new HashMap<String,JTextField>();
map.put("field 1", textField1);
...
map.put("field n", textFieldn);
public void setTextField(String id, String value) {
map.get(id).setText(value);
}
Or you could simply generate getters automatically for all your fields (most IDE do that painlessly)...

Java - Displaying contents of a HashMap using (Abstract)ListModel

I am designing a basic telephone directory for a project. It has three classes, Main (for the GUI), TelephoneDirectory (an object to store TelephoneRecords objects) and a TelephoneRecords class (where information for each record object is stored).
The requirements state: Extend your application by adding a list displaying the complete current contents of the telephone directory, ordered alphabetically by name. You will need to implement a ListModel. You may want to study class AbstractListModel before starting on your own implementation.
Only problem is, I have absolutely no idea how to extend my application to achieve this. I have searched online all night and haven't found a way to do this. I have tried storing the objects in an AbstractListModel rather than a HashMap but get errors. I don't exactly know what or why it is used and how I could use it. The next requirement (by the way) is to have the JList auto-update with new data when it's entered so I guess it has something to do with that?
Either way, if anyone could help it'd be great. My current working code for the previous that needs to be edited version is:
MAIN
public class Main extends JFrame implements ActionListener {
private static TelephoneDirectory directory = new TelephoneDirectory();
private JTextField nameField;
private JTextField numberField;
private JList contactList;
public Main() {
setTitle("Telephone Directory");
setLayout(new GridLayout(0,2));
JLabel nameLabel = new JLabel("Name of Contact:");
nameField = new JTextField(20);
add(nameLabel);
add(nameField);
JLabel numberLabel = new JLabel("Number of Contact:");
numberField = new JTextField(20);
add(numberLabel);
add(numberField);
JButton enterButton = new JButton("Enter");
JButton cancelButton = new JButton("Cancel");
enterButton.addActionListener(this);
cancelButton.addActionListener(this);
add(enterButton);
add(cancelButton);
JLabel contactsLabel = new JLabel("Current Contacts:");
contactList = new JList();
add(contactsLabel);
add(contactList);
setVisible(true);
pack();
}
public static void main(String[] args) {
new Main();
}
#Override
public void actionPerformed(ActionEvent arg0) {
JButton jb = (JButton) arg0.getSource();
if (jb.getText().equals("Cancel")) {
System.exit(0);
} else {
directory.addRecord(nameField.getText(), new TelephoneRecords(nameField.getText(), numberField.getText()));
System.out.println("Added record for " + nameField.getText() + ": number is " + numberField.getText() + ".");
}
}
}
TELEPHONEDIRECTORY
public class TelephoneDirectory implements Iterable<TelephoneRecords> {
private HashMap records;
public TelephoneDirectory() {
records = new HashMap<String, TelephoneRecords>();
}
public void addRecord(String name, TelephoneRecords newRecord) {
records.put(name, newRecord);
}
public TelephoneRecords getRecord(String name) {
return (TelephoneRecords) records.get(name);
}
public void getDirectory() {
System.out.println("Telephone Directory:");
records.values().iterator();
}
#Override
public Iterator<TelephoneRecords> iterator() {
return records.values().iterator();
}
}
TELEPHONERECORDS
public class TelephoneRecords {
private String name;
private String number;
public TelephoneRecords(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
#Override
public String toString() {
return "The phone number of " + name + " is " + number + ".";
}
}
You may be trying to do too much with inheritance. Rather than using an AbstractListModel in place of your HashMap, consider creating a class that extends AbstractListModel and that holds the TelephoneDirectory class with its HashMap as the nucleus of the AbstractListModel's data. This is called extending a class by composition rather than by inheritance.
Edit: Also consider using a TreeMap rather than a HashMap so as to be able to retrieve your names and telephone records in name order. You'll also need to give your TelephoneDirectory class a getElementAt(int index) and a getSize() method to allow it to be used within the AbstractListModel class.

Categories