Display Text field data using multiple frames - java

I am a noob to java and I have hit a snag building my gui...What I need to do is run my shipmentApp program which displays my EnterShipInfo frame that has several text fields to enter data and an enter button that when clicked passes the entered data to my ShipmentFrame. Initially when the frame pops up there should be three labels that just say "label" in them and a display button, then when you click the display button it the data from the text fields pops up in the three labels along with some other words to make a phrase.
// ShipmentFrame code begins here
private static final long serialVersionUID = 1L;
private Label headerLbl = null;
private Button displayButton = null;
private Button Exit = null;
private Label shipLbl = null;
private Label empLbl = null;
private Label dateTimeLbl = null;
private Shipment s;
private Shipment sf;
public ShipmentFrame(Shipment ship){
super();
this.s = ship;
initialize();
s = ship;
}
public void actionPerformed(ActionEvent e) {
shipLbl.setText("Shipment number " + s.getShipmentNum() +
" was received from " + s.getSupplierName());
empLbl.setText("By employee number " + s.getEmployeeNum());
dateTimeLbl.setText("On " + s.getRevDate() + " at " + s.getRevTime());
}
// this is my code from EnterShipInfo
private static final long serialVersionUID = 1L;
private Label headerLbl = null;
private Button displayButton = null;
private Button Exit = null;
private Label dateLbl = null;
private Label timeLbl = null;
private Label suplLbl = null;
private Shipment s;
private Label shipNumLbl = null;
private Label empNumLbl = null;
private TextField empNumTF = null;
private TextField shipNumTF = null;
private TextField dateTF = null;
private TextField timeTF = null;
private TextField supplTF = null;
Shipment ship = new Shipment (" ", " ", " ", " ", " ");
// #jve:decl-index=0:
public EnterShipInfo(){
super();
// this.s = ship;
initialize();
}
// This is the part that was wrong
public void actionPerformed(ActionEvent e) {
String employeeNum = empNumTF.getText();
String shipmentNum = shipNumTF.getText();
String revDate = dateTF.getText();
String revTime = timeTF.getText();
String supplierName = supplTF.getText();
ShipmentFrame sf = new ShipmentFrame(null);
}
//Below is what I was looking for...maybe someone knows more efficient way to accomplish this though
public void actionPerformed(ActionEvent e) {
ship.setEmployeeNum(empNumTF.getText());
ship.setShipmentNum( shipNumTF.getText());
ship.setRevDate( dateTF.getText());
ship.setRevTime(timeTF.getText());
ship.setSupplierName( supplTF.getText());
ShipmentFrame sf = new ShipmentFrame(ship);
}

EDIT
So here's the general process for displaying a Component in a JFrame:
1 - Set up your JFrame (Layouts, borders, etc):
JFrame frame = new JFrame("Frame Title");
JPanel contentPane = ((JPanel) frame.getContentPane());
contentPane.setLayout(new GridLayout(4,1)); //use whatever kind of layout you need
contentPane.setBorder(new EmptyBorder(10,10,10,10)); //use whatever kind of border you need
2 - Initialize your Component(s) (in this case, two JTextFields and a JButton):
JTextField empNumTF = new JTextField("Initial text in field");
JTextField shipNumTF = new JTextField("Initial text in field");
JButton displayButton = new JButton("Display");
3 - Add your component(s) to the JFrame's contentPane:
contentPane.add(empNumTF);
contentPane.add(shipNumTF);
contentPane.add(displayButton);
4 - Pack and make visible:
frame.pack();
frame.setVisible(true);
Then your JFrame should be displayed with those Components.
ADDED
Now, if we want to manipulate what the user enters into those text fields, we need to add an action listener for the button. To do this:
1 - Make one of your classes an action listener (you can use the same class that the JButton is created in if you want) by stating that it implements ActionListener:
public class EnterShipInfo implements ActionListener{
2 - Add an action-listening object to the button like so:
displayButton.addActionListener(this);
//using "this" means that the object this JButton was created in is the action listener.
3 - Add an actionPerformed() method to your ActionListener (as it seems you have already done correctly):
public void actionPerformed(ActionEvent e){
//insert code to execute whenever your button is clicked.
}
So now, specifically to you, inside your actionPerformed() method, you probably want to handle it something like this:
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals("Display")){ //"Display" is the text on the JButton
String employeeNum = empNumTF.getText();
String shipmentNum = shipNumTF.getText();
String revDate = dateTF.getText(); //These text fields
String revTime = timeTF.getText(); //not coded in
String supplierName = supplTF.getText(); //my example
ShipmentFrame sf = new ShipmentFrame(new Shipment(shipmentNum, supplierName, revDate, revTime, employeeNum)); //I'm just guessing at the order these come in
sf.setVisible(true);
}
}
Some key documentation you may want to take a look at:
javax.swing.JFrame
javax.swing.JPanel
javax.swing.JTextField
javax.swing.JButton
javax.swing.border.EmptyBorder
java.awt.GridLayout

Related

How to reuse a common panel?

I have a panel for adding an item to the cart. For example:
public class SomePanel extends JPanel {
private static final long serialVersionUID = 1L;
private JLabel firstLabel;
private JLabel secondNameLabel;
private JLabel thirdLabel;
// and more..
private JTextField firstTextField;
private JTextField firstTextField;
private JTextField thirdTextField;
// and more..
private void init() {
firstLabel = new JLabel("First label");
secondLabel = new JLabel("Second label");
thirdLabel = new JLabel("Third label");
// and more..
firstTextField = new JTextField("first field");
secondTextField = new JTextField("second field");
thirdTextField = new JTextField("third field");
// and more..
}
This panel is located in the dialog. When I select "Add" in the menu, a dialog and this panel appear. There I can enter information about the product and add the product.
The problem is that I have another three areas on the main form. These areas also display the same panel as above. How can I reuse an existing SomePanel and would this be a good practice? Maybe it's better to create singletons for each element (JLabel and JTextField) instead?
Maybe there is some special pattern for solving this problem?
It is an excellent suggestion to re-use the panel object, and it doesn't just work for a fixed number of fields, you can do it with a dynamic number of fields as well.
You have already created a wrapper around a JPanel, so we can simply add a method to it that will update the panel to display the new contents. In this case I have created a new method create(...) that will update the contents.
For example, if you have a fixed number of fields it might look something like this:
public class SomePanel extends JPanel {
private static final long serialVersionUID = 1L;
final int labelHeight = 10;
final int fieldHeight = 20;
private JLabel firstLabel = createLabel("label 1", 0, 0);
private JLabel secondLabel = createLabel("label 2", 0, 30);
private JLabel thirdLabel = createLabel("label 3", 0, 60);
// and more..
private JTextField firstTextField = createField(null, 0, 10);
private JTextField secondTextField = createField(null, 0, 40);
private JTextField thirdTextField = createField(null, 0, 70);
// and more..
//New method to udpate the contents
public boolean create(List<String> labels, List<String> textFields) {
if(labels.size() != textFields.size()){
System.out.println("Failed to update panel, there was a different number of labels and fields");
return false;
}
//Update the fixed label and field values
firstLabel.setText(labels.get(0));
secondLabel.setText(labels.get(1));
thirdLabel.setText(labels.get(2));
firstTextField.setText(textFields.get(0));
firstTextField.setText(textFields.get(1));
firstTextField.setText(textFields.get(2));
//Make sure that this panel is visiable after updating the values
this.setVisible(true);
//Success, return true
return true;
}
//Remove the x and y depending on the layout manager
private JLabel createLabel(String name, int x, int y){
//Create label
JLabel label = new JLabel(name);
//Set location and size or use a layour manager
label.setLocation(x, y);
label.setSize(50, labelHeight);
//Configure cutsom label settings
//label.setFont(...);
//label.setBorder(...);
//return the custom label
return label;
}
//Remove the x and y depending on the layout manager
private JTextField createField(String content, int x, int y) {
//Create label
JTextField field = new JTextField();
if(content != null){
field.setText(content);
}
//Set location and size or use a layour manager
field.setLocation(x, y);
field.setSize(80, fieldHeight);
//Configure cutsom text field settings
//field.setFont(...);
//field.setBorder(...);
//return the custom field
return field;
}
}
Or if you want to get fancy with dynamic content with a flexible number of labels and fields you could do something like this:
public class SomePanel extends JPanel {
private static final long serialVersionUID = 1L;
final int labelHeight = 10;
final int fieldHeight = 20;
final int padding = 5;
//Keep a list of contents only if you need to edit/retreive data from the panel
private List<JTextField> fieldList = new ArrayList<>();
//New method to udpate the contents
public boolean create(List<String> labels, List<String> textFields) {
if(labels.size() != textFields.size()){
System.out.println("Failed to update panel, there was a different number of labels and fields");
return false;
}
//remove previous components
this.removeAll();
//reset the dynamic lists (For if you need to edit/retreive data from the panel)
fieldList = new ArrayList<>();
//placement values (remove these if using a layout manager)
int xPos = 0;
int yPos = 0;
//Update the lists based on the new values
for (int count = 0; count < labels.size(); count++) {
//Create and add labels
JLabel dynamicLabel = createLabel(labels.get(count), xPos, yPos);
this.add(dynamicLabel);
//update placement location, remove if you use a layout manager
yPos += labelHeight + padding;
//Create and add fields
JTextField dynamicField = createField(textFields.get(count), xPos, yPos);
this.add(dynamicLabel);
//update placement location, remove if you use a layout manager
yPos += fieldHeight + padding;
//Store fields in a list so that we can retreive the contents later if needed, or if
fieldList.add(dynamicField);
}
//Make sure that this panel is visiable after updating the values
this.setVisible(true);
//Success, return true
return true;
}
//Remove the x and y depending on the layout manager
private JLabel createLabel(String name, int x, int y){
//Create label
JLabel label = new JLabel(name);
//Set location and size or use a layour manager
label.setLocation(x, y);
label.setSize(50, labelHeight);
//Configure cutsom label settings
//label.setFont(...);
//label.setBorder(...);
//return the custom label
return label;
}
//Remove the x and y depending on the layout manager
private JTextField createField(String content, int x, int y) {
//Create label
JTextField field = new JTextField();
if(content != null){
field.setText(content);
}
//Set location and size or use a layour manager
field.setLocation(x, y);
field.setSize(80, fieldHeight);
//Configure cutsom text field settings
//field.setFont(...);
//field.setBorder(...);
//return the custom field
return field;
}
//Method to get the current field contents if needed or if edited by the user
public List<JTextField> getCurrentFieldContent (){
return fieldList;
}
}

How can I prevent every click on the edit button from opening a JFrame to edit the selected row?

I am using 2 different classes: one holding a main JFrame with an edit JButton and one holding an edit JFrame that is called when the button is pressed.
First i select a row from a jtable for edit. After i press Edit button and a Jframe opens. If i press repeatedly the button, the same jframe are openning. So i want, after the first press of the button -> Jframe are openning and if i press again button I do not want to open the same frame again.
Here is a link with app image: https://ibb.co/gYfR9a
Here is my code for the Edit button:
JButton btnEdit = new JButton("Edit");
btnEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
Boolean chkDel = Boolean.valueOf(table.getValueAt(i, 0).toString());
if (chkDel) {
String id = table.getValueAt(i, 1).toString();
String num = table.getValueAt(i, 2).toString();
String pre = table.getValueAt(i, 3).toString();
String name = table.getValueAt(i, 4).toString();
String email = table.getValueAt(i, 5).toString();
EditFrame f = new EditFrame(Integer.valueOf(id), num, pre, name, email);
f.initFrame(Integer.valueOf(id), num, pre, name, email);
}
}
}
});
btnEdit.setBounds(150, 250, 90, 23);
getContentPane().add(btnEdit);`
And here is the code for the Edit Frame:
public class EditFrame extends JFrame {
private JPanel contentPane;
private JTextField idField;
private JTextField numField;
private JTextField preField;
private JTextField nameField;
private JTextField emailField;
private final JButton btnEdit = new JButton("Edit");
/**
* Launch the application.
*/
public void initFrame(int id, String num, String pre, String name, String email) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EditFrame eframe = new EditFrame(id, num, pre, name, email);
eframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
In your actionPerformed method of your button you should memorize if it was already clicked by using a boolean. You can then do something like if(!wasClickedAlready) { ... }. However the boolean needs to be kept in the correct scope (one above the method). For example as member variable of your ActionListener or in the wrapping class, or something like this. Else the state of the boolean can not be memorized between method-calls.
For example see this snippet:
btnEdit.addActionListener(new ActionListener() {
private boolean wasClicked = false;
#Override
public void actionPerformed(ActionEvent e) {
if (wasClicked) {
// Do nothing if clicked already
return;
} else {
// The button was clicked for the first time
wasClicked = true;
}
for (int i = 0; i < table.getRowCount(); i++) {
// Your stuff
...
}
}
});
If your question refers to not opening a frame for the same table row again, then you need to memorize the rows you have already clicked, for example by using a table of boolean like boolean[] or a Map mapping the row-index to a boolean like HashMap<Integer, Boolean>. However the scheme remains the same. If that is the case, just tell me in the comments and I will show you another snippet.
Edit: You commented that you maximally one frame should be shown for each row, not for the whole table. As stated above you can apply the same scheme than before:
btnEdit.addActionListener(new ActionListener() {
private boolean[] wasClickedTable = new boolean[table.getRowCount()];
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
Boolean chkDel = Boolean.valueOf(table.getValueAt(i, 0).toString());
// A row should be processed
if (chkDel) {
// Lookup if row was already clicked before
if(wasClickedTable[i]) {
// It was, skip the row and do not process it
continue;
}
// The row was not clicked before
// However it is now, set it
wasClickedTable[i] = true;
// Further process the row
// Your stuff
...
}
}
}
});
I'm not sure if I understood correctly. So you have a button that opens a JFrame, but you don't want the JFrame to be opened every time the button is clicked? What is the expected behavior?

ActionListener from button for JTextField, JTextField cannot be Resolved

I'm trying to get a head start on something I will be working on next semester. Its basically a template of a cell phone, consisting of a JTextField that displays the buttons pressed. My problem is when making my actionlistener, the JTextField (named "numIn") is not being recognized, getting an error saying it cannot be resolved. Here is the code for the way I have my JPanel of the phone set up:
public class Template
{
// the dial pad button strings
private static final String[][] BUTTONSTRINGS =
{
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"*", "0", "#"}
};
private static final Dimension JUNK_SIZE = new Dimension(200, 160);
private JPanel mainPanel = new JPanel();
public Template()
{
JTextField numIn = new JTextField("Enter Phone Number");
JTextField numDisplay = new JTextField("PhoneNumber");
JPanel otherJunkPanel = new JPanel();
otherJunkPanel.add(numDisplay);
otherJunkPanel.add(numIn);
otherJunkPanel.add(new JButton("Send"));
otherJunkPanel.setPreferredSize(JUNK_SIZE);
JPanel dialPadPanel = new JPanel(new GridLayout(0, 3));
Here is the two action listeners made, one for the numbers, one for the non numbers:
// action listener for the number buttons only
NumberButtonListener numberBtnListener = new NumberButtonListener();
// listener for other buttons
NonNumberButtonListener nonNumberBtnListener = new NonNumberButtonListener();
for (int i = 0; i < BUTTONSTRINGS.length; i++)
{
for (int j = 0; j < BUTTONSTRINGS[i].length; j++)
{
String btnString = BUTTONSTRINGS[i][j]; // get the button string from array
JButton btn = new JButton(btnString); // use it to make button
// if a number button, add the number button's listener
if ("012345679".contains(btnString))
{
btn.addActionListener(numberBtnListener);
}
else
{
btn.addActionListener(nonNumberBtnListener);
}
and here is where i get my error, when i tell the action listener to display the button at the JTextField named "numIn", numIn is not recognized:
private class NumberButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String buttonPressedString = e.getActionCommand();
numIn.setText("Number Button Pressed: " + buttonPressedString);
// TODO finish
}
}
I am not very strong in coding, as its not my major, so I appreciate any help possible. I should have probably prefaced that much of this code has been frankenstiend from bits and pieces of labs I have done in the past. Thanks!
Your numIn is a local variable on the constructor.
You should declare it as a class variable if you want to use it on other methods. (or pass it by argument for methods)
JTextField numIn = new JTextField("Enter Phone Number");
JTextField numDisplay = new JTextField("PhoneNumber");
public Template()
{
.......
you need to put that in class level scope. currently it is in constructor. so it will not available for out side of the constructor
Try this
private class NumberButtonListener implements ActionListener
{
Template parent=null;
NumberButtonListener(Template parent)
{
this.parent = parent;
}
public void actionPerformed(ActionEvent e)
{
String buttonPressedString = e.getActionCommand();
parent.numIn.setText("Number Button Pressed: " + buttonPressedString);
// TODO finish
}
}
Then change this
NumberButtonListener numberBtnListener = new NumberButtonListener();
to
NumberButtonListener numberBtnListener = new NumberButtonListener(this);
Add a new private field to your Template class
private JTextField numIn=null;
In the constructor change to this
numIn = new JTextField("Enter Phone Number");

Creating mouse listener for every JLabel newly created

I am building a family tree. The application is creating one JLabel by pressing JButton (with the icon as the person's picture) with this code:
JButton newPersonButton = new JButton("New Person");
newPersonButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final Data data = NewPerson.createPerson(frame);
if (data != null) {
if (Val == "mother") {
JLabel lblHomer = new JLabel(data.names);
lblHomer.setIcon(new ImageIcon(data.fileID));
cooX = cooX + 20;
cooY = cooY - 20;
panel_1.add(lblHomer, "cell " + cooX + " " + cooY);
panel_1.revalidate();
}
I need a JLabel created dynamically by clicking an existing JLabel. I can create another JLabel the same way I created the first one, and the new JLabel use the coordinates of the created JLabel as reference. Not just one, I need ALL of the JLabels to generated like that. When I click on them then it creates another. I know how to make one new JLabel by clicking on it:
JLabel lblHomer = new JLabel(data.names);
lblHomer.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
final Data data = NewPerson.createPerson(frame);
if (data != null) {
String Val = data.CBvalue;
if (Val == "mother") {
JLabel lblHomer = new JLabel(data.names);
lblHomer.setIcon(new ImageIcon(data.fileID));
cooX = cooX + 20;
cooY = cooY - 20;
panel_1.add(lblHomer, "cell " + cooX + " " + cooY);
panel_1.revalidate();
}
}
}
But, I can't just copy/paste that same code infinitely. I need to write a while loop or something to keep creating mouse listener for every JLabel I create. I need help with that.
Whole code: http://pastebin.com/zLx1zK9Z
EDIT: Data.java:
public class Data {
public final String names;
public final String dateBirth;
public final String bio;
public final String fileID;
public final String CBvalue;
public Data(String names, String dateBirth, String bio, String fileID, String CBvalue) {
this.CBvalue = CBvalue;
this.names = names;
this.dateBirth = dateBirth;
this.bio = bio;
this.fileID = fileID;
}
// getters
}
First...
if (Val == "mother") {
Is not how you compare Strings in Java, instead you should be using "mother".equals(Val)
Next, you could create a factory method which creates your labels, maybe even a utility class that has several different methods for creating yr labels, although I might consider a builder pattern of you got to this point...
public static JLabel createPersonLabel(Data data, MouseListener listener) {
JLabel lblHomer = new JLabel(data.names);
lblHomer.setIcon(new ImageIcon(data.fileID));
lblHomer.addMouseListener(listener);
}
I would then create a custom MouseListener to handle the core functionary
public class DataMouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
final Data data = NewPerson.createPerson(frame);
if (data != null) {
String Val = data.CBvalue;
if ("mother".equals(Val)) {
JLabel lblHomer = createPersonalLabel(data, this);
cooX = cooX + 20;
cooY = cooY - 20;
panel_1.add(lblHomer, "cell " + cooX + " " + cooY);
panel_1.revalidate();
}
}
}
}
As an example. Your even create a custom MouseListener for each type data you might need
Updated
There are any number of options, for example, you could create a factory style method in your NewFamilyTree class that creates and adds the data label based on your needs and the data type...
protected void createAndAddDataLabel(Data data) {
JLabel lblHomer = new JLabel(data.names);
lblHomer.setIcon(new ImageIcon(data.fileID));
cooX = cooX + 20;
cooY = cooY - 20;
panel_1.add(lblHomer, "cell " + cooX + " " + cooY);
panel_1.revalidate();
if (!"mother".equals(data.CBvalue)) {
lblHomer.addMouseListener(new DataMouseHandler());
}
}
Then call it from within your button...
JButton newPersonButton = new JButton("New Person");
newPersonButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final Data data = NewPerson.createPerson(frame);
if (data != null) {
createAndAddDataLabel(data);
}
}
});
And, as an inner class, you could define the DataMouseHandler...
public class DataMouseHandler extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
final Data data = NewPerson.createPerson(frame);
if (data != null) {
if ("mother".equals(Val)) {
createAndAddDataLabel(data);
}
}
}
}
If you need this as an external class, you would need to pass the reference of the NewFamilyTree
public class DataMouseHandler extends MouseAdapter {
private NewFamilyTree tree;
public DataMouseHandler(NewFamilyTree tree) {
this.tree = tree;
}
#Override
public void mouseClicked(MouseEvent e) {
final Data data = NewPerson.createPerson(frame);
if (data != null) {
if ("mother".equals(Val)) {
tree.createAndAddDataLabel(data);
}
}
}
}
Updated
Now, having said all that, this is a classic example of where a Model-view-controller approach would be most suitable.
What you should be doing is modelling the family tree in some way, which is divorced from the UI, so it simply focuses on the requirements of the model, how it's structured and how it's managed.
The model would provide feedback from event notification when it's changed in some way.
From there you would wrap a UI around it, so the UI would simply be responsible for rendering the output of the model.
The controller would take actions from the UI and update the model accordingly, which will in turn trigger updates from the model to the UI...
As said in comments, there are a couple of ways to do this. I think the first suggestion is probably best, based on what little I/we understand of what you want to do.
public class ListenerLabel extends JLabel implements MouseListener
{
public void mouseExited() {}
public void mouseEntered() {}
// etc.
public void mouseClicked() {}
{
// here put the code you have for creating another person
// 'this' refers to the label that was clicked on; you can get coordinates
// and whatever you need from that.
}
}
Now instead of creating JLabels to hold your people, you create ListenerLabels; they will interact with your UI just the same as JLabels, but have this extra feature of listening for their own clicks. And their name might be something do with people instead of listening, if they're going to contain code specific to people. ('PeopleLabels', or whatever).
-- edit -- more detail, as requested.
As I look at this again, it seems to me your NewPerson.createPerson() method must be popping up a dialog or something to get information for the new person. I will continue the example assuming that works, though I'd probably have done that differently.
public void mouseClicked()
{
final Data data = NewPerson.createPerson(frame);
if (data != null)
{
if (data.CBvalue.equals("mother")) // I would use a constant or enums here instead
{
ListenerLabel label = new ListenerLabel(data.names);
label.setIcon(new ImageIcon(data.fileID));
int xPosition = this.getX() + 20;
int yPosition = this.getY() - 20;
JPanel enclosingPanel = (JPanel)this.getParent();
enclosingPanel.add(label, "cell " + cooX + " " + cooY);
// set position of new label here?
enclosingPanel.revalidate();
}
}
}
Adding the new panel to the enclosing panel (which is panel_1 in your example, I assume) is a little 'black magic' to me -- unless that panel has a special layout manager, or you've extended JPanel so that add() means something special, I don't see how that's going to do anything useful. But this more-filled-out method shows where to get the existing label coordinates, a way to get the panel enclosing the two labels, and a suggestion where I would expect you to set the position of the new label.
There are a lot of assumptions here, because you haven't shown us executable code. I know it's difficult to extract running code out of a larger system, but be aware (you and other readers) that any answer for incomplete code is based on partly on assumptions made filling it in and partly on assumptions not made about what else is needed or coded elsewhere.

accessing widgets inside a GWT element

I want to access the text elements inside this textbox in GWT from the main method (where I call it like this)
DialogBox aBox = newCandidatePop.buildNewElecPopup();
aBox.center();
aBox.getWidget();
MiscUiTools.newCandidateHandler(aBox.firstName, aBox.surName);
in newCandidateHandler i want to attach a click handler to the two text boxes
However, the above doesnt quite work - I cant get access to the aBox.firstName elements because they are static methods -- I am wondering what is best practice, how would you code something like this up?
static TextBox firstName = new TextBox();
static TextBox surName = new TextBox();
static DialogBox box;
// public newCandidatePop() {
// box = buildNewElecPopup();
// }
static public DialogBox buildNewElecPopup() {
DialogBox box = new DialogBox();
box.setAutoHideEnabled(true);
box.setText("Add a New Candidate");
box.setAnimationEnabled(true);
box.setGlassEnabled(true);
Grid dialogGrid = new Grid(2, 3);
dialogGrid.setPixelSize(250 , 125);
dialogGrid.setCellPadding(10);
dialogGrid.setWidget(0, 0, new HTML("<strong>First Name</strong>"));
dialogGrid.setWidget(0, 1, firstName);
dialogGrid.setWidget(1, 0, new HTML("<strong>Surname</strong>"));
dialogGrid.setWidget(1, 1, surName);
box.add(dialogGrid);
return box;
}
Why are the TextBoxes static at all?
public class MyDialogBox extends DialogBox {
private final TextBox firstName;
private final TextBox surName;
public MyDialogBox() {
firstName = new TextBox();
surName = new TextBox();
DialogGrid dialogGrid = new Grid(2, 3);
// do all your stuff with the grid, add TextBoxes, etc.
add(dialogGrid);
setAutoHideEnabled(true);
// set all the properties of your DialogBox
}
public TextBox getFirstNameTextBox() {
return firstName;
}
// same with surName...
}

Categories

Resources