For unknown reason, a button click closes my window. How can I fix this? - monodevelop

I am trying to replicate a simple addition of 2 entries with a button in Monodevelop (shown how to make it step-by-step) but somehow the window closes 2 seconds after pressing the button without actually changing anything.
The code for the button:
using Gtk;
using Frontend.ChatService;
public partial class MainWindow : Gtk.Window
{
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
Build();
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
a.RetVal = true;
}
protected void OnButton1Clicked(object sender, EventArgs e)
{
ChatService client = new ChatService();
int x = Int32.Parse(entry1.Text);
int y = Int32.Parse(entry2.Text);
int sum = client.Add(x, y);
entry1.Text = sum.ToString();
}
}
And the sum (which I tested and think works):
using System;
using System.Web;
using System.Web.Services;
namespace Backend
{
public class ChatService : System.Web.Services.WebService
{
[WebMethod]
public int Add(int x, int y)
{
return x + y;
}
}
}
I left the main file program.cs as generated and is:
using System;
using Gtk;
namespace Frontend
{
class MainClass
{
public static void Main(string[] args)
{
Application.Init();
MainWindow win = new MainWindow();
win.Show();
Application.Run();
}
}
}
The window does pop up as it should and shows no problem until the button is pressed.
Edit:
I forgot to run the backend / server part, which is why the function was not found... (beginners mistake I guess)
Works now

The problem is probably that your code throws an exception you are not aware of. The problem is in the code that handles the button being clicked.
protected void OnButton1Clicked(object sender, EventArgs e)
{
ChatService client = new ChatService();
int x = Int32.Parse(entry1.Text);
int y = Int32.Parse(entry2.Text);
int sum = client.Add(x, y);
entry1.Text = sum.ToString();
}
Let's go line by line:
ChatService client = new ChatService();
Here you are creating a new instance of what it seems to be a system service or maybe a web services. This could throw if the service is not known (in the former case), or if the connection is interrupted or does not reach a destination, etc., in the latter case.
These lines are also delicate:
int x = Int32.Parse(entry1.Text);
int y = Int32.Parse(entry2.Text);
They will throw in case the field entry1 or entry2 are empty, or contain a letter...
In order to manage these cases you need to add try... catch blocks in the appropriate places. Alternately, you can use Int32.TryParse.
For example, assuming the service is in the web:
protected void OnButton1Clicked(object sender, EventArgs e)
{
ChatService client;
int x;
int y;
try {
client = new ChatService();
} catch(HttpRequestException exc) {
client = null;
var dlg = new Gtk.MessageDialog(
this,
Gtk.DialogFlags.Modal,
Gtk.MessageType.Error,
Gtk.ButtonsType.Ok,
"Connection error"
);
dlg.Text = exc.Message;
dlg.Run();
dlg.Destroy();
}
if ( client != null ) {
if ( !int.TryParse( entry1.Text, out x) {
entry1.Text = "0";
x = 0;
}
if ( !int.TryParse( entry2.Text, out y) {
entry2.Text = "0";
y = 0;
}
int sum = client.Add(x, y);
entry1.Text = sum.ToString();
}
}
Getting code which correctly handles errors is always harder, of course.
Hope this helps.

Related

object reference null exception

I'm trying to access the value of resulterr in button clickevent in order to display it in the messagebox. I'm not getting the value inside the button click event despite setting resulterr list as public. I'm getting exception as object reference not set to an instance of an object. Please rectify the error.
public List<ErrorMsgTemplate> resulterr;
public PPFCWCFServiceClient ppfcObj = new PPFCWCFServiceClient();
public Admin()
: base("Administration")
{
SplashScreenManager.ShowDefaultWaitForm();
InitializeComponent();
GetSource();
ErrorMsg();
FillDivision();
cmbDivision.SelectedIndex = -1;
SplashScreenManager.CloseDefaultWaitForm();
}
public void ErrorMsg()
{
List<ErrorMsgTemplate> resulterr = ppfcObj.getErrorMsgTemplate("ADMIN");
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (cmbDivision.SelectedIndex == -1) //naray added
{
MessageBox.Show(resulterr[0].ERROR_MESSAGE_TEMPLATE.ToString() + "," + resulterr[0].SCREEN_NM.ToString(), "PPFC");
}
I found the issue. I've declared global variable as
public List<ErrorMsgTemplate> resulterr;
and reinstantiated again in ErrorMsg():
public void ErrorMsg()
{
List<ErrorMsgTemplate> resulterr = ppfcObj.getErrorMsgTemplate("ADMIN");
}
Instead, used:
public void ErrorMsg()
{
resulterr = ppfcObj.getErrorMsgTemplate("ADMIN");
}
Now I'm able to access resulterr in btnsave event.
That error comes when your variable value get blank or a space .you can track by null or space to prevent this error

Seems scheduleUpdate not working

I'm trying to create a ScrollView class with cocos2d-2.0-rc2-x-2.0.1 and I mean to do something in update function to implement the auto-scroll effect.Unfortunately,I find the function has never been called.Though I've done a lot of work like searching on the internet,debuging step by step and so on,the possible solutions I found helped little.
As far as I know,my ScrollView class derive from CCNode and I've implemented the update function.The declaration of ScrollView is as following:
class ScrollView:public CCNode,public CCTouchDelegate
{
ClippingNode* visible_view;
CCNode* content_view;
//CCArray* items;
float row_margin;
float col_margin;
float interval_margin;
float last_y;//起始y方向坐标
float interval_dis;//间隔时间段内y方向上的位移。
bool touch_stopped;//标识触摸是否停止,主要用于自动滚动。
float up_bounder_y,down_bounder_y;//content_view的y方向坐标上下限
int items_num;
public:
static ScrollView* New(CCSize visible_view_size,float row_margin,float col_margin,float interval_margin,CCNode* background = NULL);
void ccTouchBegin(cocos2d::CCNode *node,const cocos2d::CCPoint &point);
void ccTouchMove(cocos2d::CCNode *node,const cocos2d::CCPoint &point);
void ccTouchEnd(cocos2d::CCNode *node,const cocos2d::CCPoint &point);
virtual void onEnter();
protected:
CCNode* makeCard();
void initContent();
private:
ScrollView():visible_view(NULL),content_view(NULL),touch_stopped(true){}
virtual ~ScrollView();
bool init(CCSize visible_view_size,float row_margin,float col_margin,float interval_margin,CCNode* background);
void update(float dt);
};
And here is the definition of update function:
void ScrollView::update(float dt)
{
CCLOG("update");
if(touch_stopped)
{
if(abs(interval_dis) < a)
{
interval_dis = 0.0f;
this->unscheduleUpdate();
}else
{
if(interval_dis < 0)
interval_dis += a;
else
interval_dis -= a;
const float future_y = content_view->getPositionY() + interval_dis;
if(future_y > down_bounder_y && future_y < up_bounder_y)
{
content_view->setPositionY(interval_dis);
}else if(future_y <= down_bounder_y)
{
content_view->setPositionY(down_bounder_y);
interval_dis = 0.0f;
}else
{
content_view->setPositionY(up_bounder_y);
interval_dis = 0.0f;
}
}
}
}
So I can ensure the type of the param is float instead of CCTime or ccTime which may cause update function never to be called.Moreover,I invoke the scheduleUpdate in the init method like the following:
bool ScrollView::init(CCSize visible_view_size,float row_margin,float col_margin,float interval_margin,CCNode* background)
{
visible_view = ClippingNode::New(visible_view_size);
CHECK_RETURN(visible_view,NULL,false);
visible_view->retain();
content_view = CCNode::create();//node函数中已调用autorelease
CHECK_RETURN(content_view,NULL,false);
content_view->retain();
this->row_margin = row_margin;
this->col_margin = col_margin;
this->interval_margin = interval_margin;
this->setAnchorPoint(ccp(0.5f,0.5f));
this->setContentSize(visible_view_size);
visible_view->setPosition(0,0);
content_view->setAnchorPoint(ccp(0,1));
content_view->setPosition(row_margin,visible_view_size.height);
content_view->setContentSize(CCSize(visible_view_size.width - 2 * row_margin,2 * col_margin));
this->addChild(visible_view);
visible_view->addChild(content_view);
down_bounder_y = visible_view_size.height;
up_bounder_y = content_view->getContentSize().height > visible_view_size.height?content_view->getContentSize().height:visible_view_size.height;
UserData* user_data = UserData::getUserData(this,true);
CHECK_RETURN(user_data,NULL,false);
user_data->setContainer(true);
items_num = 0;
initContent();
if(background)
{
background->setScaleX(visible_view_size.width/background->getContentSize().width);
background->setScaleY(visible_view_size.height/background->getContentSize().height);
background->setAnchorPoint(ccp(0.5f,0.5f));
background->setPosition(visible_view_size.width/2,visible_view_size.height/2);
user_data = UserData::getUserData(background,true);
user_data->setHitable(false);
this->addChild(background,-1);
}
this->scheduleUpdate();
return true;
}
Through debug,I can ensure the sentence "this->scheduleUpdate()" is invoked.In addition,I created a ScrollView object named scroll_view and added it to the main node through addChild function.So,where am I wrong?Any addvice would be appreciated and thanks for watching:p
I forgot to invoke the CCNode::onEnter in my own onEnter function. Thus all we need to do is invoke CCNode::onEnter in the ScrollView::onEnter. Hope other people don't make the mistake as I did.
If you invoke the onEnter, scheduleUpdate() may be not working.
CCDirector::sharedDirector()->getScheduler()->scheduleUpdateForTarget(this,0,false);
or
CCDirector::sharedDirector()->getScheduler()->scheduleSelector(schedule_selector(NewGame::update),this,0.1,false);
Dont know why your code is not working but have you tried this:
CCDirector::sharedDirector()->getScheduler()->scheduleUpdateForTarget(cocos2d::CCObject *pTarget, int nPriority, bool bPaused);
you can check whether the node responds to update() call using:
pNode->getIsRunning();

Play sound file on Timer end

I have a countdown timer and I want an alarm to go off when it reaches the end ... lots for Android and iOS, but nothing that I could find for WP8.
I'm using the DispatcherTimer for counting down.
I'm looking for some information or an example on how to call a sound when the timer finishes counting down. I have the counter start on a button click and reset on a long press. It all works good, just want a sound effect when it stops after counting down.
private DateTime EndTime { get; set; }
private DispatcherTimer _dispatcherTimer;
private void BtnCounter_Click(object sender, RoutedEventArgs e)
{
if (this._dispatcherTimer == null)
{
this._dispatcherTimer = new DispatcherTimer();
this._dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100);
this._dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
}
if (this.EndTime == DateTime.MinValue)
{
this.EndTime = DateTime.Now + (TimeSpan)this.tsPicker.Value;
}
this._dispatcherTimer.Start();
}
void dispatcherTimer_Tick(object sender, EventArgs e)
{
var remaining = this.EndTime - DateTime.Now;
int remainingSeconds = (int)remaining.TotalSeconds;
this.tsPicker.Value = TimeSpan.FromSeconds(remainingSeconds);
if (remaining.TotalSeconds <= 0)
{
this._dispatcherTimer.Stop();
// Sound code should go here, or a method call to it.
}
}
private void BtnCounter_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
cnt = 0;
BtnCounter.Content = cnt;
this._dispatcherTimer.Stop();
this.EndTime = DateTime.MinValue;
this.tsPicker.Value = TimeSpan.FromSeconds(0);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
this.EndTime = DateTime.MinValue;
base.OnNavigatedFrom(e);
}
Have you tried using a MediaElement? There seems to be a good example using it, titled Windows Phone 8: Playing Sounds

SWT JFace: SelectionProvider not working in TabFolder

In a GraphicalEditor I created a tab folder:
private final String[] tabNames = { "Text", "Image" };
private ResourcesTextComposite comText;
private ResourcesImageComposite comImage;
...
public void createPartControl(Composite parent) {
...
tabFolder = new TabFolder(parent, SWT.BORDER);
for (int loopIndex = 0; loopIndex < tabNames.length; loopIndex++) {
TabItem tabItem = new TabItem(tabFolder, SWT.NULL);
tabItem.setText(tabNames[loopIndex]);
if (loopIndex == 0) {
comText = new ResourcesTextComposite(tabFolder, SWT.NONE,
resources);
tabItem.setControl(comText);
} else if (loopIndex == 1) {
comImage = new ResourcesImageComposite(tabFolder, SWT.NONE,
resources);
tabItem.setControl(comImage);
}
}
...
}
it has 2 tab items and each item has a composite in it, and each composite has a TableViewer respectively.
I tried this to make each TableViewer the selection provider when the user selects the corresponding tab item (the same function createPartControl of the editor):
public void createPartControl(Composite parent) {
...
tabFolder.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
int tabIdx = tabFolder.getSelectionIndex();
getSite().setSelectionProvider(null);
if (tabIdx == 0) {
getSite().setSelectionProvider(comText.getViewer());
} else if (tabIdx == 1) {
getSite().setSelectionProvider(comImage.getViewer());
}
System.out.println("widgetSelected" + getSite() + ": "
+ getSite().getSelectionProvider());
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
...
}
I hope when I select a row in a TableViewer, the Properties view will show the selected model's properties, I've complete those IPropertySource things and they works well in other editors that has no tab folders, so I think the problem should be in the Selection Provider area.
Any ideas or has anyone encountered the same problem?
If you have multiple selection providers in a view or editor, then you need to use a mediator like org.eclipse.jdt.internal.ui.viewsupport.SelectionProviderMediator. Note that it is unfortunately internal, so you need to copy it to your own project

Java Reflection Problem

Hi I am currently doing my final year project; I need to develop an algorithm visualization tool. I need to cater for user-defined algo; that is animate the algorithm the user types in a text-editor provided in my tool.
I am using the Java Compiler API to compile the code that the user has typed and saved. My tool offers a set of classes that the user can use in his/her algo.
For example:
myArray(this class is provided by my tool)
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.accessibility.AccessibleContext;
import javax.swing.*;
public class myArray extends JComponent {
int size = 0;
int count = 0;
int[]hold;
Thread th;
public myArray(int[]arr)//pass user array as parameter
{
//th = new Thread();
size=arr.length;
hold = arr;//make a copy of the array so as to use later in swap operation
}
public int length()
{
return hold.length;
}
public void setAccessibleContext(AccessibleContext accessibleContext) {
this.accessibleContext = accessibleContext;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
this.setPreferredSize(new Dimension(360,100));
for(int i=1; i<=size; i++)
{
g2d.drawRect((i*30), 30, 30, 50);
}
for(int i=1; i<=size; i++)
{
g2d.drawString(Integer.toString(hold[i-1]), (i*30)+15, 30+25);
}
}
public void set(int i, int j)//position of the two elements to swap in the array
{
try {
th.sleep(2000);//sleep before swapping because else user won't see original array since it would swap and then sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int temp = hold[i];
hold[i] = hold[j];
hold[j] = temp;
hold[i]=j;
this.repaint();//can use eapint with a class that extends JPanel
}
public void swap(int i, int j)//position of the two elements to swap in the array
{
try {
th.sleep(2000);//sleep before swapping because else user won't see original array since it would swap and then sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int temp = hold[i];
hold[i] = hold[j];
hold[j] = temp;
this.repaint();//can use eapint with a class that extends JPanel
}
public int get(int pos)
{
return hold[pos];
}
}
This is a portion of my GUI that will cause the compilation:
JavaCompiler jc = null;
StandardJavaFileManager sjfm = null;
File javaFile = null;
String[] options = null;
File outputDir = null;
URL[] urls = null;
URLClassLoader ucl = null;
Class clazz = null;
Method method = null;
Object object = null;
try
{
jc = ToolProvider.getSystemJavaCompiler();
sjfm = jc.getStandardFileManager(null, null, null);
File[] files = new File[1];
//files[0] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/myArray.java");
//files[1] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/Tool.java");
files[0] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/userDefined.java");
// getJavaFileObjects’ param is a vararg
Iterable fileObjects = sjfm.getJavaFileObjects(files);
jc.getTask(null, sjfm, null, null, null, fileObjects).call();
// Add more compilation tasks
sjfm.close();
options = new String[]{"-d", "C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project"};
jc.getTask(null, sjfm, null, Arrays.asList(options), null, fileObjects).call();
outputDir = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project");
urls = new URL[]{outputDir.toURL()};
ucl = new URLClassLoader(urls);
clazz = ucl.loadClass("userDefined");
method = clazz.getMethod("user", null);
object = clazz.newInstance();
Object ob = method.invoke(object, null);
}
This is an example of a user-defined algo(userDefined.java):
import java.awt.*;
import javax.swing.*;
public class userDefined
{
public void user()
{
int [] numArr = {1,3,1,-1,5,-5,0,7,12,-36};
myArray myArray = new myArray(numArr);
JFrame frame = new JFrame("Rectangles");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(360, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(myArray);
for (int i=myArray.length(); i>1; i--)
{
for (int j=0; j<i-1; j++)
{
if (myArray.get(j) > myArray.get(j+1))
{
myArray.swap(j, j+1);
}
}
}
}
}
The problem I am getting is that if I try to use reflection like above; I only get a white window which does not show the animation) but just displays the result at the very end.
However if I use this instead of reflection(and change the method void user() to static void main(string args) in userDefined.java):
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(compiler.run(null, null, null, "userDefined.java") != 0) {
System.err.println("Could not compile.");
System.exit(0);
}
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java "+"userDefined");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
it woks provided that after first compilation I place the myArray class in the same folder as the userDefined.java. In this case I can see the animation take place correctly.
How do I use reflection to invoke the main method instead of using an instance of the class.
Please I really need some help with this. Thanks!
You a violating / missusing the first rule of swing: acces swing components only in the EDT (Event Dispatch Thread).
When you start your program using the main method, you are violating that rule. This happens to work, but might have all kinds of weird effects. This is not a theoretic warning, it happend to me and it is not nice.
When you run it using reflection from your code, you are most likely in the EDT, so your algorithm runs completely before the GUI gets updated again (which also happens on the EDT). Thats why you see only the final result of the algorithm.
The correct way to do this would be:
Run the algorithm in a seperate thread and make sure all changes to your myArray Component happen in the EDT, using SwingUtilities.invokeAndWait or SwingUtilities.invokeLater