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...
}
Related
I have a pretty simple class that basically is just an AppLayout with some Tab.
Now my issue. I am not able to find a smart way to display different contents for the Tabs-class. Is there any interface or something that can be called to differ the content for the Tab?
class MainAppView extends AppLayout {
public MainAppView()
{
createDrawerAndAddToAppView();
}
void createDrawerAndAddToAppView()
{
Tabs tabs = createTabsForDrawer();
tabs.setOrientation(Tabs.Orientation.VERTICAL);
addToDrawer(tabs);
H1 a = new H1("Test"); // Is displayed as content for every Tab
tabs.addSelectedChangeListener(selectedChangeEvent ->
/**
* How to get the specific content of a Tab here?
*/
//selectedChangeEvent.getSelectedTab(). //getContent() and put in super.setContent()?
super.setContent(a)); // Displays 'Test' as content for every Tab
// The Listener shall display the specific content of the getSelectedTab()
}
private Tabs createTabsForDrawer()
{
return new Tabs(
new Tab("Home"),
new Tab("Dummy"),
new Tab("Test"));
}
}
Here is one example, using a map to keep track of which content belongs to which tab. In reality your tab content would be more complicated, and maybe be created in it's own method.
#Route
public class TabTest extends VerticalLayout {
private Map<Tab, Component> tabComponentMap = new LinkedHashMap<>();
public TabTest() {
Tabs tabs = createTabs();
Div contentContainer = new Div();
add(tabs, contentContainer);
tabs.addSelectedChangeListener(e -> {
contentContainer.removeAll();
contentContainer.add(tabComponentMap.get(e.getSelectedTab()));
});
// Set initial content
contentContainer.add(tabComponentMap.get(tabs.getSelectedTab()));
}
private Tabs createTabs() {
tabComponentMap.put(new Tab("Show some text"), new H1("This is the text tab"));
tabComponentMap.put(new Tab("Show a Combo Box"), new ComboBox<String>());
tabComponentMap.put(new Tab("Show a button"), new Button("Click me and nothing happens"));
return new Tabs(tabComponentMap.keySet().toArray(new Tab[]{}));
}
}
You can do something similar with routes also, but then you would probably want your containing component to be a RouterLayout. Also this requires a bit more logic if you want to automatically select the correct tab after navigating from somewhere else.
#Route
public class TabTest extends VerticalLayout implements RouterLayout {
private Map<Tab, String> tabToUrlMap = new LinkedHashMap<>();
private Div contentContainer = new Div();
public TabTest() {
Tabs tabs = createTabs();
Div contentContainer = new Div();
contentContainer.setSizeFull();
add(tabs, contentContainer);
tabs.addSelectedChangeListener(e ->
UI.getCurrent().navigate(tabToUrlMap.get(e.getSelectedTab())));
}
private Tabs createTabs() {
RouteConfiguration routeConfiguration = RouteConfiguration.forApplicationScope();
tabToUrlMap.put(new Tab("View 1"), routeConfiguration.getUrl(TestView1.class));
tabToUrlMap.put(new Tab("View 2"), routeConfiguration.getUrl(TestView2.class));
tabToUrlMap.put(new Tab("View 3"), routeConfiguration.getUrl(TestView3.class));
return new Tabs(tabToUrlMap.keySet().toArray(new Tab[]{}));
}
#Override
public void showRouterLayoutContent(HasElement content) {
getElement().appendChild(content.getElement());
}
}
And an example view
#Route(layout = TabTest.class)
public class TestView3 extends VerticalLayout {
public TestView3() {
add("View 3");
}
}
I would like to have this functionality in my program:
I will have a user input field. When the user pressed the button, it will be added to the list, and input will be shown to the user.
The problem is, I would like to deselect/remove those input if the user wants. I could not achieve this.
Here is the code I have written so far, I have removed some functionality unnecessary for the question's scope:
public class AddUserInput extends VerticalLayout{
// The user input will be added to the this list
// later, this list will be sent to the server for some verification
private List<String> emails;
private HorizontalLayout content;
private VerticalLayout rows;
// user input field
private TextField emailField = new TextField("Enter email address");
public AddUserInput() {
content = new HorizontalLayout();
rows = new VerticalLayout();
content.setMargin(true);
Button addToListButton= new Button("Add to list");
addToListButton.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(Button.ClickEvent event) {
// When the user clicks add to list button
// The raw input will be added to the emails list
// The UI component is added to 'rows' component
rows.addComponent(addNewRow(emailField.getValue()));
}
});
content.addComponents(emailField, addToListButton, rows);
addComponent(content);
}
public Component addNewRow(String email){
HorizontalLayout newRow = new HorizontalLayout();
Button deleteRowButton = new Button("-");
deleteRowButton.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(Button.ClickEvent event) {
// I can delete from the UI by using the code below
newRow.removeAllComponents();
rows.removeComponent(newRow);
// How to remove from the email list???
}
});
emails.add(emailField.getValue());
Label lastEmail = new Label(emailField.getValue());
emailField.clear();
newRow.addComponents(lastEmail,deleteRowButton);
return newRow;
}
}
Is there any component/library that does this functionality?
I only need a text field, and adding the input to the list, and removing the list item if a user wants to.
The visualization of the code above:
You could use the NativeSelect component for managing the entered Strings.
I modified your AddUserInput-Component to use a NativeSelect and a corresponding DataProvider:
public class AddUserInput extends VerticalLayout {
private HorizontalLayout content = new HorizontalLayout();;
private NativeSelect<String> select = new NativeSelect<>("The List");
private ListDataProvider<String> dataProvider = DataProvider.ofCollection(new ArrayList<>());
private Button addToListButton= new Button("Add to list");
private Button deleteFromListButton = new Button("-");
private TextField emailField = new TextField("Enter email address");
public AddUserInput() {
select.setVisibleItemCount(5);
select.setWidth("100px");
select.setDataProvider(dataProvider);
select.setEmptySelectionAllowed(false);
deleteFromListButton.setEnabled(false);
content.setMargin(true);
addToListButton.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(Button.ClickEvent event) {
addEmailToList(emailField.getValue());
}
});
deleteFromListButton.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(Button.ClickEvent clickEvent) {
select.getSelectedItem().ifPresent(selectedItem -> removeSelectedEmailFromList());
}
});
select.addValueChangeListener(new HasValue.ValueChangeListener<String>() {
#Override
public void valueChange(HasValue.ValueChangeEvent<String> valueChangeEvent) {
deleteFromListButton.setEnabled(select.getSelectedItem().isPresent());
}
});
content.addComponents(emailField, addToListButton, select, deleteFromListButton);
addComponent(content);
}
private void addEmailToList(String email){
dataProvider.getItems().add(email);
select.getDataProvider().refreshAll();
emailField.clear();
}
private void removeSelectedEmailFromList(){
select.getSelectedItem().ifPresent(selectedItem -> dataProvider.getItems().remove(selectedItem));
select.setSelectedItem(dataProvider.getItems().isEmpty() ? null : dataProvider.getItems().iterator().next());
select.getDataProvider().refreshAll();
}
}
It looks like the following:
Would that be a possible option for you?
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
I'm looking for a way to pass fields with enter key in VerticalLayout or others. In vaadin book there an example with Shortcut and Handler listeners but I don't know how to implement that.
I'm trying this.
public class MyWindow extends Window implements Handler{
private Action action_enter; //pass fields with enter
private Action action_esc;
private TextField name, lastName;
public MyWindow(){
super("this window is opened");
VerticalLayout vLayout = new VerticalLayout();
setContent(vLayout);
center();
setModal(true);
setClosable(false);
setDraggable(false);
setResizable(false);
//actions
action_enter = new ShortcutAction("Enter key", ShortcutAction.KeyCode.ENTER, null);
action_esc = new ShortcutAction("Esc key", ShortcutAction.KeyCode.ESCAPE, null);
addActionHandler(this);
//fields
name = new TextField("Name");
lastName = new TextField("Last name");
name.focus();
vLayout.addComponent(name);
vLayout.addComponent(lastName);
}
#Override
public Action[] getActions(Object target, Object sender) {
return new Action[] { action_enter, action_esc };
}
#Override
public void handleAction(Action action, Object sender, Object target) {
/** close window with esc key */
if(action == action_esc){
close();
}
/** pass fields with enter key */
if(action == action_enter){
//here pass fields with enter key
}
}
}
any idea ?
try this way with ShortcutListener:
ShortcutListener skEnterListener = new ShortcutListener("Enter", ShortcutAction.KeyCode.ENTER, null){
#Override
public void handleAction(Object sender, Object target) {
if (target instanceof VerticalLayout) { // VerticalLayout or other
// sending fileds here
}
}
};
addShortcutListener(skEnterListener);
change focus of TextField using Enter instead Tab:
final TextField tf1 = new TextField("tf1");
tf1.setId("tf1");
final TextField tf2 = new TextField("tf2");
tf2.setId("tf2");
ShortcutListener skEnterListener = new ShortcutListener("Enter", ShortcutAction.KeyCode.ENTER, null){
#Override
public void handleAction(Object sender, Object target) {
if (target instanceof TextField) {
TextField field = (TextField) target;
if ("tf1".equals(field.getId())) {
tf2.focus();
}
if ("tf2".equals(field.getId())) {
tf1.focus();
}
}
}
};
addShortcutListener(skEnterListener);
There is no interface which does provide an accessor that would allow you finding out the currently focused component. Focus information can be acquired for some (but not all) field components through the com.vaadin.event.FieldEvents.FocusListener and com.vaadin.event.FieldEvents.BlurListener interfaces.
You could add for all possible fields a FocusListener and remember every time it's invoked, the current field in a variable. (Problem: not all fields provide a FocusListener.) Then when ENTER is pressed focus the next component according to the current focused field (remember the variable) that has to be focused (with the help of a simple List, LinkedList, Map, switch-case and so forth). To make it even better add a BlurListener as well to know when not to focus the next field.
Hope that helps.
I am working on Eclipse plugin. Here i created a separate view and now i want to format the color of tree node.
These are code present in createpartcontrol method.
ScrolledComposite sc = new ScrolledComposite(parent, SWT.V_SCROLL );
Composite composite1 = new Composite(sc, SWT.NONE);
Composite composite_1 = creatingcomposite(composite1);
Tree tree = new Tree(composite_1, SWT.FULL_SELECTION );
TreeItem item = new TreeItem(tree, SWT.NONE);
here i want to set some colour like blue.
item.setText("This is sparta");
Now here i want some different colour like yellow on subsubitem text.
TreeItem subsubItem = new TreeItem(subItem, SWT.NONE);
subsubItem.setText(new String[] { "Function Name: "+ errorPreTest11.description.get(j).function });
For doing this i tried to set SWT.COLOR_BLUE but it's not working.
Use
item.setForeground(tree.getDisplay().getSystemColor(SWT.COLOR_BLUE));
You can also create your own colors but if you do this you must dispose of them when you are done.
I suggest you using the TreeViewer. In this case you would have a functionality to set a LabelProvier on your viewer. Label provider has a subclass called StyledCellLabelProvider, which you can successfully extend to provide styling of your labels like this: (Please also see a TextStyle class for more formating options).
public class MyStyledLabelProvider extends StyledCellLabelProvider {
private Styler defaultStyler;
public MyStyledLabelProvider () {
defaultStyler = new Styler() {
#Override
public void applyStyles(TextStyle textStyle) {
textStyle.strikeout = true;
}
};
}
#Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
StyledString styledString = getStyledString(element);
cell.setText(styledString.toString());
cell.setStyleRanges(styledString.getStyleRanges());
super.update(cell);
}
#SuppressWarnings("unchecked")
private StyledString getStyledString(Object element) {
return new StyledString("Cell string", defaultStyler);
}
}