Search filter in Container Codename One - java

I'm trying to implement a search filter in my Container which contains a set of buttons.
Here's my code:
public void listMenu() {
Dialog loading = new InfiniteProgress().showInifiniteBlocking();
loading.show();
final Form listMenu = new Form("List Menu");
listMenu.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Container list = new Container();
list.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
list.removeAll();
Button back = new Button("Back to Main Menu");
ParseQuery<ParseObject> query = ParseQuery.getQuery("mylist");
query.whereExists("Title");
List<ParseObject> results = null;
try {
Button btn = null;
results = query.find();
if(!results.isEmpty()) {
int index = 0;
int size = results.size();
for(;index < size;++index) {
list.add(btn = new Button(results.get(index).getString("Title")));
addListener(btn);
}
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Err", "Server is not responding.", "OK", null);
}
listMenu.add(list);
listMenu.add(back);
listMenu.show();
loading.dispose();
back.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
new StateMachine("/theme");
}
});
}
This code basically is querying data from the Database then setting its results into buttons then added to a Container. My question is how to implement a search filter to my Container? I've seen FilterProxyListModel<T> but not sure if ListModel<T> is compatible with Container. I'd appreciate to see an example of search filter implementation in my code.

FilterProxyListModel is for List which we don't recommend anymore. There is a full sample of searching a container here. It uses MultiButton but using Button would work just as well:
hi.getToolbar().addSearchCommand(e -> {
String text = (String)e.getSource();
if(text == null || text.length() == 0) {
// clear search
for(Component cmp : hi.getContentPane()) {
cmp.setHidden(false);
cmp.setVisible(true);
}
hi.getContentPane().animateLayout(150);
} else {
text = text.toLowerCase();
for(Component cmp : hi.getContentPane()) {
Button mb = (Button)cmp;
String line1 = mb.getText();
boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1;
mb.setHidden(!show);
mb.setVisible(show);
}
hi.getContentPane().animateLayout(150);
}
}, 4);

Related

RadioGroupButton deselect value when button is clicked in Vaadin 14

I've been working on an online exam project and currently adding some multiple choice feature. My problem is, each time I moved to the next question the value from the previous radiogroupbutton is removed/deselect. But still the assigned value of the object is present.
I tried removing/adding the component as well, still the selected value for the RadioGroupButton is missing.
public class TestQuestionaire extends Dialog {
TQCoverageService tqcs = new TQCoverageServiceImpl();
CellItemService cis = new CellItemServiceImpl();
ItemKeyService iks = new ItemKeyServiceImpl();
VerticalLayout mainLayout;
TQCoverage tqCoverage;
List<CellItem> ciList = new ArrayList();
Map<CellItem, CellItemOption> cellItemAnswerMap = new HashMap();
CellItem cellItem;
Binder<CellItem> binder;
private int tqCoverageId;
private int cellItemIndex = 0;
private int cellItemIndexSize = 0;
private int score = 0;
Button next;
Button prev;
String stem;
Paragraph stemHolder;
RadioButtonGroup<CellItemOption> cioGroup;
public TestQuestionaire(int tqCoverageId) {
this.tqCoverageId = tqCoverageId;
tqCoverage = tqcs.findTQCoverage(tqCoverageId);
cellItemIndexSize = tqCoverage.getTotalItems();
for(TQItems tqi : tqcs.findAllTQItems(tqCoverageId)){
cellItem = cis.findCellItem(tqi.getCellItemId());
List<CellItemOption> cioList = cis.findAllItemOptions(tqi.getCellItemId());
cellItem.setCellItemOptionList(cioList);
ItemKey ik = iks.findItemKey(tqi.getItemKeyId());
cellItem.setItemKey(ik);
TQAnswerKey tqak = tqcs.findTQAnswerKeyByTQItem(tqi.getTqItemId());
cellItem.setTQAnswerKey(tqak);
cellItemAnswerMap.put(cellItem, new CellItemOption());
ciList.add(cellItem);
}
stemHolder = new Paragraph();
stemHolder.setWidthFull();
stemHolder.getStyle().set("font-weight", "500");
Hr hr = new Hr();
hr.setWidthFull();
cioGroup = new RadioButtonGroup<>();
cioGroup.setRenderer(new TextRenderer<>(CellItemOption::getCellItemOption));
cioGroup.addThemeVariants(RadioGroupVariant.LUMO_VERTICAL);
cioGroup.addValueChangeListener(event -> {
if(event.getValue() == null){
return;
}
if(!event.getValue().equals(event.getOldValue())){
cellItemAnswerMap.replace(getCellItem(), event.getValue());
}
});
mainLayout = new VerticalLayout(stemHolder, hr, cioGroup);
mainLayout.setWidth("600px");
hr = new Hr();
hr.setWidthFull();
mainLayout.add(hr);
binder = new Binder();
binder.forField(cioGroup)
.bind(CellItem::getCellItemOption, CellItem::setCellItemOption);
changeCellItem();
prev = new Button(VaadinIcon.BACKWARDS.create());
prev.addClickListener(event -> {
cellItemIndex--;
if(cellItemIndex == 0){
prev.setEnabled(false);
next.setEnabled(true);
} else {
prev.setEnabled(true);
next.setEnabled(true);
}
changeCellItem();
});
prev.setEnabled(false);
next = new Button(VaadinIcon.FORWARD.create());
next.getStyle().set("margin-left", "490px");
next.addClickListener(event -> {
cellItemIndex++;
if((cellItemIndex + 1) == cellItemIndexSize){
next.setEnabled(false);
prev.setEnabled(true);
} else {
next.setEnabled(true);
prev.setEnabled(true);
}
changeCellItem();
});
//this button is only to test if the current value for radiobuttongroup is removed/deselect when clicked!!
mainLayout.add(new Button("TEST", event -> {
changeCellItem();
}));
HorizontalLayout buttons = new HorizontalLayout(prev, next);
buttons.setWidthFull();
buttons.setJustifyContentMode(FlexComponent.JustifyContentMode.START);
mainLayout.add(buttons);
add(mainLayout);
open();
}
//refresh components for new/previous set if item
private void changeCellItem(){
stemHolder.removeAll();
cellItem = ciList.get(getCellItemIndex());
stem = cellItem.getItem().replace("{key}", cellItem.getItemKey().getItemKey());
stemHolder.add(stem);
cioGroup.clear();
cioGroup.setItems(cellItem.getCellItemOptionList());
cellItem.setCellItemOption(cellItemAnswerMap.get(cellItem));
binder.readBean(cellItem);
//binder.setBean(cellItem);
}
public TQCoverage getTQCoverage() {
return tqCoverage;
}
public CellItem getCellItem() {
return cellItem;
}
public int getCellItemIndex() {
return cellItemIndex;
}
public int getCellItemIndexSize() {
return cellItemIndexSize;
}
}

Tree View JavaFX Memory out of Space

I have created javaFX tree with custom Objects (SystemNode).
Tree Items has graphics: check-box and image icon which I have set through updateItems() method.
Whenever I expand or collapse Item in tree ,twice or thrice I get JAVA HEAP MEMORY OUT OF SPACE and whole UI hangs UP.
PS: updateItems() method is invoked every time I expand or collapse tree node
I have tried adding event handlers but they didn't work.
Can anyone give some solutions.
Here is how I set cellFactory :
treeView_technicalAreas.setCellFactory(Util.getTreeCellFactory());
Here is code for cell factory:
public static Callback<TreeView<SystemNode>, TreeCell<SystemNode>> getTreeCellFactory() {
Callback<TreeView<SystemNode>, TreeCell<SystemNode>> callback = new Callback<TreeView<SystemNode>, TreeCell<SystemNode>>() {
#Override
public TreeCell<SystemNode> call(TreeView<SystemNode> p) {
TreeCell<SystemNode> cell = new TreeCell<SystemNode>() {
#Override
protected void updateItem(SystemNode t, boolean isEmpty) {
super.updateItem(t, isEmpty); //To change body of generated methods, choose Tools | Templates.
if (!isEmpty) {
System.out.println("util call back : " + t.getSystem().getName());
setText(t.getSystem().getName());
HBox hBox = new HBox();
CheckBox checkBox = new CheckBox();
checkBox.setSelected(t.getSelected());
checkBox.selectedProperty().bindBidirectional(t.getSelectedProperty());
hBox.setSpacing(SPACING_BETWEEN_ICON_AND_CHECKBOX);
ImageView imageView_icon = null;
if (t.getSystem().getType() == TYPE.BAREA) {
imageView_icon = new ImageView(Constant.Image_AREAS);
} else if (t.getSystem().getType() == TYPE.AREA) {
imageView_icon = new ImageView(Constant.Image_AREAS);
} else if (t.getSystem().getType() == TYPE.DOCUMENT) {
imageView_icon = new ImageView(Constant.Image_DOCUMENTS);
} else if (t.getSystem().getType() == TYPE.NOUN_NAME) {
imageView_icon = new ImageView(Constant.Image_NOUN_NAME);
} else if (t.getSystem().getType() == TYPE.CHANGE) {
imageView_icon = new ImageView(Constant.Image_DCC);
} else if (t.getSystem().getType() == TYPE.TASK) {
imageView_icon = new ImageView(Constant.Image_TASK);
}
hBox.getChildren().addAll(checkBox, imageView_icon);
setGraphic(hBox);
}
}
};
return cell;
}
};
return callback;
}

How to get radiobutton value?

Here is my code
//unlock
rbtnUTrue = new RadioButton("rbtnUnlock", "True");
rbtnUFalse = new RadioButton("rbtnUnlock", "False");
hp = new HorizontalPanel();
hp.add(rbtnUTrue);
hp.add(rbtnUFalse);
vlc.add(new FieldLabel(hp, "Has Unlock"), new VerticalLayoutData(1, -1, new Margins(10)));
if (rbtnUTrue.isChecked()) {
dummy_u = 1;
} else if (rbtnUFalse.isChecked()) {
dummy_u = 0;
}
but it always says that I clicked the false button
To answer your question: "how to get data from radio buttons in gwt?":
radioButton.getValue(); or radioButton.isChecked();
I'm not sure what do you want to achieve with the if-clause. If you need an initial value then just set it.
What you probably want to do is to register when the button is clicked:
rbtnUTrue.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
#Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
if (rbtnUTrue.isChecked()) {
dummy_u = 1;
} else if (rbtnUFalse.isChecked()) {
dummy_u = 0;
}
}
});

ArrayList , JFrame, JLabel

I am trying to create and simple program that has the user input 4 fields using the JFrame and textfields. Save those into a class. Put that class into an ArrayList (So they have the option to delete / or add more "classes" to it later). Then display all the contents of the ArrayList on one Frame.
I got the four fields to work I believe , but the part where the ArrayList contents are supposed to be displayed is not working ( I get a blank frame ).
this is my add into the arrayList ..
public void newEntryFrame()
{
JFrame entryFrame = new JFrame("Passafe");
entryFrame.setVisible(true);
entryFrame.setSize(500, 500);
entryFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
entryFrame.setLocationRelativeTo(null);
entryFrame.setLayout(new FlowLayout());
header.setFont(new Font("Serif", Font.BOLD, 16));
entryFrame.add(header);
entryFrame.add(nameLabel);
entryFrame.add(nametf);
entryFrame.add(usernameLabel);
entryFrame.add(usernametf);
entryFrame.add(passwordLabel);
entryFrame.add(passwordtf);
entryFrame.add(descriptionLabel);
entryFrame.add(descriptiontf);
entryFrame.add(enterButton);
enterButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
JOptionPane.showMessageDialog(null, "SAVED");
}
else if(source == okButton)
{
JOptionPane.showMessageDialog(null, "Ok Button Works");
}
}
this is what I have to display the arrayList.
public void viewEntryFrame()
{
JFrame viewFrame = new JFrame("Passafe");
viewFrame.setSize(500, 500);
viewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
viewFrame.setLocationRelativeTo(null);
viewFrame.setLayout(new FlowLayout());
viewFrame.add(listHeader);
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
viewFrame.add(okButton);
okButton.addActionListener(this);
viewFrame.setVisible(true);
}
I might be doing this completely wrong if so could you point me in the right direction.
I don't think you ever called setContentPane() A JFrame has only one component in the main part of it. You have to create a JPanel to which you can add all of the components you want, then add that to your JFrame.
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(/**whatever you want in your JFrame**/);
//...
panel.add(/**whatever you want in your JFrame**/);
frame.setContentPane(panel);
You never seem to be adding anything to your entries list...
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
// Nope, nothing here...
JOptionPane.showMessageDialog(null, "SAVED");
}
//...
}
Also, this is very dangrouos...
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Rather the relying on the actual side of the ArrayList, you relying on some other variable, which may or may not equal the actual size, instead you should be using ArrayList#size, for example
for(int i = 0; i < entries.size(); ++i)
{
newEntry tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Or if you're using Java 5+...
for(newEntry tempView : enties)
{
viewFrame.add(tempView.display);
}

Setting component focus in JOptionPane.showOptionDialog()

In order to have custom button captions in an input dialog, I created the following code:
String key = null;
JTextField txtKey = new JTextField();
int answerKey = JOptionPane.showOptionDialog(this, new Object[] {pleaseEnterTheKey, txtKey}, decryptionKey, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] {okCaption, cancelCaption}, okCaption);
if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
key = txtKey.getText();
}
How can I move the focus (cursor) to the text field as the dialog is displayed?
UPDATE
This does not work for me, I mean the textfield has no focus:
OS: Fedora - Gnome
public class Test {
public static void main(String[] args) {
String key = null;
JTextField txtKey = new JTextField();
txtKey.addAncestorListener(new RequestFocusListener());
int answerKey = JOptionPane.showOptionDialog(null, new Object[]{"Please enter the key:", txtKey}, "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"OKKK", "CANCELLLL"}, "OKKK");
if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
key = txtKey.getText();
}
}
}
Dialog Focus shows how you can easily set the focus on any component in a modal dialog.
public static String getPassword(String title) {
JPanel panel = new JPanel();
final JPasswordField passwordField = new JPasswordField(10);
panel.add(new JLabel("Password"));
panel.add(passwordField);
JOptionPane pane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
#Override
public void selectInitialValue() {
passwordField.requestFocusInWindow();
}
};
pane.createDialog(null, title).setVisible(true);
return passwordField.getPassword().length == 0 ? null : new String(passwordField.getPassword());
}
passing null as the last argument is the solution. At least it worked for me.
String key = null;
JTextField txtKey = new JTextField();
int answerKey = JOptionPane.showOptionDialog(this, new Object[] {pleaseEnterTheKey, txtKey}, decryptionKey, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] {okCaption, cancelCaption}, null);
if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
key = txtKey.getText();
}
But even this solution bring another problem:
Focused component and Default component are different. Default component or default button is the button which its onclick fires if you press ENTER KEY.The last argument define the default component which gets the focus too and passing null brings the problem of having no default component!
I solved it for my code this way but I guess it is not a best practice:
String key = null;
final JTextField txtKey = new JTextField();
txtKey.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == 10) { //enter key
Container parent = txtKey.getParent();
while (!(parent instanceof JOptionPane)) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
final JPanel pnlBottom = (JPanel) pane.getComponent(pane.getComponentCount() - 1);
for (int i = 0; i < pnlBottom.getComponents().length; i++) {
Component component = pnlBottom.getComponents()[i];
if (component instanceof JButton) {
final JButton okButton = ((JButton)component);
if (okButton.getText().equalsIgnoreCase(okCaption)) {
ActionListener[] actionListeners = okButton.getActionListeners();
if (actionListeners.length > 0) {
actionListeners[0].actionPerformed(null);
}
}
}
}
}
}
});
I had the same problem with the RequestFocusListener() not working on Linux, after following the discussion on http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5018574 I found that adding an invokeLater fixed it for now...
public class RequestFocusListener implements AncestorListener
{
public void ancestorAdded(final AncestorEvent e)
{
final AncestorListener al= this;
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
JComponent component = (JComponent)e.getComponent();
component.requestFocusInWindow();
component.removeAncestorListener( al );
}
});
}
public void ancestorMoved(AncestorEvent e) {}
public void ancestorRemoved(AncestorEvent e) {}
}
The trick is to (a) use an AncestorListener on the text component to request focus, and when the focus is lost again (given to the default button), ask for focus a second time using a FocusListener on the text component (but don't keep asking for focus after that):
final JPasswordField accessPassword = new JPasswordField();
accessPassword.addAncestorListener( new AncestorListener()
{
#Override
public void ancestorRemoved( final AncestorEvent event )
{
}
#Override
public void ancestorMoved( final AncestorEvent event )
{
}
#Override
public void ancestorAdded( final AncestorEvent event )
{
// Ask for focus (we'll lose it again)
accessPassword.requestFocusInWindow();
}
} );
accessPassword.addFocusListener( new FocusListener()
{
#Override
public void focusGained( final FocusEvent e )
{
}
#Override
public void focusLost( final FocusEvent e )
{
if( isFirstTime )
{
// When we lose focus, ask for it back but only once
accessPassword.requestFocusInWindow();
isFirstTime = false;
}
}
private boolean isFirstTime = true;
} );
Better way to do it: create the JOptionPane using the constructor, override selectInitialValue to set the focus, and then build the dialog using createDialog.
// Replace by the constructor you want
JOptionPane pane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
#Override
public void selectInitialValue() {
textArea.requestFocusInWindow();
}
};
JDialog dialog = pane.createDialog(owner, title);
dialog.setVisible(true);
Try this
String key = null;
JTextField txtKey = new JTextField();
Object[] foo = {pleaseEnterTheKey, txtKey};
int answerKey = JOptionPane.showOptionDialog(this, foo, decryptionKey, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] {okCaption, cancelCaption}, foo[1]);
if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
key = txtKey.getText();
}
I found a solution !
Very primitive, but works.
Just jump to the field by java.awt.Robot using key "Tab".
I've created utils method calls "pressTab(..)"
For example:
GuiUtils.pressTab(1); <------------- // add this method before popup show
int result = JOptionPane.showConfirmDialog(this, inputs, "Text search window", JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION)
{
}
If you should press multiple times on "Tab" to get your Component you can use below method:
GUIUtils.pressTab(3);
Definition:
public static void pressTab(int amountOfClickes)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
Robot robot = new Robot();
int i = amountOfClickes;
while (i-- > 0)
{
robot.keyPress(KeyEvent.VK_TAB);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_TAB);
}
}
catch (AWTException e)
{
System.out.println("Failed to use Robot, got exception: " + e.getMessage());
}
}
});
}
If your Component location is dynamic, you can run over the while loop without limitation, but add some focus listener on the component, to stop the loop once arrived to it.

Categories