How to make keyCode == ENTER update a string? - variables

I have my programme here, where you can see I have a string called "S", and a void Get Temperature. At the bottom where keypresses are processed, it has an else If statement with ENTER. I want it so that when you press enter, it updates the string (s) to whatever you have typed, and then load it into the "SetAddress" field. How would I go about this?
import com.temboo.core.*;
import com.temboo.Library.Yahoo.Weather.*;
import ddf.minim.*;
AudioPlayer player;
Minim minim;
PImage bg;
String myText;
PFont Bold;
PFont Thin;
TembooSession session = new TembooSession("goldsmiths-c", "myFirstApp", "CNgLbwqnqzGdsnk6wHXPfAnQNSmV0Fmr");
String s = "Enter Location";
int prev = frameCount;
//KeyPressed KeyPressed = new KeyPressed();
void setup() {
size(960, 540);
bg = loadImage("mountains.jpg");
minim = new Minim(this);
player = minim.loadFile("song.mp3");
player.play();
player.loop();
runGetTemperatureChoreo();
Bold = createFont ("TTFirsBlackItalic.otf", height);
Thin = createFont ("TTFirsThin.otf", height);
frameRate (30);
}
void draw() {
background(bg);
fill (0);
textFont (Bold);
textSize (48);
fill(255, 255, 255);
text(myText, 10, 390);
fill(255, 255, 255);
textFont (Thin);
textSize (48);
text(s, 10, 500);
print(mouseY);
}
void runGetTemperatureChoreo() {
GetTemperature getTemperatureChoreo = new GetTemperature(session);
getTemperatureChoreo.setAddress(s);
getTemperatureChoreo.setUnits("c");
GetTemperatureResultSet getTemperatureResults = getTemperatureChoreo.run();
myText = (s) + (getTemperatureResults.getTemperature() + ("°c"));
print(getTemperatureResults.getTemperature());
}
void keyPressed()
{
if (keyPressed && prev <= frameCount-10) { //If a key is being pressed, and the security/delay is fine with it
prev = frameCount; //re-Init the clock
if (keyCode == BACKSPACE) { //Delete a char!
if (s.length() > 0) {
s = s.substring(0, s.length()-1);
}
} else if (keyCode == DELETE) {
s = "";
} else if (keyCode == ENTER && s.length() != 0) {
} else if (keyCode != SHIFT && keyCode != CONTROL && keyCode != ALT && s.length() < 20) { //It's an ok char, add it to the String
s += key;
}
}
}

Well, it looks like you're storing what the user types in the s variable. You then have this part of your if statement:
else if (keyCode == ENTER && s.length() != 0) {
}
That else if will be entered whenever the user presses enter after typing something. So you just have to put whatever code you want inside the body of that statement:
else if (keyCode == ENTER && s.length() != 0) {
getTemperatureChoreo.setAddress(s);
}
I might not be fully understanding your code, so this is just an example. But the basic idea is the same: to do something when the user presses enter, just put the code you want to happen inside this else if block.
In the future, please try to post an MCVE instead of your entire sketch. For example, your question has nothing to do with minim, so you can get rid of all of that code. Start over with a blank sketch and only add enough code so we can copy and paste it to run it ourselves to see where you're stuck. Good luck.

Related

Color change a background in processing w/ out affecting particles

I'm trying to fade a background in and out into different colors. I decided to try drawing a rect rather than using background, but I'm getting trails on my particles, because the background isn't getting drawn. Suggestions on how to fix this?
// main tab
ArrayList<ParticleSystem> systems;
PVector windRight = new PVector(0.1,0);
PVector sortaSpeed = new PVector(-0.1,0);
PVector gravity = new PVector(0,0.05);
boolean wR = false;
boolean sP = false;
boolean cS = false;
int limit = 8;
int alpha = 10;
color[] colorArray = {color(0,0,0,alpha),color(16, 37, 43,alpha),color(51, 10, 10,alpha),color(126, 255, 0,alpha)};
int currentColor;
int nextColor;
boolean change = false;
void setup() {
size(640,480);
systems = new ArrayList<ParticleSystem>();
smooth();
noStroke();
currentColor = 0;
for(int i = 0; i < limit; i++){
systems.add(new ParticleSystem(random(100,200),10,new PVector(random(100,500),-5))); //random(480)
}
background(0);
}
void draw() {
//rect(0, 0, 2000, 2000);
fill(colorArray[currentColor]);
rect(0, 0, width*2, height*2);
//background(colorArray[currentColor]);
if(change){
currentColor = nextColor;
change = false;
}
if(!systems.isEmpty()){
for (int i =0; i < systems.size(); i++){
ParticleSystem ps = systems.get(i);
ps.applyForce(gravity);
ps.run();
if(wR){
ps.applyForce(windRight);
}
if(sP){
ps.applyForce(sortaSpeed);
}
}
}
}
void keyPressed() {
if(key == 'w'){
wR = true;
print("w");
}
if(key == 'a'){
print('a');
sP = true;
}
}
void keyReleased(){
if(key == 'w'){
wR = false;
} else if(key == 'a'){
sP = false;
} else if(key == 's'){
if(key == 's'){
change = true;
println("currentColor: "+currentColor);
int newColor = currentColor;
while (newColor == currentColor)
newColor=(int) random(colorArray.length);
nextColor = newColor;
}
} // end of cS
}
In the future, please try to post an MCVE. Right now we can't run your code because it contains compiler errors. We don't need to see your entire sketch anyway though, just a small example that gets the point across.
But your problem is caused because you're trying to use alpha values in your background. That won't work with the background() function because that function ignores alpha values, and it won't work with the rect() function because then you won't be clearing out old frames- you'll see them through the transparent rectangle.
Instead, you could use the lerpColor() function to calculate the transition from one color to another over time.
Here's an example that transitions between random colors:
color fromColor = getRandomColor();
color toColor = getRandomColor();
float currentLerpValue = 0;
float lerpStep = .01;
void draw() {
color currentColor = lerpColor(fromColor, toColor, currentLerpValue);
currentLerpValue += lerpStep;
if (currentLerpValue >= 1) {
fromColor = currentColor;
toColor= getRandomColor();
currentLerpValue = 0;
}
background(currentColor);
}
color getRandomColor() {
return color(random(255), random(255), random(255));
}

Color System in Processing Paint-like Program

I am building a paint-like program in processing. I want to be able to adjust the r, g, and b values of the pen color. What I did is use the 'r' key to allow the user to change r. After hitting 'r' they use the '+' and '-' keys to adjust it. Then you hit 'd', and it finishes. '+' and '-' are already used for pen size so I had to do it this way. But when I run the code and hit r it freezes up and stops responding. Does anyone know what is wrong.
Here is the problematic part of the code:
if(key == 'r'){ // Activates if 'r' is pressed
actr = true; // Sets actr = to true
while (actr = true) { // Goes until actr is false
if (key == '=') { // Activates is '=' is pressed
r = r ++; // Increases r by one
}
if (key == '-'){ // Activates if '-' is pressed
r = r --; // Decreases r by one
}
if (key == 'd') { // Activates if 'd' is pressed
actr = false; // Sets actr = to false
}
}
}
Here is the full code: http://www.openprocessing.org/sketch/226658
You've got a few problems. First of all, look at this line:
while (actr = true) { // Goes until actr is false
You're not checking equality here, you're assigning the value of true to your actr variable, which will also evaluate to true. In other words, that will never be false. Instead, you should use:
while (actr == true) {
Or even better:
while (actr) {
However, even when you fix that, your while loop will still never exit. This is because you're busy waiting and blocking the program from continuing. This will prevent Processing from ever changing the key variable.
Instead of busy waiting, just keep track of which mode you're in, which determines what the + and - keys do. You could use a series of booleans:
boolean size = true;
boolean red = false;
boolean green = false;
boolean blue = false;
void keyPressed(){
if(key == 'r'){ // Activates if 'r' is pressed
if (key == '=') {
if(size){
x++;
}
else if(red){
r++;
}
}
else if (key == '-'){
if(size){
x++;
}
else if(red){
r++;
}
}
if (key == 'd') { // Activates if 'd' is pressed
size = true;
red = false;
blue = false;
green = false;
}
else if(key == 'r'){
size = false;
red = true;
blue = false;
green = false;
}
}
}
That's just one approach, and I didn't include all of the code, but that should be a better general idea than your busy waiting.

Treeviews QueueDraw doesn't render current row?

I'm working with a treeview, which contains several columns, also one displaying a pixbuf, if audio is playing or paused. If the user double clicks on one row, audio playback starts and the row needs to be rerendered in order to display the pixbuf icon. I used QueueDraw for this, but that does only work, if the cursor leaves the current row. How can I update the pixbuf directly?
CODE:
protected void trvMainCuesheetRowActivated (object o, RowActivatedArgs args)
{
log.debug("trvMainCuesheetRowActivated called");
TreeIter ti = TreeIter.Zero;
this.lsCuesheetData.GetIter(out ti,args.Path);
if (this.lsCuesheetData.GetValue(ti,0) != null)
{
Track tCurTrack = (Track)this.lsCuesheetData.GetValue(ti,0);
if (this.objProgram.getAudioManager().getPlayState() == AudioCuesheetEditor.AudioBackend.PlayState.Stopped)
{
this.objProgram.getAudioManager().play(tCurTrack);
this.refresh();
}
else
{
if (this.objProgram.getAudioManager().getPlayState() == AudioCuesheetEditor.AudioBackend.PlayState.Playing)
{
this.objProgram.getAudioManager().seek(tCurTrack);
this.refresh();
}
}
}
}
private void renderPlaying(TreeViewColumn _tvcColumn, CellRenderer _crCell, TreeModel _tmModel, TreeIter _tiIter)
{
Track tCurTrack = (Track)_tmModel.GetValue (_tiIter, 0);
//Just display an icon, if we are playing
if (this.objProgram.getAudioManager().getPlayState() == AudioCuesheetEditor.AudioBackend.PlayState.Playing)
{
if (this.objProgram.getAudioManager().getCurrentlyPlayingTrack() == tCurTrack)
{
Gdk.Pixbuf icon = this.RenderIcon(Stock.MediaPlay, IconSize.SmallToolbar, null);
(_crCell as CellRendererPixbuf).Pixbuf = icon;
}
else
{
(_crCell as CellRendererPixbuf).Pixbuf = null;
}
}
else
{
if (this.objProgram.getAudioManager().getPlayState() == AudioCuesheetEditor.AudioBackend.PlayState.Paused)
{
if (this.objProgram.getAudioManager().getCurrentlyPlayingTrack() == tCurTrack)
{
Gdk.Pixbuf icon = this.RenderIcon(Stock.MediaPause, IconSize.SmallToolbar, null);
(_crCell as CellRendererPixbuf).Pixbuf = icon;
}
else
{
(_crCell as CellRendererPixbuf).Pixbuf = null;
}
}
else
{
(_crCell as CellRendererPixbuf).Pixbuf = null;
}
}
}
//Purpose: Function used to refresh the MainWindow depending on new options set.
public void refresh()
{
//QueueDraw is needed since it fires a signal to cellrenderers to update
this.trvMainCuesheet.QueueDraw();
this.sbMainWindow.Visible = this.objProgram.getObjOption().getBShowStatusbar();
this.mwToolbar.Visible = this.objProgram.getObjOption().getBToolbarVisible();
}
Greetings
Sven
Found the error myself.
this.objProgram.getAudioManager().getCurrentlyPlayingTrack()
didn't always return a track, where I expected one, so the renderer worked right. Bug is fixed, thanks anyway ;).

Windows 8 - TextBox that only accepts numbers goes wrong

here is my TextBox written in C# with Key Down event handler
private void TextBox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
//ONLY ACCEPTS NUMBERS
char c = Convert.ToChar(e.Key);
if (!c.Equals('0') && !c.Equals('1') && !c.Equals('2') && !c.Equals('3') && !c.Equals('4') &&
!c.Equals('5') && !c.Equals('6') && !c.Equals('7') && !c.Equals('8') && !c.Equals('9'))
{
e.Handled = true;
}
}
it does works preventing letters from a to z. However, if I enter symbols like !##$%^&*()_+, it stills accept them. What am I missing?
You can use Char.IsDigit
e. Handled = !Char.IsDigit(c);
But this won't help you much in case of copy\pasting.
Also check related question on the right. For example Create WPF TextBox that accepts only numbers
UPDATE
For letters only try
e.Handled = Char.IsLetter(c);
There is no reliable way to handle this on the key down or key up events because for some odd reason shift 4 which is the $ sign returns 4 not the key value.
The best workaround is to catch the value before it's used and check it is numeric then alert the user.
var IsNumeric = new System.Text.RegularExpressions.Regex("^[0-9]*$");
if (!IsNumeric.IsMatch(edtPort.Text))
{
showMessage("Port number must be number", "Input Error");
return;
}
In no way ideal but better that trying to teach your users that the dollar sign is now a number!
Try this code. But sometimes you see char that you pressed and it is removed immediately. Not the best solution but sufficient
private void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null)
return;
if (textBox.Text.Length == 0) return;
var text = textBox.Text;
int result;
var isValid = int.TryParse(text, out result);
if (isValid) return;
var selectionStart = textBox.SelectionStart;
var resultString = new string(text.Where(char.IsDigit).ToArray());
var lengthDiff = textBox.Text.Length - resultString.Length;
textBox.Text = resultString;
textBox.SelectionStart = selectionStart - lengthDiff;
}
this might help, this is what I used.
private void txtBoxBA_KeyDown(object sender, KeyRoutedEventArgs e)
{
// only allow 0-9 and "."
e.Handled = !((e.Key.GetHashCode() >= 48 && e.Key.GetHashCode() <= 57));
// check if "." is already there in box.
if (e.Key.GetHashCode() == 190)
e.Handled = (sender as TextBox).Text.Contains(".");
}

Objective-C ccKeyDown player movement

I currently working on a Cocos2D Mac Game in Objective-C.
I've got the movement working but i have one more question ..
I use this code to move my player, it is a fly so it needs free movement in all directions.
Keyboard event:
- (void)ccKeyDown:(NSEvent*)keyDownEvent
{
// Get pressed key (code)
NSString * character = [keyDownEvent characters];
unichar keyCode = [character characterAtIndex: 0];
// Player movement
if (keyCode == 119) {
playerMoveUp = TRUE;
} else if (keyCode == 115) {
playerMoveDown = TRUE;
}
if (keyCode == 100) {
playerMoveLeft = TRUE;
} else if (keyCode == 97) {
playerMoveRight = TRUE;
}
}
- (void)ccKeyUp:(NSEvent*)keyUpEvent
{
// Get pressed key (code)
NSString * character = [keyUpEvent characters];
unichar keyCode = [character characterAtIndex: 0];
// Player movement
if (keyCode == 119) {
playerMoveUp = FALSE;
} else if (keyCode == 115) {
playerMoveDown = FALSE;
}
if (keyCode == 100) {
playerMoveLeft = FALSE;
} else if (keyCode == 97) {
playerMoveRight = FALSE;
}
}
Gametime loop:
-(void) tick: (ccTime) dt
{
// Get player current position
NSInteger playerPositionX = player.position.x;
NSInteger playerPositionY = player.position.y;
// Player movement
if (playerMoveUp == TRUE) {
player.position = ccp(playerPositionX, playerPositionY + 1);
}
if (playerMoveDown == TRUE) {
player.position = ccp(playerPositionX, playerPositionY - 1);
}
if (playerMoveLeft == TRUE) {
player.position = ccp(playerPositionX + 1, playerPositionY);
}
if (playerMoveRight == TRUE) {
player.position = ccp(playerPositionX - 1, playerPositionY);
}
}
My problem is when my player is moving left it's not possible to add the up key the same time, so the player will be moving left and up. What is the best way to achieve this?
There is a simple-simple trick: declare an array of bool like bool arrows[4], where each element is an arrow button state and true == pressed. Now you set an array element to true in keyDown event and to false in keyUp. The last thing you need - a timer to check this array and move objects.
Actually, the timer a better solution than regular event handling because you can control "keys processing speed".