How to create multiple checkbox in canvas - java-me

I get trouble when I try to create a check box in canvas.
My checkbox works well but I don't know how to store value of each item, that mean when user check row 1 , and then they move to another row check box still check row 1, and when user check row 1 and 2 and move to another row, check box will check row 1 and 2.
But I can't find out solution for this problem

modify your code to use selectTodelete as boolean array instead of int, about like shown below
// ...initialization of DataList
boolean[] selectTodelete = new boolean[2]; // instead of int
{ selectTodelete[0] = selectTodelete[1] = false; } // init array
Command editCommand, backCommand,selectCmd, unselectCmd,selectAll;
//...
protected void paint(Graphics g) {
//...
for(int i =0 ; i<countRow; i++ ){
//draw background
//...
if(selectTodelete[i]){ // was selectTodelete == 1
//draw select dot at location for row 'i'
//...
}
// remove: you don't need that anymore: if(selectTodelete == 2) {
//draw select dot...
//}
// draw a checkbox before each item
// ...
}
}
public void commandAction(Command c, Displayable d) {
//...
if(c == selectCmd){
selectTodelete[selectedItem] = true;
}
if(c== unselectCmd){
selectTodelete[selectedItem] = false;
}
if(c == selectAll){
selectTodelete[0] = selectTodelete[1] = true;
}
repaint();
}
//...
}
update - answer to question in comments
I want to get RCID fit to checked it mean when row was checked I can get this id and when I use delete command it will delete all rows were checked
For that, you can expose selectTodelete for use outside of its class with getter, or, better yet, with method like below...
boolean isSelected(int elementNum) {
return elementNum >= 0 && elementNum < selectTodelete.length
&& selectTodelete[elementNum];
} // modelled after javax.microedition.lcdui.Choice.isSelected
...information exposed like that can be further used anywhere when you need it to deal with RCID, like eg in method below:
Vector useSelection(DataList dataList, DataStore[][] ds) {
Vector result = new Vector();
int count = ds.length;
for(int i = 0; i < count; i++ ) {
if (!dataList.isSelected(i)) {
continue; // skip non selected
}
System.out.println("RCID selected: [" + ds[i][5].cellText + "]");
result.addElement(ds[i][5]);
}
return result;
}

Related

How to have different color brushes using multi touch?

I am trying to make it so each finger on the screen has a different color as it paints its path. I am using pointers to create the path and toyed with assigning the pointer IDs a different color per number but no result. In the code below I am trying to make the first finger blue then when another finger begins drawing it would turn red. Currently the code makes all the paint blue but when 3 fingers are on the screen it all changes red. Any help is appreciated thank you
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(idColor == 1)
mFingerPaint.setColor(Color.BLUE);
if(idColor == 2)
mFingerPaint.setColor(Color.RED);
for (Path completedPath : mCompletedPaths) {
canvas.drawPath(completedPath, mFingerPaint);
}
for (Path fingerPath : mFingerPaths) {
if (fingerPath != null) {
canvas.drawPath(fingerPath, mFingerPaint);
}
}
}
public boolean onTouchEvent(MotionEvent event) {
int pointerCount = event.getPointerCount();
int cappedPointerCount = pointerCount > MAX_FINGERS ? MAX_FINGERS : pointerCount;
// get pointer index from the event object
int actionIndex = event.getActionIndex();
// get masked (not specific to a pointer) action
int action = event.getActionMasked();
// get pointer ID
int id = event.getPointerId(actionIndex);
idColor = id;
if ((action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) && id < MAX_FINGERS)
{
mFingerPaths[id] = new Path();
mFingerPaths[id].moveTo(event.getX(actionIndex), event.getY(actionIndex));
}
else if ((action == MotionEvent.ACTION_POINTER_UP || action == MotionEvent.ACTION_UP) && id < MAX_FINGERS)
{
mFingerPaths[id].setLastPoint(event.getX(actionIndex), event.getY(actionIndex));
mCompletedPaths.add(mFingerPaths[id]);
mFingerPaths[id].computeBounds(mPathBounds, true);
invalidate((int) mPathBounds.left, (int) mPathBounds.top, (int) mPathBounds.right, (int) mPathBounds.bottom);
mFingerPaths[id] = null;
}
for(int i = 0; i < cappedPointerCount; i++) {
if(mFingerPaths[i] != null)
{
int index = event.findPointerIndex(i);
mFingerPaths[i].lineTo(event.getX(index), event.getY(index));
mFingerPaths[i].computeBounds(mPathBounds, true);
invalidate((int) mPathBounds.left, (int) mPathBounds.top, (int) mPathBounds.right, (int) mPathBounds.bottom);
}
}
return true;
}
}

How can I perform indexing in datagridview in c# .net

I want to show only few rows in DataGridview (like 1 to 10) and remaining are shown on button click..
so How can I Perform this operation..
If you have all data loaded (that means you are not doing paging on DB side for example) then keep track of page;
private int page = 0;
protected void ShowNextResults_Click(object sender, EventArgs e)
{
page++;
dataGridView1.CurrentCell = null; //required to control row visibility as we cannot hide current cell
int from = page * 10;
int to = from + 10;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (i >= from || i < to)
{
dataGridView1.Rows[i].Visible = true;
}
else
{
dataGridView1.Rows[i].Visible = false;
}
}
}
This traverse results forward but it should be very easy to implement backwards moving.

How can I correct the error "Cross-thread operation not valid"?

This following code gives me the error below . I think I need "InvokeRequired" . But I don't understand how can I use?
error:Cross-thread operation not valid: Control 'statusBar1' accessed from a thread other than the thread it was created on.
the code :
public void CalculateGeneration(int nPopulation, int nGeneration)
{
int _previousFitness = 0;
Population TestPopulation = new Population();
for (int i = 0; i < nGeneration; i++)
{
if (_threadFlag)
break;
TestPopulation.NextGeneration();
Genome g = TestPopulation.GetHighestScoreGenome();
if (i % 100 == 0)
{
Console.WriteLine("Generation #{0}", i);
if ( ToPercent(g.CurrentFitness) != _previousFitness)
{
Console.WriteLine(g.ToString());
_gene = g;
statusBar1.Text = String.Format("Current Fitness = {0}", g.CurrentFitness.ToString("0.00"));
this.Text = String.Format("Sudoko Grid - Generation {0}", i);
Invalidate();
_previousFitness = ToPercent(g.CurrentFitness);
}
if (g.CurrentFitness > .9999)
{
Console.WriteLine("Final Solution at Generation {0}", i);
statusBar1.Text = "Finished";
Console.WriteLine(g.ToString());
break;
}
}
}
}
Easiest for reusability is to add a helper function like:
void setstatus(string txt)
{
Action set = () => statusBar1.Text = txt;
statusBar1.Invoke(set);
}
Or with the invokerequired check first:
delegate void settextdelegate(string txt);
void setstatus(string txt)
{
if (statusBar1.InvokeRequired)
statusBar1.Invoke(new settextdelegate(setstatus), txt);
else
statusBar1.Text = txt;
}
Either way the status can then be set like
setstatus("Finished");
For completeness I should add that even better would be to keep your calculating logic separated from your form and raise a status from within your calculating functionality that can be hanled by the form, but that could be completely out of scope here.

Changing colors in xamDataGrid cells

I have xamDataGrid bound to DataTable where first column contains reference values. Coloring of all other columns depends on whether the value in cells is or isn't equal to the value of reference column. The logic uses converter.
What I want to achieve is when I move another column to the 1st position, it will become the reference column and the colors in all other columns should change.
I'm listening to FieldPositionChanged event and invalidating the grid layout, but it does not work:
grid.UpdateLayout();
grid.InvalidateVisual();
The breakpoint in converter is hit but not for all records (only 2 or 3).
If you set the CellValuePresenterStyle when the fields move they should update correctly. The following logic will do this:
void XamDataGrid1_FieldPositionChanged(object sender, Infragistics.Windows.DataPresenter.Events.FieldPositionChangedEventArgs e)
{
FieldLayout layout = e.Field.Owner;
Field first = null;
foreach (Field f in layout.Fields)
{
if (f.ActualPosition.Column == 0)
first = f;
}
if (first != null)
{
SetCellValuePresenterStyle(e.Field.Owner, first);
}
}
void XamDataGrid1_FieldLayoutInitialized(object sender, Infragistics.Windows.DataPresenter.Events.FieldLayoutInitializedEventArgs e)
{
SetCellValuePresenterStyle(e.FieldLayout, e.FieldLayout.Fields[0]);
}
void SetCellValuePresenterStyle(FieldLayout layout, Field sourceField)
{
Binding sourceValueBinding = new Binding("DataItem[" + sourceField.Name + "]");
foreach (Field f in layout.Fields)
{
if (f != sourceField)
{
Style cellValuePresenterStyle = new Style(typeof(CellValuePresenter));
Binding compareValueBinding = new Binding("DataItem[" + f.Name + "]");
MultiBinding styleBinding = new MultiBinding();
styleBinding.Bindings.Add(sourceValueBinding);
styleBinding.Bindings.Add(compareValueBinding);
styleBinding.Converter = new EqualMultiValueConverter();
DataTrigger trigger = new DataTrigger();
trigger.Value = true;
trigger.Binding = styleBinding;
cellValuePresenterStyle.Triggers.Add(trigger);
Setter backgroundSetter = new Setter(Control.BackgroundProperty, Brushes.Green);
trigger.Setters.Add(backgroundSetter);
f.Settings.CellValuePresenterStyle = cellValuePresenterStyle;
}
else
{
f.Settings.CellValuePresenterStyle = null;
}
}
}

Is there a way to use normal ASCII characters (like a comma) as wxWidgets menu accelerators?

I want a few menu entries that show accelerators that are normal keys, like the space-bar or comma key, but I don't want wxWidgets to make those accelerators itself (because then they can't be used anywhere in the program, including in things like edit boxes).
Unfortunately, wxWidgets insists on always making anything it recognizes in that column into an accelerator under its control, and simply erases anything it doesn't recognize.
I'm looking for some way to either put arbitrary text into the accelerator column (which I don't think exists, I've looked at the source code), or get 'hold of the accelerator table used for the menus so I can modify it myself (haven't found it yet). Can anyone point me in the right direction?
You can try wxKeyBinder. It allows you to bind hotkeys to commands (usually menu entries), save/load/add/remove/modify ... them easily
I couldn't find a way to access the menu's accelerator keys directly, but modifying the accelerator menu text works just as well. Here's the code I came up with:
In a header file:
class accel_t {
public:
// If idcount == -1, idlist must be null or terminated with a -1 entry.
accel_t(): mMenu(0) { }
accel_t(wxMenuBar *m, int *idlist = 0, int idcount = -1);
void reset(wxMenuBar *m, int *idlist = 0, int idcount = -1);
void restore() const;
void remove() const;
private: //
struct accelitem_t {
accelitem_t(int _id, wxAcceleratorEntry _key): id(_id), hotkey(_key) { }
int id;
wxAcceleratorEntry hotkey;
};
typedef std::vector<accelitem_t> data_t;
void noteProblemMenuItems(wxMenu *m);
static bool isProblemAccelerator(wxAcceleratorEntry *a);
wxMenuBar *mMenu;
data_t mData;
};
In a cpp file:
accel_t::accel_t(wxMenuBar *m, int *idlist, int idcount) {
reset(m, idlist, idcount);
}
void accel_t::reset(wxMenuBar *m, int *idlist, int idcount) {
mMenu = m;
mData.clear();
if (idlist == 0) {
for (int i = 0, ie = m->GetMenuCount(); i != ie; ++i)
noteProblemMenuItems(m->GetMenu(i));
} else {
if (idcount < 0) {
int *i = idlist;
while (*i != -1) ++i;
idcount = (i - idlist);
}
for (int *i = idlist, *ie = i + idcount; i != ie; ++i) {
wxMenuItem *item = mMenu->FindItem(*i);
if (item) {
wxAcceleratorEntry *a = item->GetAccel();
if (a != 0) mData.push_back(accelitem_t(*i, *a));
}
}
}
}
bool accel_t::isProblemAccelerator(wxAcceleratorEntry *a) {
if (a == 0) return false;
int flags = a->GetFlags(), keycode = a->GetKeyCode();
// Normal ASCII characters, when used with no modifier or Shift-only, would
// interfere with editing.
if ((flags == wxACCEL_NORMAL || flags == wxACCEL_SHIFT) &&
(keycode >= 32 && keycode < 127)) return true;
// Certain other values, when used as normal accelerators, could cause
// problems too.
if (flags == wxACCEL_NORMAL) {
if (keycode == WXK_RETURN ||
keycode == WXK_DELETE ||
keycode == WXK_BACK) return true;
}
return false;
}
void accel_t::noteProblemMenuItems(wxMenu *m) {
// Problem menu items have hotkeys that are ASCII characters with normal or
// shift-only modifiers.
for (size_t i = 0, ie = m->GetMenuItemCount(); i != ie; ++i) {
wxMenuItem *item = m->FindItemByPosition(i);
if (item->IsSubMenu())
noteProblemMenuItems(item->GetSubMenu());
else {
wxAcceleratorEntry *a = item->GetAccel();
if (isProblemAccelerator(a))
mData.push_back(accelitem_t(item->GetId(), *a));
}
}
}
void accel_t::restore() const {
if (mMenu == 0) return;
for (data_t::const_iterator i = mData.begin(), ie = mData.end(); i != ie;
++i)
{
wxMenuItem *item = mMenu->FindItem(i->id);
if (item) {
wxString text = item->GetItemLabel().BeforeFirst(wxT('\t'));
wxString hotkey = i->hotkey.ToString();
if (hotkey.empty()) {
// The wxWidgets authors apparently don't expect ASCII
// characters to be used for accelerators, because
// wxAcceleratorEntry::ToString just returns an empty string for
// them. This code deals with that.
int flags = i->hotkey.GetFlags(), key = i->hotkey.GetKeyCode();
if (flags == wxACCEL_SHIFT) hotkey = wx("Shift-") + wxChar(key);
else hotkey = wxChar(key);
}
item->SetItemLabel(text + '\t' + hotkey);
}
}
}
void accel_t::remove() const {
if (mMenu == 0) return;
for (data_t::const_iterator i = mData.begin(), ie = mData.end(); i != ie;
++i)
{
wxMenuItem *item = mMenu->FindItem(i->id);
if (item) {
wxString text = item->GetItemLabel().BeforeFirst(wxT('\t'));
item->SetItemLabel(text);
}
}
}
The easiest way to use it is to create your menu-bar as normal, with all accelerator keys (including the problematic ones) in place, then create an accel_t item from it something like this:
// mProblemAccelerators is an accel_t item in the private part of my frame class.
// This code is in the frame class's constructor.
wxMenuBar *menubar = _createMenuBar();
SetMenuBar(menubar);
mProblemAccelerators.reset(menubar);
It will identify and record the accelerator keys that pose problems. Finally, call the remove and restore functions as needed, to remove or restore the problematic accelerator keys. I'm calling them via messages passed to the frame whenever I open a window that needs to do standard editing.

Resources