Я пытаюсь анимировать Layoutpanel с дочерним элементом текстового поля внутри диалогового окна. Я смог сделать это (например, анимацию), когда я тестировал его в простом классе/представлении, но когда я импортировал один и тот же код в диалоговом окне, анимация больше не работает.Анимировать виджет внутри DialogBox в GWT
В общем, анимация, которую я пытаюсь выполнить, в некоторой степени похожа на ящик, в котором, когда пользователь нажимает на флажок, панель макета, где мой текстовый ящик скрывается или скрывается (например, ящик) в зависимости от состояния флажок. Ниже мой код:
public class Testingwork implements EntryPoint {
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
public void onModuleLoad() {
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
final CheckBox danCheck2 = new CheckBox("Dan2");
final LayoutPanel testPanel2 = new LayoutPanel(); //-----------> LayoutPanel
final HorizontalPanel cont2 = new HorizontalPanel();
final TextBox tb12 = new TextBox();
final TextBox tb22 = new TextBox();
final TextBox tb32 = new TextBox();
dialogVPanel.add(danCheck2);
testPanel2.add(cont2);
cont2.add(tb12);
cont2.add(tb22);
cont2.add(tb32);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
if (event.getSource().equals(sendButton)) {
sendNameToServer();
}
else if(event.getSource().equals(danCheck2)) {
danMethod2();
}
}
/**
* Fired when the user types in the nameField.
*/
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
sendNameToServer();
}
}
/**
* Send the name from the nameField to the server and wait for a response.
*/
private void sendNameToServer() {
// First, we validate the input.
errorLabel.setText("");
String textToServer = nameField.getText();
if (!FieldVerifier.isValidName(textToServer)) {
errorLabel.setText("Please enter at least four characters");
return;
}
// Then, we send the input to the server.
sendButton.setEnabled(false);
textToServerLabel.setText(textToServer);
serverResponseLabel.setText("");
greetingService.greetServer(textToServer,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
dialogBox
.setText("Remote Procedure Call - Failure");
serverResponseLabel
.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(String result) {
dialogBox.setText("Remote Procedure Call");
serverResponseLabel
.removeStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(result);
dialogBox.center();
closeButton.setFocus(true);
}
});
}
private void danMethod2(){
if (danCheck2.getValue()){
System.out.println("[dan]: chbCrossReferencePnr2 = Checked!");
testPanel2.setWidgetTopHeight(cont2, 0, PX, 60, PX);
// testPanel2.setHeight("60px");
testPanel2.animate(500);
}
else {
System.out.println("[dan]: chbCrossReferencePnr2 = unChecked!");
testPanel2.setWidgetTopHeight(cont2, 0, PX, 0, PX);
// testPanel2.setHeight("0px");
testPanel2.animate(500);
}
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
danCheck2.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
}
Я проверил это в классе; и это работает. Но когда я импортировал его в диалоговом окне, мой layoutpanel (и текстовое поле внутри) больше не отображается.
Можете ли вы рассказать мне, что я здесь делаю неправильно? Возможно, я просто пропустил что-то в моей реализации диалогового окна, так как мой код работает в классе.
Заранее благодарен!
В вашем коде нет необходимости в LayoutPanel. Убери это. Я не знаю, решает ли она вашу проблему, но меньшее количество виджетов всегда хорошая идея. –
Не требуется ли LayoutPanel при анимации виджета? Я попытался удалить LayoutPanel и просто использовал HorizontalPanel, но он не принимает анимацию(). Есть ли альтернативный способ сделать это без использования LayoutPanel (или других, которые реализуют AnimatedLayout)? – dan15ph
[отредактировано] О, я не заметил, что вы тот, кто отметил, что макетная панель не добавлена, поэтому она не отображается ниже. :) Я уже добавил layoutpanel, и он работает. Я просто пропустил его, когда тестирую свои коды. Спасибо за помощь! : D – dan15ph