Relayout of Text field that is being editted scrambles text in simulator - codenameone

I want the user to enter an artbitrary number of keywords (or keyphrases). To this end, I have a row of TextFields, one for each keyword. I add a new TextField to the row when all existing ones have text in them, so the user can enter another keyword.
The addition of a new TextField happens when a character is added to the last empty TextField; i.e. that TextField is being editted when a new TextField is added. Furthermore, the existing TextFields will be moved and resized when adding a new TextField (to make space).
This works fine on Android, but in the simulator it does not. In the similator, the TextField being editted is being moved, but the text being editted is not.
The issue can be replicated using the form below.
Kind regards, Frans.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.codename1.ui.Container;
import com.codename1.ui.Form;
import com.codename1.ui.Label;
import com.codename1.ui.TextArea;
import com.codename1.ui.TextField;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.GridLayout;
public class TextFieldRelayoutForm extends Form
{
public TextFieldRelayoutForm()
{
super("TextField relayout", BoxLayout.y());
add(new Label("Type into the last text field below"));
Strings strings = new Strings("blabla");
strings.setStrings(Arrays.asList("one", "two"));
add(strings);
}
public class Strings extends Container
{
private final String hint;
private final Runnable listener;
public Strings(String hint)
{
this(hint, null);
}
public Strings(String hint, Runnable listener)
{
//TextField.setUseNativeTextInput(false);
this.hint = hint;
this.listener = listener;
addEmptyField();
}
public void setStrings(List<String> strings)
{
removeAll();
for (String string : strings)
{
addComponent(getTextField(string));
}
addEmptyField();
}
private TextField getTextField(String text)
{
TextField field = new TextField("", hint, 20, TextArea.ANY);
field.setText(text);
field.addDataChangedListener((t,i) -> textFieldDataChanged(field));
return field;
}
private void textFieldDataChanged(TextField field)
{
if (!hasEmptyField())
{
addEmptyField();
}
if (listener != null)
{
listener.run();
}
}
private boolean hasEmptyField()
{
for (int i = getComponentCount() - 1; i >= 0; i--)
{
String string = ((TextField)getComponentAt(i)).getText();
if (string.length() == 0)
{
return true;
}
}
return false;
}
private void addEmptyField()
{
addComponent(getTextField(""));
setLayout(new GridLayout(getComponentCount()));
revalidate();
}
public List<String> getStrings()
{
List<String> strings = new ArrayList<>();
for (int i = 0; i < getComponentCount(); i++)
{
String string = ((TextField)getComponentAt(i)).getText();
if (string.length() != 0)
{
strings.add(string);
}
}
return strings;
}
}
}

Editing happens in native code so when you edit we "seamlessly" layout a native text field on top of the lightweight text field and let you edit. I quoted seamlessly as this abstraction leaks on some cases and this is one of them. That's why it's a best practice to use stopEdit/startEditAsync when changing layouts or text field information.
You can read about similar issues in this post https://www.codenameone.com/blog/tip-stop-editing.html
Another possibly better alternative would be to use the action listener. This happens only when editing finished. This means fewer events and when you make changes you won't need to hack. The downside is that a user will need to abandon editing so the new field appears.

Related

SWT+ Jface,tableviewer : How to set combo box in the 3rd column?

Current out put of code is output image
import java.io.Serializable;
import java.util.HashMap;
import java.util.Objects;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.part.ViewPart;
public class Theartview extends ViewPart implements Serializable {
Table table;
private TableViewer tableViewer;
public void createPartControl(Composite parent) {
System.out.println("createPartControl call");
Composite tableComposite = new Composite(parent, SWT.NONE);
TableColumnLayout tableColumnLayout = new TableColumnLayout();
tableComposite.setLayout(tableColumnLayout);
tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
true));
tableViewer = new TableViewer(tableComposite, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL);
tableViewer.setContentProvider(ArrayContentProvider.getInstance());
// TODO viewer.setLabelProvider(new ViewLabelProvider());
table = tableViewer.getTable();
// Table table = tableViewer.getTable();
System.out.println("#############table$$$$$$$$" + table);
table.setHeaderVisible(true);
table.setLinesVisible(true);
String[] titles = { "Threat Name", "Category Name", "Status",
"Priority", "Description", "Justification" };
for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
TableViewerColumn tableViewerColumn = new TableViewerColumn(
tableViewer, SWT.NONE);
TableColumn tblclmn = tableViewerColumn.getColumn();
tableColumnLayout.setColumnData(tblclmn, new ColumnPixelData(200,
true, true));
tblclmn.setText(titles[loopIndex]);
}
}
private static class Dummy {
public String value;
public Dummy(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
#SuppressWarnings("static-access")
public void fillTableRoWData() {
System.out.println("After connection fillTableRoWData call");
System.out.println("No of Connected object = no of fillTableRoWData call ");
if (Connection.Number_Of_Connection != 0) {
// item = new TableItem(table, SWT.NONE);
if (Service.class.isInstance(sourceNode)) {
String id = "S1";
shortDescription = threattypexmltoobject.shortdescription(id,
sourceNode.getName(), targetNode.getName(), null);
category = "Spoofing";
description = threattypexmltoobject.longdescription(id,
sourceNode.getName(), targetNode.getName(), null);
fillRows(shortDescription, category, description);
}
if (Service.class.isInstance(sourceNode)
&& (connectionType == Connection.CONNECTION_DESIGN)) {
String id = "T1";
System.out.println(conn.getConnectionDesign());
shortDescription = threattypexmltoobject.shortdescription(id,
sourceNode.getName(), targetNode.getName(),
conn.getConnectionDesign());
category = "Tampering";
description = threattypexmltoobject.longdescription(id,
sourceNode.getName(), targetNode.getName(),
conn.getConnectionDesign());
fillRows(shortDescription, category, description);
}
}
private void fillRows(String shortdesc, String categ, String descp) {
System.out.println("fillRows call from above method.");
TableItem item = new TableItem(table, SWT.NONE);
// for Threat_Name
item.setText(0, "x");
// For Category_Name
item.setText(1, "y");
// For Status_Name
item.setText(2, "z");
// For Priority_Name
item.setText(3, "a");
// For Descrption_Name
item.setText(4, "b");
// For justification
item.setText(5, "c");
}
public static class FirstValueEditingSupport extends EditingSupport {
private final TableViewer viewer;
private final CellEditor editor;
private final String[] possibleValues = { "Mitigated",
"Not Applicable", "Not Started", "Needs Investigation" };
public FirstValueEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
this.editor = new ComboBoxCellEditor(viewer.getTable(),
possibleValues);
}
#Override
protected CellEditor getCellEditor(Object element) {
return editor;
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
Dummy dummy = (Dummy) element;
int index = 0;
for (int i = 0; i < possibleValues.length; i++) {
if (Objects.equals(possibleValues[i], dummy.getValue())) {
index = i;
break;
}
}
return index;
}
#Override
protected void setValue(Object element, Object value) {
Dummy dummy = (Dummy) element;
int index = (Integer) value;
dummy.setValue(possibleValues[index]);
viewer.update(element, null);
}
}
}
Questions
How to set combo box in the 3rd and 4th column of table viewer. here FirstValueEditingSupport is combobox options value which is display comobo dropdown
String shortDescription, set into 1st and 2ed column how to set ?
in Output image "Status" and "Priority", which is column name of the table where set combo box in the table.
Please only ask one question in a question.
You set the editing support in the TableColumnViewer for the column you want to edit. So for the columns you want to edit do:
tableViewerColumn.setEditingSupport(new FirstValueEditingSupport());
To set the data shown in each column you set a label provider of the column.
tableViewerColumn.setLabelProvider(column label provider);
where the label provider is derived from CellLabelProvider or one of its many subclasses.
Note: NEVER set the table viewer contents by creating TableItems - you must always use a content provider and a setInput call on the table viewer. TableViewer is in complete control of the underlying Table and is free to discard any TableItems you may create. With very few exceptions you should never be looking at the Table or TableItem objects when using TableViewer.
The content provider should provide one object for each row in the table, the column label providers should use this row object to get labels for the individual columns.

CheckBox inside TableCell breaks the traversal order

Consider the following example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class TestCheckBoxTab extends Application {
public void start (Stage stage) {
HBox root = new HBox();
root.getChildren().addAll(new TextField(), new TextField(), new CheckBox(), new TextField());
stage.setScene(new Scene(root));
stage.show();
}
public static void main (String[] args) {
launch();
}
}
Here you can easily use the TAB and SHIFT+TAB commands to traverse through the different controls, and it works properly.
But if you have the same controls inside table cells in a TableView, the CheckBox breaks the traversal order. This is demonstrated in the following example:
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class AlwaysEditableTable extends Application {
public void start(Stage stage) {
TableView<ObservableList<StringProperty>> table = new TableView<>();
table.setEditable(true);
table.getSelectionModel().setCellSelectionEnabled(true);
table.setPrefWidth(505);
// Dummy columns
ObservableList<String> columns = FXCollections.observableArrayList("Column1", "Column2", "Column3", "Column4",
"Column5");
// Dummy data
ObservableList<StringProperty> row1 = FXCollections.observableArrayList(new SimpleStringProperty("Cell1"),
new SimpleStringProperty("Cell2"), new SimpleStringProperty("0"), new SimpleStringProperty("Cell4"),
new SimpleStringProperty("1"));
ObservableList<ObservableList<StringProperty>> data = FXCollections.observableArrayList();
data.add(row1);
for (int i = 0; i < columns.size(); i++) {
final int j = i;
TableColumn<ObservableList<StringProperty>, String> col = new TableColumn<>(columns.get(i));
col.setCellValueFactory(param -> param.getValue().get(j));
col.setPrefWidth(100);
if (i == 2 || i == 4) {
col.setCellFactory(e -> new CheckBoxCell(j));
} else {
col.setCellFactory(e -> new AlwaysEditingCell(j));
}
table.getColumns().add(col);
}
table.setItems(data);
Scene scene = new Scene(table);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
/**
* A cell that contains a text field that is always shown. The text of the
* text field is bound to the underlying data.
*/
public static class AlwaysEditingCell extends TableCell<ObservableList<StringProperty>, String> {
private final TextField textField;
public AlwaysEditingCell(int columnIndex) {
textField = new TextField();
this.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
setGraphic(null);
} else {
setGraphic(textField);
}
});
// The index is not changed until tableData is instantiated, so this
// ensure the we wont get a NullPointerException when we do the
// binding.
this.indexProperty().addListener((obs, oldValue, newValue) -> {
ObservableList<ObservableList<StringProperty>> tableData = getTableView().getItems();
int oldIndex = oldValue.intValue();
if (oldIndex >= 0 && oldIndex < tableData.size()) {
textField.textProperty().unbindBidirectional(tableData.get(oldIndex).get(columnIndex));
}
int newIndex = newValue.intValue();
if (newIndex >= 0 && newIndex < tableData.size()) {
textField.textProperty().bindBidirectional(tableData.get(newIndex).get(columnIndex));
setGraphic(textField);
} else {
setGraphic(null);
}
});
}
}
/**
* A cell containing a checkbox. The checkbox represent the underlying value
* in the cell. If the cell value is 0, the checkbox is unchecked. Checking
* or unchecking the checkbox will change the underlying value.
*/
public static class CheckBoxCell extends TableCell<ObservableList<StringProperty>, String> {
private final CheckBox box;
private ObservableList<ObservableList<StringProperty>> tableData;
public CheckBoxCell(int columnIndex) {
this.box = new CheckBox();
this.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
setGraphic(null);
} else {
setGraphic(box);
}
});
this.indexProperty().addListener((obs, oldValue, newValue) -> {
tableData = getTableView().getItems();
int newIndex = newValue.intValue();
if (newIndex >= 0 && newIndex < tableData.size()) {
// If active value is "1", the check box will be set to
// selected.
box.setSelected(tableData.get(getIndex()).get(columnIndex).equals("1"));
// We add a listener to the selected property. This will
// allow us to execute code every time the check box is
// selected or deselected.
box.selectedProperty().addListener((observable, oldVal, newVal) -> {
if (newVal) {
// If newValue is true the checkBox is selected, and
// we set the corresponding cell value to "1".
tableData.get(getIndex()).get(columnIndex).set("1");
} else {
// Otherwise we set it to "0".
tableData.get(getIndex()).get(columnIndex).set("0");
}
});
setGraphic(box);
} else {
setGraphic(null);
}
});
}
}
}
When pressing TAB while focusing a TextField inside a TableCell, the focus is moved to the next control properly. But if a CheckBox inside a TableCell is focused, the focus is moved to the first Control in the TableView instead of to the next Control. SHIFT+TAB while focusing a CheckBoxwill move the focus to the last control in the TableView. If I add a TextField outside the TableView, SHIFT+TAB while focusing a CheckBox will actually focus that TextField, while TAB behaviour still at least keeps the focus inside the TableView. The CheckBox somehow breaks the traversal order.
This is strange to me since TextField and CheckBox seems to have the same TAB functionality implemented, due to the fact the traversal order is correct in the first example. Something I guess is inherited from the Control class.
Does anybody know anything about this? I tried to look for some kind of EventFilter or listener for the TAB and SHIFT+TAB commands inside the source code of Control, TextField, CheckBox, TextInputControl and even in the Scene source, but I couldn't find it anywhere.
I also tried implementing my own TAB functionality for the CheckBox cell, which ended up raising another issue.
I was struggling a lot with the same issue. I finally avoided it by setting:
checkBox.setFocusTraversable(false);
and
this.setFocusTraversable(false);
on my own implementation of BooleanCell.
The table traverses over editable fields and the Checkbox is always enabled in my implementation. But setting the Checkbox disabled means you have to double click on it to change the value. That would be weird behaviour.

How to temporarily remove items from a ChoiceBox (or maybe a ComboBox)?

I've come across a somewhat perplexing conundrum. I've recently started to figure out how to work with listeners, thanks to some people on here, and I'm trying to find a way to use them in conjunction with choice/comboboxes to do something tricky. What I want to have happen is, when the user makes a selection from one of six linked boxes containing six choices, it removes that option from the other 5 boxes until either A: the option is changed to one of the remaining ones, or B: the option is changed to a null or default setting (to prevent getting "locked in" after picking, or maybe I can just make a reset button for that purpose). I've got a ChangeListener on each choicebox now, but various things I've tried (switch statements, assigning each answer a boolean, various attempts to use .getItems().remove() in vain, I've been at this a while) Has anyone figured or seen an example of how this could be done? Thanks in advance for any advice, you guys(and gals) have helped me learn by leaps and bounds these past few weeks.
if you want something like this:
I had this code in my program. it is nor really efficient, but was fine for me on a small set of data.
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ChoiceBox;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ConnectedComboBox<T> implements ChangeListener<T> {
private ObservableList<T> items;
private List<ChoiceBox<T>> comboBoxList = new ArrayList<>();
public ConnectedComboBox(ObservableList<T> items){
this.items = items;
if (this.items == null) this.items = FXCollections.observableArrayList();
}
public void addComboBox(ChoiceBox<T> comboBox){
comboBoxList.add(comboBox);
comboBox.valueProperty().addListener(this);
updateSelection();
}
public void removeComboBox(ChoiceBox<T> comboBox){
comboBoxList.remove(comboBox);
comboBox.valueProperty().removeListener(this);
updateSelection();
}
// this boolean needed because we can set combobox Value in updateSelection()
// this will trigger a value listener and update selection one more time => stack overflow
// this behavior occurs only if we have more than one equal item in source ObservableList<T> items list.
private boolean updating = false;
private void updateSelection() {
if (updating) return;
updating = true;
List<T> availableChoices = items.stream().collect(Collectors.toList());
for (ChoiceBox<T> comboBox: comboBoxList){
if (comboBox.getValue()!= null) {
availableChoices.remove(comboBox.getValue());
}
}
for (ChoiceBox<T> comboBox: comboBoxList){
T selectedValue = comboBox.getValue();
ObservableList<T> items = comboBox.getItems();
items.setAll(availableChoices);
if (selectedValue != null) {
items.add(selectedValue);
comboBox.setValue(selectedValue);
}
}
updating = false;
}
#Override
public void changed(ObservableValue<? extends T> observable, T oldValue, T newValue) {
updateSelection();
}
}
And here is how you use it:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class MainFX extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
HBox root = new HBox();
root.setSpacing(10);
ObservableList<String> values = FXCollections.observableArrayList("One", "Two", "Three", "Four","Five");
ChoiceBox<String> combo1 = new ChoiceBox<>();
combo1.setPrefWidth(100);
ChoiceBox<String> combo2 = new ChoiceBox<>();
combo2.setPrefWidth(100);
ChoiceBox<String> combo3 = new ChoiceBox<>();
combo3.setPrefWidth(100);
root.getChildren().addAll(combo1,combo2,combo3);
ConnectedComboBox<String> connectedComboBox = new ConnectedComboBox<>(values);
connectedComboBox.addComboBox(combo1);
connectedComboBox.addComboBox(combo2);
connectedComboBox.addComboBox(combo3);
primaryStage.setScene(new Scene(root,600,600));
primaryStage.show();
}
public static void main(String[] args){
launch(args);
}
}

How I can stop an animated GIF in JavaFX?

I want to use an animated GIF in my project, but I dont know how I can stop the loop animation. I mean, I want the GIF to play 1 time only.
Thanks!
I haven't done GIF animation, wasn't even aware that JavaFX would have methods for starting and stopping them. If you wish to do ANY animation using images, I rather suggest you do it frame by frame yourself. This way you have full control over it and you can have more than just 256 colors in your image.
I read a very good article about Creating a Sprite Animation with JavaFX in Mike's blog.
It's very easy to do. You simply extend the Transition class, add an ImageView to it and implement the Transition's Interpolate method.
Edit: oh, and by the way, GIFs have a loop flag which tells them to either play in a loop or not to play in a loop. In other words: In theory you could modify the GIF file's loop property. In theory only, because I just tried with specifying to play only once and in JavaFX it still played in an endless loop while in FireFox it played once. By the way, JavaFX doesn't seem to support animated PNGs (APNG) which would support more than 256 colors. So the automatic image animation capabilities are very limited. Best to do the animation by yourself.
I hope someone comes up with something better, but here's an example code about how you could get full control over your gif.
import java.awt.image.BufferedImage;
import java.net.URISyntaxException;
import javafx.animation.Interpolator;
import javafx.animation.Transition;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
* Requires GifDecoder from here: http://www.java2s.com/Code/Java/2D-Graphics-GUI/DecodesaGIFfileintooneormoreframes.htm
*/
public class AnimatedGifDemo extends Application {
#Override
public void start(Stage primaryStage) throws URISyntaxException {
HBox root = new HBox();
// TODO: provide gif file, ie exchange banana.gif with your file
Animation ani = new AnimatedGif(getClass().getResource("banana.gif").toExternalForm(), 1000);
ani.setCycleCount(10);
ani.play();
Button btPause = new Button( "Pause");
btPause.setOnAction( e -> ani.pause());
Button btResume = new Button( "Resume");
btResume.setOnAction( e -> ani.play());
root.getChildren().addAll( ani.getView(), btPause, btResume);
Scene scene = new Scene(root, 1600, 900);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public class AnimatedGif extends Animation {
public AnimatedGif( String filename, double durationMs) {
GifDecoder d = new GifDecoder();
d.read( filename);
Image[] sequence = new Image[ d.getFrameCount()];
for( int i=0; i < d.getFrameCount(); i++) {
WritableImage wimg = null;
BufferedImage bimg = d.getFrame(i);
sequence[i] = SwingFXUtils.toFXImage( bimg, wimg);
}
super.init( sequence, durationMs);
}
}
public class Animation extends Transition {
private ImageView imageView;
private int count;
private int lastIndex;
private Image[] sequence;
private Animation() {
}
public Animation( Image[] sequence, double durationMs) {
init( sequence, durationMs);
}
private void init( Image[] sequence, double durationMs) {
this.imageView = new ImageView(sequence[0]);
this.sequence = sequence;
this.count = sequence.length;
setCycleCount(1);
setCycleDuration(Duration.millis(durationMs));
setInterpolator(Interpolator.LINEAR);
}
protected void interpolate(double k) {
final int index = Math.min((int) Math.floor(k * count), count - 1);
if (index != lastIndex) {
imageView.setImage(sequence[index]);
lastIndex = index;
}
}
public ImageView getView() {
return imageView;
}
}
}
It provides a pause/resume button for testing. What you need in addition is the Gif Decoder code and an animated banana.gif.

AWT repaint issues

I am trying to make some small additions to some old java code that does not support swing. I need to add a small dialog that contains a panel which has a checkbox and a couple text fields. When the user clicks on the checkbox I want to disable or enable the checkboxes. This part seems to work well but the text fields are not properly getting redrawn. When I click the checkbox the fields do not appear to become enabled but if I then click on the panel or the text field you see that they are enabled (the opposite is also true, when I un-check the checkbox the fields still look enabled until you try and click on them and they become ghosted and do not become selected). I use the setEnabled(boolean) to set the status of the fields. I have tried calling repaint and validate on both the fields and the panel after changing the status and this does not seem to work. I have also tried to have the fields request focus and this did not work. Anyone have any other ideas?
//The class that contains all of this is of type Window
//Declaration of the components
private Panel _inputPanel;
private TextField min , max;
//This method adds to two text fields
public void addMinMaxtextFields(String min, String max) {
TextField minField = new TextField(min);
TextField maxField = new TextField(max);
this.min = minField;
this.max = maxField;
this.min.setEnabled(false);
this.max.setEnabled(false);
_inputPanel.add(minField);
_inputPanel.add(maxField);
}
//listener for the checkbox
public void itemStateChanged(ItemEvent e) {
Component[] components = _inputPanel.getComponents();
min.setEnabled(!min.isEnabled());
min.setVisible(true);
min.validate();
min.repaint();
_inputPanel.validate();
_inputPanel.repaint();
this.pack();
this.setSize(this.getWidth(), this.getHeight());
this.validate();
this.repaint();
/* do nothing */
}
You will need to call update(Graphics g) on Panel after setEnabled(boolean) is called.
check :
http://download-llnw.oracle.com/javase/1.4.2/docs/api/java/awt/Container.html#update(java.awt.Graphics)
I tried following code (built from code you provided), Its working fine.
import java.awt.Checkbox;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class CheckUI extends Dialog implements ItemListener {
// The class that contains all of this is of type Window
// Declaration of the components
private Panel _inputPanel;
private TextField min, max;
private Checkbox cb;
public CheckUI(Frame owner, boolean modal) {
super(owner, modal);
_inputPanel = new Panel();
this.add(_inputPanel);
addMinMaxtextFields("min", "max");
}
// This method adds to two text fields
public void addMinMaxtextFields(String min, String max) {
cb = new Checkbox();
cb.addItemListener(this);
TextField minField = new TextField(min);
TextField maxField = new TextField(max);
this.min = minField;
this.max = maxField;
this.min.setEnabled(false);
this.max.setEnabled(false);
_inputPanel.add(minField);
_inputPanel.add(maxField);
_inputPanel.add(cb);
}
// listener for the checkbox
public void itemStateChanged(ItemEvent e) {
Component[] components = _inputPanel.getComponents();
min.setEnabled(!min.isEnabled());
min.setVisible(true);
min.validate();
min.repaint();
_inputPanel.validate();
_inputPanel.repaint();
this.pack();
this.setSize(this.getWidth(), this.getHeight());
this.validate();
this.repaint();
/* do nothing */
}
/**
* #param args
*/
public static void main(String[] args) {
Frame parent = new Frame();
parent.setVisible(true);
parent.setExtendedState(Frame.MAXIMIZED_BOTH);
parent.pack();
CheckUI ui = new CheckUI(parent, true);
ui.pack();
ui.setVisible(true);
}
}

Resources