A few days ago I asked a question that might be a little unclear. Now I have written code that might illustrate the question better. Please look at the code below first:
int d;
d = DateTime.Today.Day;
if (d==1)
{
hyperlinkButton1.Background=new SolidColorBrush(Colors.Black);
}
else if (d==2)
{
hyperlinkButton2.Background=new SolidColorBrush(Colors.Black);
}
else if (d==3)
{
hyperlinkButton3.Background=new SolidColorBrush(Colors.Black);
}
else if (d==4)
{
hyperlinkButton4.Background=new SolidColorBrush(Colors.Black);
}
else if (d==5)
{
hyperlinkButton5.Background=new SolidColorBrush(Colors.Black);
}
else if (d==6)
{
hyperlinkButton6.Background=new SolidColorBrush(Colors.Black);
}
else if (d==7)
{
hyperlinkButton7.Background=new SolidColorBrush(Colors.Black);
}
else if (d==8)
{
hyperlinkButton8.Background=new SolidColorBrush(Colors.Black);
}
else if (d==9)
{
hyperlinkButton9.Background=new SolidColorBrush(Colors.Black);
}
else if (d==10)
{
hyperlinkButton10.Background=new SolidColorBrush(Colors.Black);
}
else if (d==11)
{
hyperlinkButton11.Background=new SolidColorBrush(Colors.Black);
}
else if (d==12)
{
hyperlinkButton12.Background=new SolidColorBrush(Colors.Black);
}
else if (d==13)
{
hyperlinkButton13.Background=new SolidColorBrush(Colors.Black);
}
else if (d==14)
{
hyperlinkButton14.Background=new SolidColorBrush(Colors.Black);
}
else if (d==15)
{
hyperlinkButton15.Background=new SolidColorBrush(Colors.Black);
}
else if (d==16)
{
hyperlinkButton16.Background=new SolidColorBrush(Colors.Black);
}
else if (d==17)
{
hyperlinkButton17.Background=new SolidColorBrush(Colors.Black);
}
else if (d==18)
{
hyperlinkButton18.Background = new SolidColorBrush(Colors.Black);
}
else if (d==19)
{
hyperlinkButton19.Background=new SolidColorBrush(Colors.Black);
}
else if (d==20)
{
hyperlinkButton20.Background=new SolidColorBrush(Colors.Black);
}
else if (d==21)
{
hyperlinkButton21.Background=new SolidColorBrush(Colors.Black);
}
else if (d==22)
{
hyperlinkButton22.Background=new SolidColorBrush(Colors.Black);
}
else if (d==23)
{
hyperlinkButton23.Background=new SolidColorBrush(Colors.Black);
}
else if (d==24)
{
hyperlinkButton24.Background=new SolidColorBrush(Colors.Black);
}
else if (d==25)
{
hyperlinkButton25.Background=new SolidColorBrush(Colors.Black);
}
else if (d==26)
{
hyperlinkButton26.Background=new SolidColorBrush(Colors.Black);
}
else if (d==27)
{
hyperlinkButton2.Background=new SolidColorBrush(Colors.Black);
}
else if (d==28)
{
hyperlinkButton28.Background=new SolidColorBrush(Colors.Black);
}
else if (d==29)
{
hyperlinkButton29.Background=new SolidColorBrush(Colors.Black);
}
else if (d==30)
{
hyperlinkButton30.Background=new SolidColorBrush(Colors.Black);
}
else
{
hyperlinkButton31.Background=new SolidColorBrush(Colors.Black);
}
My question (as a beginner) is this: is there any way in C# to shorten this condition by making the application determine which hyperlinkbutton background it has to change depending on the value of d?
Define an array of the relevant controls, and use the integer to key into the array, remembering that arrays are 0-based and not 1-based.
var buttons = new [] {
hyperlinkButton1,
hyperlinkButton2,
hyperlinkButton3,
hyperlinkButton4,
hyperlinkButton5,
hyperlinkButton6,
hyperlinkButton7,
hyperlinkButton8,
hyperlinkButton9,
// ...
}
//....
buttons[DateTime.Today.Day-1].Background=new SolidColorBrush(Colors.Black);
The array based approach is a good alternative at a general level to the multiple if statements but since this is also tagged as Silverlight, you might be interested in taking advantage of the FrameworkElement.FindName Method if you can rely on the convention of naming the HyperlinkButtons with a common prefix.
var hyperlinkButton = this.FindName("hyperlinkButton" + DateTime.Now.Day) as HyperlinkButton;
if (hyperlinkButton != null)
{
hyperlinkButton.Background = new SolidColorBrush(Colors.Black);
}
switch(d)
{
case 1: doThings(); break;
case 2: doThings2(); break;
case 3:
doSomeThings();
doMoreThings();
break;
default:
runThingsIfDIsNotListed();
break;
}
etc.
Related
I have one Dialog box where it's consist 3 EditControl boxes and 2 for Validating the Enter Data. When the Editcontrol is lost focus we are validating the entered data using OnKillFocus method and facing the Hang issue because of calling OnKIllFocus multiple times, after that we separated each KillFocus for each Editcontrol still also we are facing the same issue calling KillFocus multiple times
`BEGIN_MESSAGE_MAP(CWHPwdDlg, CDialog)
ON_BN_CLICKED(IDOK, OnOK)
ON_BN_CLICKED(IDCANCEL, OnCancel)
ON_WM_CTLCOLOR()
ON_EN_KILLFOCUS(IDC_HMI_SERVERNAME, OnKillFocusServerNameTextBox)
ON_EN_KILLFOCUS(IDC_WH_RT_PORT, OnKillFocusPortTextBox)
ON_EN_KILLFOCUS(IDC_HMI_USERNAME, OnKillFocusUserNameTextBox)
ON_EN_KILLFOCUS(IDC_HMI_PASSWORD, OnKillFocusPwdTextBox)
ON_BN_CLICKED(IDC_WH_RT_TEST_CONNECTION, OnTestConnection)
ON_BN_CLICKED(IDC_WH_RT_VIEW_CERT, OnViewCertificate)
ON_BN_CLICKED(IDC_WH_RT_REQUIRE_TRUST, OnCheckEnableTrust)
END_MESSAGE_MAP()
void CWHPwdDlg::OnKillFocusServerNameTextBox()
{
MessageBoxA(NULL, "Click", "Servername", MB_OK);
if (!UpdateData(TRUE)) {
return;
}
CWnd* pWndOk = GetDlgItem(IDOK);
//if (m_hmiServerName.IsEmpty())
if(m_hmiServerName.GetLength()<=0)
{
m_TestConnection.EnableWindow(FALSE);
SetDlgItemText(IDC_WH_RT_TRUSTED_MSG, _T(""));
CWnd* p_CertificateButton = GetDlgItem(IDC_WH_RT_VIEW_CERT);
if (p_CertificateButton != NULL)
p_CertificateButton->EnableWindow(FALSE);
CWnd* pTrustCheck = GetDlgItem(IDC_WH_RT_REQUIRE_TRUST);
if (pTrustCheck != NULL)
pTrustCheck->EnableWindow(FALSE);
m_whErrorStr.SetWindowText(m_strServerNameError);
m_whErrorStr.ShowWindow(SW_SHOW);
m_whErrorIcon.ShowWindow(SW_SHOW);
pWndOk->EnableWindow(FALSE);
return;
}
else
{
SetCertificateAndEnableViewer();
}
}
void CWHPwdDlg::OnKillFocusPortTextBox()
{
MessageBoxA(NULL, "Click", "KillPort", MB_OK);
if (!UpdateData(TRUE)) {
return;
}
CWnd* pWndOk = GetDlgItem(IDOK);
if (m_hmiPortNum.IsEmpty() || m_hmiPortNum == _T("0"))
{
m_whErrorStr.SetWindowText(m_strPortError);
m_whErrorStr.ShowWindow(SW_SHOW);
m_whErrorIcon.ShowWindow(SW_SHOW);
pWndOk->EnableWindow(FALSE);
//return FALSE;
}
}
void CWHPwdDlg::OnKillFocusUserNameTextBox()
{
MessageBoxA(NULL, "Click", "KillUserName", MB_OK);
if (!UpdateData(TRUE)) {
return;
}
CWnd* pWndOk = GetDlgItem(IDOK);
if (m_hmiUserName.IsEmpty())
{
m_whErrorStr.SetWindowText(m_strUserNameError);
m_whErrorStr.ShowWindow(SW_SHOW);
m_whErrorIcon.ShowWindow(SW_SHOW);
pWndOk->EnableWindow(FALSE);
// return FALSE;
}
}
`
When the strobe value is increased from 1 to 10 the blinking of flashlight will never stop.neither it stops on zero nor it turns on beside it just get blinking and blinking constantly. here i am adding the code which i have written to do so. if someone knows the solutions please help me.
Thread is not stop thread works until you stop debugger..
cheers!
enter code here
flashButton = findViewById(R.id.flash_button);
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
flashButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (!isTorchOn) {
turnOnFlashLight();
} else {
turnOffFlashLight();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
scrollValue = findViewById(R.id.value);
mWheel = findViewById(R.id.wheel);
mWheel.setOnScrollListener(new Wheel.OnScrollListener() {
#Override
public void onScrollStarted(Wheel view, float value, int roundValue) {
frequency = Math.abs(roundValue);
}
#Override
public void onScrollFinished(Wheel view, float value, int roundValue) {
scrollValue.setText("" + Math.abs(roundValue));
frequency = strobeFrequency(Math.abs(roundValue));
if(isTorchOn && frequency > 0) {
thread = new Thread(stroboRunner);
thread = null;
strobe(frequency);
}
else if(isTorchOn) {
strobe(0);
// thread.stop();
// thread=null;
}
}
#Override
public void onScroll(Wheel view, float value, int roundValue) {
scrollValue.setText("" + Math.abs(roundValue));
frequency = strobeFrequency(Math.abs(roundValue));
if(isTorchOn && frequency > 0) {
// thread = null;
strobe(frequency);
}
}
});
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void turnOnFlashLight() {
/*
if(frequency > 0){
scrollValue.setText("0.0");
}
*/
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
} else {
try {
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(camParams);
cam.startPreview();
} catch (RuntimeException e) {
Toast.makeText(this, "Camera Permission is not granted", Toast.LENGTH_SHORT).show();
}
}
flashButton.setImageResource(R.drawable.power_on);
isTorchOn = true;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(thread != null){
stroboRunner.stopRunning = true;
thread = null;
}else {
mCameraManager.setTorchMode(mCameraId, false);
}
} else {
try {
if(thread != null){
stroboRunner.stopRunning = true;
thread = null;
}else {
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
cam.setParameters(camParams);
cam.stopPreview();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception throws in turning off flashlight.", Toast.LENGTH_SHORT).show();
}
}
flashButton.setImageResource(R.drawable.power_off);
isTorchOn = false;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private int strobeFrequency(int roundValue) {
int freq = 0;
switch (roundValue) {
case 1:
freq = Math.abs(50);
break;
case 2:
freq = Math.abs(150);
break;
case 3:
freq = Math.abs(300);
break;
case 4:
freq = Math.abs(600);
break;
case 5:
freq = Math.abs(900);
break;
case 6:
freq = Math.abs(1200);
break;
case 7:
freq = Math.abs(1500);
break;
case 8:
freq = Math.abs(1800);
break;
case 9:
freq = Math.abs(2000);
break;
case 10:
freq = Math.abs(2300);
break;
}
return freq;
}
#Override
protected void onResume() {
super.onResume();
try {
cam = Camera.open();
camParams = cam.getParameters();
cam.startPreview();
hasCam = true;
} catch (Exception e) {
// TODO: handle exception
}
compass.start();
}
#Override
protected void onPause() {
super.onPause();
compass.stop();
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "stop compass");
compass.stop();
}
private void strobe(int freq) {
if(thread == null){
stroboRunner = new StroboRunner();
stroboRunner.freq = freq;
thread = new Thread(stroboRunner);
thread.start();
} else if(freq == 0 && thread!=null) {
stroboRunner.stopRunning = true;
thread = null;
// thread.stop();
}
}
private class StroboRunner implements Runnable {
int freq;
boolean stopRunning = false;
#Override
public void run() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
while (!stopRunning) {
mCameraManager.setTorchMode(mCameraId, true);
Thread.sleep(2600 - freq);
System.out.println(""+(2600-freq));
// Toast.makeText(MainActivity.this, ""+(2600-freq), Toast.LENGTH_SHORT).show();
mCameraManager.setTorchMode(mCameraId, false);
Thread.sleep(freq);
}
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
// thread=null;
} else {
Camera.Parameters paramsOn = cam.getParameters();
Camera.Parameters paramsOff = camParams;
paramsOn.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
paramsOff.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
try {
while (!stopRunning) {
cam.setParameters(paramsOn);
cam.startPreview();
Thread.sleep(2600 - freq);
cam.setParameters(paramsOff);
cam.startPreview();
Thread.sleep(freq);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
i'm currently writing an application with a parent class named 'Vehicle' and two children classes named 'Car' and 'Truck'. My problem is that I would like to search through the full list of Vehicles and return only each car, or each truck depending on what object is placed into a method. Right now I have had to write a method for ach search term such as below:
public string searchCarsByName(string nameString)
{
string carNames = "";
foreach (Car car in Vehicles.OfType<Car>())
{
if (car.Name.Contains(nameString))
{
carNames += car.ToString();
}
}
if (carNames == "")
{
return "No cars found";
}
else
{
return carNames;
}
}
public string searchTrucksByName(string nameString)
{
string truckNames = "";
foreach (Truck truck in Vehicles.OfType<Truck>())
{
if (truck.Name.Contains(nameString))
{
truckNames += name.ToString();
}
}
if (truckNames == "")
{
return "No vehicle found";
}
else
{
return truckNames;
}
}
My only problem is that the names isn't the only way I would like to search, so for each search I am going to perform then I will have to write two methods. What i'm looking for is a way to pass in an Object to the method, and then dependent on the object it will append the necessary details to the string such as below:
public string searchVehiclesByName(Vehicle nameString)
{
string vehicleNames = "";
if(Vehicle.Type == car)
{
foreach (Car car in Vehicles.OfType<Car>())
{
if (car.Name.Contains(nameString))
{
vehicleNames += car.ToString();
}
}
}
else
{
foreach (Truck truck in Vehicles.OfType<Truck>())
{
if (truck.Name.Contains(nameString))
{
vehicleNames += truck.ToString();
}
}
}
if (vehicleNames == "")
{
return "No vehicles found";
}
else
{
return vehicleNames;
}
}
}
Essentially what I need is a way to pass in a parent object and check if an object is of a certain child type before creating the resultant string, rather than having to pass each individual type of child object into a method to get the results I want.
Thank you in advance.
Please have a look at this: Type Checking: typeof, GetType, or is?
public string searchVehiclesByName(Vehicle vehicle)
{
string vehicleNames = "";
if(vehicle.GetType() == typeof(Car))
{
foreach (Car car in Vehicles.OfType<Car>())
{
if (car.Name.Contains(nameString))
{
vehicleNames += car.ToString();
}
}
}
else
{
foreach (Truck truck in Vehicles.OfType<Truck>())
{
if (truck.Name.Contains(nameString))
{
vehicleNames += truck.ToString();
}
}
}
if (vehicleNames == "")
{
return "No vehicles found";
}
else
{
return vehicleNames;
}
}
Hope this helps.
So I've been picking apart a friend's pong game in order to figure out keyPressed functions, and use them in my balloon game that I mentioned in another post. I believe I've put the code together correctly, keeping procedure and the logical order of things in mind, but for some reason the unexpected token:void keeps coming up as an error message. I've closed off all brackets, and declared all of the global variables to the best of my knowledge, but I keep running into this message.
Here's the code:
int level;
int paddleWidth = 200;
int paddleHeight = 200;
int paddleSpeed = 5;
int posX;
int posY;
boolean p1UP = false;
boolean p1DOWN = false;
boolean p1LEFT = false;
boolean p1RIGHT = false;
void setup() {
size (800,800);
frameRate(60);
smooth();
posX = width/2;
posY = height/2;
}
void draw() {
if (level==0) {
background(0);
textSize(50);
text("PREPARE YOUR ANUS", width/2, height/2-200);
text("PRESS A KEY YOU DINGUS", width/2, height/2-400);
if (keyPressed) level=1;
}
if (level==1) {
background(0);
fill(posX,0,posY);
rect(posX, posY, paddeWidth, paddleHeight);
if(p1UP==true) {
posY -=paddleSpeed;
}
if(p1DOWN==true) {
posY +=paddleSpeed;
}
if(p1LEFT==true) {
posX -= paddleSpeed;
}
if(p1RIGHT==true) {
posX += paddleSpeed;
}
void keyPressed() {
if (key=='w' || key=='W') {
p1UP = true;
}
if (key=='s' || key=='S') {
p1DOWN = true;
}
if (key=='a' || key=='A') {
p1LEFT = true;
}
if (key=='d' || key=='D') {
p1RIGHT = true;
}
}
void keyReleased() {
if (key=='w' || key=='W') {
p1UP = false;
}
if (key=='s' || key=='S') {
p1DOWN = false;
}
if (key=='a' || key=='A') {
p1LEFT = false;
}
if (key=='d' || key=='D') {
p1RIGHT = false;
}
}
}
}
Please use proper formatting. Your indentation made this really hard to read, which is probably why you didn't get an answer right away.
The code with proper formatting looks like this:
boolean p1UP = false;
boolean p1DOWN = false;
boolean p1LEFT = false;
boolean p1RIGHT = false;
void setup() {
size (800,800);
frameRate(60);
smooth();
posX = width/2;
posY = height/2;
}
void draw() {
if (level==0) {
background(0);
textSize(50);
text("use more mature examples", width/2, height/2-200);
text("PRESS A KEY please", width/2, height/2-400);
if (keyPressed) level=1;
}
if (level==1) {
background(0);
fill(posX,0,posY);
rect(posX, posY, paddeWidth, paddleHeight);
if(p1UP==true) {
posY -=paddleSpeed;
}
if(p1DOWN==true) {
posY +=paddleSpeed;
}
if(p1LEFT==true) {
posX -= paddleSpeed;
}
if(p1RIGHT==true) {
posX += paddleSpeed;
}
void keyPressed() {
if (key=='w' || key=='W') {
p1UP = true;
}
if (key=='s' || key=='S') {
p1DOWN = true;
}
if (key=='a' || key=='A') {
p1LEFT = true;
}
if (key=='d' || key=='D') {
p1RIGHT = true;
}
}
void keyReleased() {
if (key=='w' || key=='W') {
p1UP = false;
}
if (key=='s' || key=='S') {
p1DOWN = false;
}
if (key=='a' || key=='A') {
p1LEFT = false;
}
if (key=='d' || key=='D') {
p1RIGHT = false;
}
}
}
}
This makes it obvious that your keyPressed() and keyReleased() functions are inside your draw() function, which isn't valid.
Also note that this line is pretty egregious:
if (keyPressed) level=1;
Even though it's not causing anything bad now, if down the road you want to do more than just set the level equal to 1, you're more likely to introduce logical errors. For that reason, if statements should always be followed by curly brackets, even if they're only one statement:
if (keyPressed){
level=1;
}
How to retrieve both SIM and phone book contact using PIM in J2ME.
I Tried
PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
but it's only displaying Phone book contact.
May be this method can help you
public static HashLongObject loadContactFromPhone() {
PIM iPim = PIM.getInstance();
String[] allContactLists = iPim.listPIMLists(PIM.CONTACT_LIST);
// Phone or SIM
HashLongObject iPhoneBookList = new HashLongObject();
int i;
for (i = 0; i < allContactLists.length; i++) {
try {
PIMList iPIMList = iPim.openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, allContactLists[i]);
Enumeration iPimListEnum = iPIMList.items();
String iContactName, iTelNumber;
String []arrName;
boolean isSupportFormettedName = iPIMList.isSupportedField(Contact.FORMATTED_NAME);
if(isSupportFormettedName) {
while (iPimListEnum.hasMoreElements()) {
try {
Contact iContact = (Contact) iPimListEnum.nextElement();
iContactName = iContact.getString(Contact.FORMATTED_NAME, 0);
iTelNumber = iContact.getString(Contact.TEL, 0);
} catch (Exception e) {
Logger.logStackTrace(e);
continue;
}
long corePhoneNumber = StringUtils.toCCPhoneNumber(iTelNumber);
// Check Duplicate
if (iPhoneBookList.containsKey(corePhoneNumber)) {
continue;
}
iPhoneBookList.put(corePhoneNumber, iContactName);
}
} else {
while (iPimListEnum.hasMoreElements()) {
try {
Contact iContact = (Contact) iPimListEnum.nextElement();
arrName = iContact.getStringArray(Contact.NAME, Contact.ATTR_NONE);
iContactName = "";
if(arrName[Contact.NAME_FAMILY] != null) {
iContactName += arrName[Contact.NAME_FAMILY];
}
if(arrName[Contact.NAME_GIVEN] != null) {
iContactName += arrName[Contact.NAME_GIVEN];
}
iTelNumber = iContact.getString(Contact.TEL, 0);
} catch (Exception e) {
Logger.logStackTrace(e);
continue;
}
long corePhoneNumber = StringUtils.toCCPhoneNumber(iTelNumber);
// Check Duplicate
if (iPhoneBookList.containsKey(corePhoneNumber)) {
continue;
}
iPhoneBookList.put(corePhoneNumber, iContactName);
}
}
} catch (PIMException ex) {
Logger.logStackTrace(ex);
} catch (Exception otherEx) {
Logger.logStackTrace(otherEx);
}
}
return iPhoneBookList;
}