Updating label of a ButtonField from PopupScreen - java

I have a ButtonField on MainScreen, from which I am pushing a PopupScreen where I have added an ObjectListfield. What I want to do is to update the label of ButtonField on MainScreen with the element selected from ObjectListfield of PopupScreen.
Please tell me if it is possible to do without using Dialog class (I really want to use PopupScreen and not Dialog class) and the method by which this can be done. I'd appreciate if some sample code will be provided.
I have added my code.
public final class MyScreen extends MainScreen {
HorizontalFieldManager hfm;
ButtonField btn;
public MyScreen() {
// Set the displayed title of the screen
super();
setTitle("MyTitle");
btn = new ButtonField("label",ButtonField.CONSUME_CLICK);
final mypopup mps = new mypopup();
btn.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field,int context) {
UiApplication.getUiApplication().pushModalScreen(mps);
}
});
hfm = new HorizontalFieldManager();
hfm.add(btn);
add(hfm);
}
public void setlabel(String labelnew) {
btn.setLabel(labelnew);
}
public String getlabel() {
return this.btn.getLabel();
}
}
class mypopup extends PopupScreen implements FieldChangeListener {
String it;
ObjectListField obj = new ObjectListField() {
public boolean navigationClick(int status,int time) {
int selectedindex=obj.getSelectedIndex();
it=(String)obj.get(obj, selectedindex);
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
/*MyScreen my=new MyScreen();
my.btn.setLabel(it);
my.invalidate(); */
//close();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
/* This im doing to see that setlabel and getlabel are
working properly */
MyScreen my=new MyScreen();
my.setlabel(it);
String gt=my.getlabel();
Dialog.alert(gt);
my.hfm.invalidate();
//the label of button is changed but not updating in mainscreen.
}
});
return true;
}
};
public mypopup() {
super(new VerticalFieldManager());
String[] type=new String[] {"a","b","c","d"};
obj.set(type);
add(obj);
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
}
}

You need to change following block of code,
MyScreen my = new MyScreen();
my.setlabel(it);
String gt = my.getlabel();
Dialog.alert(gt);
my.hfm.invalidate();
With the code block,
Screen scr = UiApplication.getUiApplication().getActiveScreen();
if (scr instanceof MyScreen) {
MyScreen my = (MyScreen) scr;
my.setlabel(it);
my.invalidate();
}

Add the button in one Manager either HorizontalFieldManager or VerticalFieldManager and after setting text on button invalidate the managerlike this way
public final class MyScreen extends MainScreen
{
ButtonField btn;
public MyScreen()
{
// Set the displayed title of the screen
super();
setTitle("MyTitle");
btn=new ButtonField("label",ButtonField.CONSUME_CLICK);
final mypopup mps=new mypopup();
btn.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field,int context){
UiApplication.getUiApplication().pushModalScreen(mps);
}
});
HorizontalFieldManager hfmToholdButtons = new HorizontalFieldManager();
btn.setLabel(mps.gettext());
hfmToholdButtons.add(btn);
hfmToholdButtons.invalidate();
}
}

Related

Unexpected change in background of header of custome jcombobox in swing

I try to make a custom jcombobox for my menu sidebar
my jcombobox has JButton as items because I found it easy to insert and align icon and text.
But my problem is when I choose a item in dropdown, the color of the header changes unexpectedly to the default color of component.
public class MyComboBoxRenderer extends JLabel implements ListCellRenderer<Object> {
private String _title;
private JButton header;
public MyComboBoxRenderer(String title) {
_title = title;
}
#Override
public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean hasFocus) {
JButton item = new JButton();
item.setOpaque(true);
item.setBorderPainted(false);
item.setFocusPainted(false);
item.setBackground(isSelected ? Frame.LIGHTER_COLOR : Frame.LIGHT_COLOR );
ImageIcon dot = new ImageIcon("image/icon/orange_dot.png");
if (index == -1){
item.setText(_title);
header=item;
return item;
}
else{
item.setIcon(dot);
item.setIconTextGap(30);
item.setText(value.toString());
return item;
}
}
public JButton getHeader(){
return header;
}
}
public static class MyComboBoxUI extends BasicComboBoxUI {
final JButton button= new JButton(EXPAND_ARROW);
protected void installDefaults() {
super.installDefaults();
}
#Override
protected JButton createArrowButton() {
button.setContentAreaFilled(false);
button.setBorder(null);
return button;
}
#Override
public void configureArrowButton() {
super.configureArrowButton();
}
public JButton getArrowButton(){
return button;
}
}
public class ComboBox extends JComboBox{
public boolean isExpanded = false;
private MyComboBoxRenderer renderer;
public ComboBox(){
super();
this.setUI(new MyComboBoxUI());
}
public ComboBox(String[] list){
super(list);
renderer = new MyComboBoxRenderer("Lists Of Vocab");
this.setUI(new MyComboBoxUI());
this.setFont(Frame.I_FONT);
this.setForeground(Frame.FONT_COLOR);
this.setBackground(Frame.LIGHT_COLOR);
this.setRenderer(renderer);
MyComboBoxUI ui = (MyComboBoxUI) this.getUI();
JButton arrowButton = ui.getArrowButton();
arrowButton.addActionListener((ActionEvent e)->{
isExpanded = !isExpanded;
if(isExpanded == true){
arrowButton.setIcon(COLLAPSE_ARROW);
}
else{
arrowButton.setIcon(EXPAND_ARROW);
}
});
}
public MyComboBoxRenderer getRenderer(){
return renderer;
}
I add this combobox to the sideBar
private void addCheckBoxToSideBar(){
ComboBox lists = new ComboBox(listNames);
lists.setAlignmentX(Component.LEFT_ALIGNMENT); // have to have
lists.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
CardLayout cl = (CardLayout)(mainPane.getLayout());
cl.show(mainPane, (String)e.getItem());[enter image description here][1]
}
}
});
sideBar.add(lists);
}
This is first:
https://i.stack.imgur.com/ctVnT.png
But when I click to choose an item, it changes to default color:
https://i.stack.imgur.com/KkhhO.png
Those are what I tried but they didn't work:
to set the background of the header in the itemStateChanged
get the JTextfield of BasicComboBoxEditor of it
I wonder whether updating UI causes this problem but I don't understand much about it.
In your MyComboBoxUI, try overriding this method :
#Override
public void paintCurrentValueBackground(Graphics g,Rectangle bounds,boolean hasFocus)
{
Color t = g.getColor();
g.setColor(your_color);
g.fillRect(bounds.x,bounds.y,bounds.width,bounds.height);
g.setColor(t);
}

Hide UI component in sub-view

I am trying to find the best way to hide a UI component in a specific sub View but let it be visible in others.
This is the code of my UI class:
public class DCSAdminUI extends UI {
private static final long serialVersionUID = 1L;
VerticalLayout root = new VerticalLayout();
CssLayout content = new CssLayout();
private MenuBar nav = new MenuBar();
private MenuBar userNav = new MenuBar();
private Navigator navigator;
public static final String PERSISTENCE_UNIT = "mystery";
public static DCSAdminUI getCurrent() {
return (DCSAdminUI) UI.getCurrent();
}
public static DCSAdminUI getApplication() {
return (DCSAdminUI) getApplication();
}
#Override
protected void init(VaadinRequest request) {
Page.getCurrent().setTitle("Admin");
initLayout();
initNav();
initUserNav();
getUserOrg();
navigator = new Navigator(this, content);
LoginUI loginView = new LoginUI();
navigator.addView("", loginView);
navigator.addView(ActivitiesUI.VIEW_NAME.toLowerCase(), new ActivitiesUI());
navigator.addView(BookingsUI.VIEW_NAME.toLowerCase(), new BookingsUI());
navigator.addView(OperatorsUI.VIEW_NAME.toLowerCase(), new OperatorsUI());
navigator.addView(TeamUI.VIEW_NAME.toLowerCase(), new TeamUI());
navigator.addView(OrganisationsUI.VIEW_NAME.toLowerCase(), new OrganisationsUI());
navigator.addView(PlayersUI.VIEW_NAME.toLowerCase(), new PlayersUI());
navigator.addViewChangeListener(new ViewChangeListener() {
private static final long serialVersionUID = 1L;
#Override
public boolean beforeViewChange(ViewChangeEvent event) {
return true;
}
#Override
public void afterViewChange(ViewChangeEvent event) {
if (event.getViewName() == null || event.getViewName().equals("")) {
updateNavSelection("activities");
} else {
updateNavSelection(event.getViewName());
}
}
});
}
private void initLayout() {
root.setSizeFull();
setContent(root);
HorizontalLayout topbar = new HorizontalLayout();
topbar.addStyleName("topbar");
topbar.setWidth("100%");
topbar.setSpacing(true);
root.addComponent(topbar);
content.setSizeFull();
root.addComponent(content);
root.setExpandRatio(content, 1);
nav.addStyleName("nav");
topbar.addComponent(nav);
userNav.addStyleName("user-nav");
topbar.addComponent(userNav);
topbar.setComponentAlignment(userNav, Alignment.TOP_CENTER);
}
private void initNav() {
nav.addItem(ActivitiesUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(BookingsUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(PlayersUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(TeamUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(OperatorsUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
nav.addItem(OrganisationsUI.VIEW_NAME.toUpperCase(Locale.GERMANY), navCommand).setCheckable(true);
}
private void initUserNav() {
MenuItem username = userNav.addItem("DCS User", FontAwesome.CHEVRON_DOWN, null);
username.addItem("Edit Profile", null);
username.addItem("Settings", null);
username.addSeparator();
username.addItem("Logout", null);
}
private Command navCommand = new Command() {
private static final long serialVersionUID = 1L;
#Override
public void menuSelected(MenuItem selectedItem) {
updateNavSelection(selectedItem.getText());
navigator.navigateTo(selectedItem.getText().toLowerCase());
}
};
private void updateNavSelection(String selectedItem) {
for (MenuItem item : nav.getItems()) {
item.setChecked(item.getText().toLowerCase()
.equals(selectedItem.toLowerCase()));
}
}
void navigateTo(String menuItem) {
for (MenuItem item : nav.getItems()) {
if (item.getText().toLowerCase().equals(menuItem.toLowerCase())) {
navCommand.menuSelected(item);
return;
}
}
}
}
The UI component in question here is topbar in the initLayout() method which is the app's main MenuBar() but I want this to appear only for authenticated users, meaning that it should be hidden in LoginUI() (the default View class for now). My search efforts have led me to understand that I can use multiple UI classes but that this would eventually become tedious to maintain and that is why I would ideally like to find a way of hiding the topbar component in specific View classes
You can implement a ViewChangeListener in your UI and deal with your navbar in the beforeViewChange. Since this can also reject entering a View you can send anon users to the login too.

GWT - Get button's "addClickHandler" from a Widget

first of all Im working on a time tracking page with login authentication using ldap.
For the login I created a dialogbox setting verticalpanel as its widget. My verticalpanel contains two textboxes to enter username/password and one button to send data to the ldap server.
On module load the dialogbox pops up and gets the time tracking content on login success.
To my question:
"LoginWidget" and "LoginClickHandler" have separated classes, hence I need to get the login button on module load to add "LoginClickHandler".
What is the best way to handle this? - since I know that my solution isnt that good.
LoginWidget class
public class LoginWidget{
private Button loginButton;
private DialogBox dialogBox;
private TextBox tbxUser;
private PasswordTextBox tbxPw;
private Label lblUser;
private Label lblPW;
private Label lblError;
public LoginWidget(){
dialogBox = new DialogBox();
tbxUser = new TextBox();
tbxPw = new PasswordTextBox();
lblUser = new Label();
lblPW = new Label();
lblError = new Label();
dialogBox.setText("Login");
dialogBox.setAnimationEnabled(true);
loginButton = new Button("Login");
// set the id of a widget by accessing its Element
loginButton.getElement().setId("closeButton");
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(lblUser);
lblUser.setText("User:");
dialogVPanel.add(tbxUser);
dialogVPanel.add(lblPW);
lblPW.setText("PW:");
dialogVPanel.add(tbxPw);
dialogVPanel.add(lblError);
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
dialogVPanel.add(loginButton);
dialogBox.setWidget(dialogVPanel);
dialogBox.show();
dialogBox.center();
}
public Button getLoginButton(){
return loginButton;
}
public DialogBox getDialogBox(){
return dialogBox;
}
public TextBox getTbxUser(){
return tbxUser;
}
public TextBox getTbxPw(){
return tbxPw;
}
public Label getLblError(){
return lblError;
}
}
LoginClickHandler class
public class LoginClickHandler implements ClickHandler {
/**
*/
private LoginWidget lw;
private ServiceImplURL serviceImplURL;
private TimeTracking dtt = new TimeTracking();
public LoginClickHandler(ServiceImplURL sIU, LoginWidget _lw){
/**
*/
this.lw = _lw;
this.serviceImplURL = sIU;
}
public void onClick(ClickEvent event) {
/**
*/
serviceImplURL.getRpcLdap().authenticate(lw.getTbxPw().getText(), lw.getTbxUser().getText(), new AsyncCallback<Boolean>() {
/**
*/
#Override
public void onSuccess(Boolean isLdapAuthOk) {
/**
*/
if(isLdapAuthOk){
lw.getDialogBox().hide();
User user = new User(lw.getTbxUser().getText(), lw.getTbxPw().getText());
serviceImplURL.getRpcSession().setUsername(user.getUsername(), new AsyncCallback<Void>() {
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(Void result) {
// TODO Auto-generated method stub
}
});
serviceImplURL.getRpcDB().insertUser(user.getUsername(), new AsyncCallback<Void>() {
/**
*/
#Override
public void onFailure(Throwable caught) {
/*
* connection error to implement
*/
}
#Override
public void onSuccess(Void result) {
/*
* do nothing
*/
}
});
dtt.loadContent();
}
else{
lw.getLblError().setStyleName("error");
lw.getLblError().setText("Passwort oder Username falsch!");
}
}
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
});
}
}
My Entrypoint
#Override
public void onModuleLoad() {
/**
*/
loadLoginWidget();
}
/**
* Creates the login pop up.
*/
public void loadLoginWidget(){
/**
*/
LoginWidget lw = new LoginWidget();
LoginClickHandler lch = new LoginClickHandler(serviceImplURL, lw);
lw.getLoginButton().addClickHandler(lch);
}
I already tried to extend Button but I dont think its a difference.
Pass a listener class (eg. your LoginClickHandler) to the view constructor:
public LoginWidget( LoginClickHandler listener )
{
...
loginButton.addClickHandler( listener )
...
}
More generally you may want to interject an interface defining the actions and have LoginClickHandler implement it:
public interface LoginListener
{
void onLogin();
...
}
public class LoginWidget
{
public LoginWidget( LoginListener listener )
{
this.listener = listener;
Button loginButton = new Button( "Login" );
loginButton.addClickHandler( new ClickHandler()
{
public void onClick( ClickEvent event ) { listener.onLogin(); }
} );
}
...
}
and finally
public class LoginClickHandler implements LoginListener
{
#Override public void onLogin()
{
serviceImplURL.getRpcLdap()...
...
}
}
and
public void loadLoginWidget()
{
LoginWidget lw = new LoginWidget( new LoginClickHandler() );
...
}
Cheers,

Component within ListView does not update on AJAX refresh

I have a Wicket Panel that contains a ListView and then sub-items (Form controls), but when I press an inner CheckBox, the visibility of some of the sub-items should change.
However, calling WebMarkupContainer.setVisible(false) does not hide the items within the ListView after the ListView is redrawn during the AJAX update.
Code below:
public class ImagePanel extends Panel {
private ArrayList<ImageEntry> imageEntryList;
public class ImageEntry implements Serializable {
private static final long serialVersionUID = -3987685200930059655L;
public String thumbnail;
public String filename;
public boolean webDownloaded;
public WebMarkupContainer fileUpload;
public WebMarkupContainer webDownload;
}
public ImagePanel(String id) {
this(id, IMAGE_NORMAL);
}
public ImagePanel(String id, int type) {
super(id);
this.type = type;
wmc = new WebMarkupContainer ("wmc");
wmc.setOutputMarkupId(true);
add(wmc);
imageEntryList = new ArrayList<ImageEntry>();
ImageEntry imageEntry = new ImageEntry();
imageEntry.thumbnail = "blah";
imageEntry.filename = "blah";
imageEntryList.add(imageEntry);
ListView<ImageEntry> llv = new LargeImageListView("large_image_list", imageEntryList);
wmc.add(llv);
SmallImageListView slv = new SmallImageListView("small_image_list", imageEntryList);
wmc.add(slv);
}
private final class SmallImageListView extends ListView<ImageEntry> {
private SmallImageListView(String id, List<? extends ImageEntry> list) {
super(id, list);
}
#Override
protected void populateItem(final ListItem<ImageEntry> item) {
...
if (type == IMAGE_WIZARD) {
item.getModelObject().fileUpload = showWizardFileUpload(item);
item.getModelObject().webDownload = showWizardWebDownload(item);
showSortUpDown(item);
showWebCheckbox(item);
}
}
}
private void showWebCheckbox(final ListItem<ImageEntry> item) {
AjaxCheckBox checkbox = new AjaxCheckBox("use_web_image", new PropertyModel<Boolean>(item.getModelObject(), "webDownloaded")) {
public void onUpdate(AjaxRequestTarget target) {
if (getModelObject()) {
System.out.println("Show");
item.getModelObject().fileUpload.setVisible(false);
item.getModelObject().webDownload.setVisible(false);
} else {
System.out.println("Hide");
item.getModelObject().fileUpload.setVisible(false);
item.getModelObject().webDownload.setVisible(false);
}
target.add(wmc);
}
};
item.add(checkbox);
}
...
}
Use ListView.setReuseItems(true) to ensure that the objects within the ListView are serialized correctly... Otherwise, you will receive a different object each time and the .setVisible() property will be reset to its default value (e.g. 'true').
slv.setReuseItems(true);
Try
WebMarkupContainer.add(new AttributeModifier("style", new Model("display:none")));
or
WebMarkupContainer.add(new AttributeAppender("style", new Model("display:none"), "="));
instead.

Understanding composite in java or GWT

I have problem in understanding a composite.
In Frame class i have verticalPanel(vp) when vp is loaded , getAction and get Button is visible on vp
WHen click on button there is a getTree is executed and there is treeC class initialized where there is customised tree. and treeitem.
I want to use action object in class TreeC
How to do it.
Plz Help.
public class Frame{
public frame () {
initWidget(getFramePanel());
}
Private VerticalalPanel getFramePanel() {
if (vp== null) {
vp= new VerticalalPanel();
vp.setSize("1442px", "750px");
vp.add(getAction());// **are composites**
vp.add(getButton) // **are composite**
}
return vp;
private Action getAction() {
if (action == null) {
action = new Action(); // In action class there are 7 buttons and 2 methods //setDisplayRepository(), and setDisplayFolder()
action.setDisplayRepository();
}
return action;
}
}
private Button getButton() {
if (btn == null) {
btn = new Button("Click");
btnProperties.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
hp.add(getTree());
}
});
btn.setSize("37px", "36px");
}
return btnProperties;
}
private TreeCmis getTreeC() {
if (treeC == null) {
treeC = new TreeC();
treeC.setWidth("360px");
}
return treeCmis;
}
}
public class TreeC extends Composite{
private Tree repo;
//constructor
public TreeC {
createTree()
}
Void createTree(){
/* here i need to to use the object action declared in frame class
For using action.setDisplayfolder*/
}
}
The simplest way is:
public class TreeC extends Composite{
private Tree repo;
private Action action;
//constructor
public TreeC(Action action) {
this.action = action;
createTree()
}
void createTree(){
/* here i need to to use the object action declared in frame class
For using action.setDisplayfolder*/
}
}
When Create instance treeC = new TreeC(action);

Categories