MousePressed gets wrong source JPanel - mouseevent

Im coding a simple movegame and i have some troubles with the MouseListener.
This is the View of the game
the single panels are defined in an Array and each of them has a mouse listener
for (int i=0; i<9; i++) {
labels[i] = new JLabel();
labels[i].setPreferredSize(new Dimension(70, 70));
if (numbers[i] != null) {
labels[i].addMouseListener(mausListener);
labels[i].setBorder(border);
labels[i].setText(Integer.toString(numbers[i]));
labels[i].setFont(font);
labels[i].setBackground(Color.LIGHT_GRAY);
labels[i].setHorizontalAlignment(SwingConstants.CENTER);
labels[i].setOpaque(true);
} else {
labels[i].setText("null");
labels[i].setVisible(false);
}
this.add(labels[i]);
}
numbers is an Array filled with the unsorted numbers:
[8, 2, 3, 1, 5, 4, 7, null, 6]
This is my mouseListener:
public void mousePressed(MouseEvent e) {
clicked = (JLabel) e.getSource();
if (clicked.getText() != "null") {
System.out.println(clicked.getText());
logik.move(Integer.parseInt(clicked.getText()));
System.out.println(Arrays.toString(logik.getNummern()));
}
}
The move function checks if the clicked label is a possible label and switches it with the null-label. This function was given by our professor so there will be no mistake in it.
Now the Problem is when I click the null-label after I clicked, for example, the "6" label, the mousePressed function give me the "6" label as source Object although I pressed the null-label.
I hope someone can help me out of this.
Thank you all :D

Related

I am trying to display SQL result on a list control using MFC

Please, I have list control on, I want to display my query result on a list control. The program runs without error, but it does not display the SQL result on the list control.
BOOL CClassDialog::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: Add extra initialization here
CString DSN;
DSN = _T("DRIVER=SQL Server;SERVER=DESKTOP-
DICUCDS\\SQL2K14;Trusted_Connection=Yes;APP=Microsoft\x00ae Visual Studio\x00ae 2013;WSID=DESKTOP-
DICUCDS;DATABASE=School");
CDatabase aDB;
try {
aDB.OpenEx(DSN);
CRecordset aRS(&aDB);
aRS.Open(CRecordset::forwardOnly, (L"SELECT DISTINCT Myclass FROM MyFacts"));
// populate Grids
ListView_SetExtendedListViewStyle(m_classlist, LVS_EX_GRIDLINES);
// Column width and heading
m_classlist.InsertColumn(1, L"Class", LVCFMT_LEFT, -1, 1);
m_classlist.InsertColumn(2, L"Age", LVCFMT_LEFT, -1, 1);
m_classlist.SetColumnWidth(0, 120);
m_classlist.SetColumnWidth(1, 200);
m_classlist.SetColumnWidth(2, 200);
while(!aRS.IsEOF())
{
CString strValue;
aRS.GetFieldValue(L"Myclass", strValue);
m_classlist.SetItemText(-1, 1, strValue);
//strValue.AddString(strValue);
aRS.MoveNext();
}
aRS.Close();
aDB.Close();
}
catch (CDBException * ex)
{
TCHAR buf[255];
ex->GetErrorMessage(buf, 255);
CString strPrompt(buf);
AfxMessageBox(strPrompt);
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CClassDialog::ResetListControl()
{
m_classlist.DeleteAllItems();
int iNbrOfColumns;
CHeaderCtrl* pHeader = (CHeaderCtrl*)m_classlist.GetDlgItem(0);
if (pHeader) {
iNbrOfColumns = pHeader->GetItemCount();
}
for (int i = iNbrOfColumns; i >= 0; i--) {
m_classlist.DeleteColumn(i);
}
}
Are you sure this is right? m_classlist.SetItemText(-1, 1, strValue);
If you research the official documentation for the CListCtrl (for example, here) you will see:
CString strText;
int nColumnCount = m_myListCtrl.GetHeaderCtrl()->GetItemCount();
// Insert 10 items in the list view control.
for (int i = 0; i < 10; i++)
{
strText.Format(TEXT("item %d"), i);
// Insert the item, select every other item.
m_myListCtrl.InsertItem(LVIF_TEXT | LVIF_STATE, i, strText,
(i % 2) == 0 ? LVIS_SELECTED : 0, LVIS_SELECTED, 0, 0);
// Initialize the text of the subitems.
for (int j = 1; j < nColumnCount; j++)
{
strText.Format(TEXT("sub-item %d %d"), i, j);
m_myListCtrl.SetItemText(i, j, strText);
}
}
You are making references to SetItemText but you have not actually added any elements into the list. The code before shows an example:
// Insert the item, select every other item.
m_myListCtrl.InsertItem(LVIF_TEXT | LVIF_STATE, i, strText,
(i % 2) == 0 ? LVIS_SELECTED : 0, LVIS_SELECTED, 0, 0);
I am not saying that you have to use that specific set of paramaters. But the point is that you must insert an item into the list before you can update it's properties. Or even set the properties at the moment you add it into the list.

How to make keyCode == ENTER update a string?

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.

display legend with Geotools JMapFrame

Shall anybody give some tips on how to display a legend for a shapefile in JMapFrame of Geotools? I have already created the style for the shapefile and I need a way to tell the users how the style is defined, that comes out the need of legend.
There is a package org.geotools.legend. But I do not know how to use it.
Thanks!
You need to iterate through the Styles FeatureTypeStyless Rules Symbolizers and draw a representative feature for each one. Something like:
private void drawLegend(BufferedImage img, Rule r) {
for (Symbolizer sym : r.symbolizers()) {
SimpleFeature feature = null;
if (sym instanceof LineSymbolizer) {
LineString line = drawer.line(new int[] { 1, 1, 10, 20, 20, 20 });
feature = drawer.feature(line);
} else if(sym instanceof PolygonSymbolizer) {
Polygon p = drawer.polygon(new int[] { 1, 1, 1, 18, 18, 18, 18, 1, 1,1 });
feature = drawer.feature(p);
} else if(sym instanceof PointSymbolizer || sym instanceof TextSymbolizer) {
Point p = drawer.point(10, 10);
feature = drawer.feature(p);
}
if(feature == null)
continue;
drawer.drawDirect(img, feature, r);
Graphics2D gr = img.createGraphics();
gr.setColor(Color.BLACK);
if (r.getDescription() != null && r.getDescription().getTitle() != null) {
gr.drawString(r.getDescription().getTitle().toString(), 20, 18);
}
}
}
And then you can draw those images to a JPanel or the map.
For a fully worked example see how GeoServer creates the response to a getLegendGraphic request.

My current GPS Position under Nutiteq is not properly updated

as basis for my GPS functionality I've taken HelloMap3D Example of Nutiteq (Thx Jaak) and I adapted to show my current GPS position light different of this example, so, no growing yelow circles but a fix blue translucent circle with a center point as my current Position and works fine except the update. It should erase the past position if location is changed, so that
this update happens as in the example in the method onLocationChanged
This is the code in my Main Activity
protected void initGps(final MyLocationCircle locationCircle) {
final Projection proj = mapView.getLayers().getBaseLayer().getProjection();
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
locationCircle.setLocation(proj, location);
locationCircle.setVisible(true);
}
// Another Methods...
}
}
I have adapted MyLocationCircle Class like this
public void update() {
//Draw center with a drawable
Bitmap bitmapPosition = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_home);
PointStyle pointStyle = PointStyle.builder().setBitmap(bitmapPosition).setColor(Color.BLUE).build();
// Create/update Point
if ( point == null ) {
point = new Point(circlePos, null, pointStyle, null);
layer.add(point);
} else { // We just have to change the Position to actual Position
point.setMapPos(circlePos);
}
point.setVisible(visible);
// Build closed circle
circleVerts.clear();
for (float tsj = 0; tsj <= 360; tsj += 360 / NR_OF_CIRCLE_VERTS) {
MapPos mapPos = new MapPos(circleScale * Math.cos(tsj * Const.DEG_TO_RAD) + circlePos.x, circleScale * Math.sin(tsj * Const.DEG_TO_RAD) + circlePos.y);
circleVerts.add(mapPos);
}
// Create/update line
if (circle == null) {
LineStyle lineStyle = LineStyle.builder().setWidth(0.05f).setColor(Color.BLUE).build();
PolygonStyle polygonStyle = PolygonStyle.builder().setColor(Color.BLUE & 0x80FFFFFF).setLineStyle(lineStyle).build();//0xE0FFFF
circle = new Polygon(circleVerts, null, polygonStyle, circle_data);
layer.add(circle);
} else {
circle.setVertexList(circleVerts);
}
circle.setVisible(visible);
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public void setLocation(Projection proj, Location location) {
circlePos = proj.fromWgs84(location.getLongitude(), location.getLatitude());
projectionScale = (float) proj.getBounds().getWidth();
circleRadius = location.getAccuracy();
// Here is the most important modification
update();
}
So, each time our Position changes is called onLocationChanged(Location location) Method and there will be called locationCircle.setLocation(location) and last there, it will be called update called.
The questions are, What am I making wrong? and How can I solve it?
Thank you in advance.
You create and add new circle with every update. You should reuse single one, just update vertexes with setVertexList(). In particular this line should be outside onLocationChanged cycle, somewhere in initGPS perhaps:
circle = new Polygon(circleVerts, null, polygonStyle, circle_data);

Instagram & Processing - Real time view

I'm working on a small app similar to instaprint and need some help. I'm using the source code from Globalgram by Andrew Haskin, it searches instagram for a particular hashtag and displays the most recent image posted with that hashtag. The problem is it only does it once, I need it to continuously search for the hashtag and display an image when a new one is added, so a refresh, I've been tinkering with it but to no avail. Any help would be greatly appreciated
Code Below :
import com.francisli.processing.http.*;
PFont InstagramFont;
PImage backgroundimg;
PImage brand;
PImage userphoto;
PImage profilepicture;
String username;
String tag;
String[] tagStrings;
com.francisli.processing.http.HttpClient client;
void setup() {
size(580, 900);
smooth();
backgroundimg = loadImage("iso_background.jpg");
brand = loadImage("iso.jpg");
InstagramFont = loadFont("Helvetica-Bold-36.vlw");
client = new com.francisli.processing.http.HttpClient(this, "api.instagram.com");
client.useSSL = true;
//// instantiate a new HashMap
HashMap params = new HashMap();
//// put key/value pairs that you want to send in the request
params.put("access_token", "------ACCESS TOKEN HERE------");
params.put("count", "1");
client.GET("/v1/tags/coffee/media/recent.json", params);
}
void responseReceived(com.francisli.processing.http.HttpRequest request, com.francisli.processing.http.HttpResponse response) {
println(response.getContentAsString());
//// we get the server response as a JSON object
com.francisli.processing.http.JSONObject content = response.getContentAsJSONObject();
//// get the "data" value, which is an array
com.francisli.processing.http.JSONObject data = content.get("data");
//// get the first element in the array
com.francisli.processing.http.JSONObject first = data.get(0);
//// the "user" value is another dictionary, from which we can get the "full_name" string value
println(first.get("user").get("full_name").stringValue());
//// the "caption" value is another dictionary, from which we can get the "text" string value
//println(first.get("caption").get("text").stringValue());
//// get profile picture
println(first.get("user").get("profile_picture").stringValue());
//// the "images" value is another dictionary, from which we can get different image URL data
println(first.get("images").get("standard_resolution").get("url").stringValue());
com.francisli.processing.http.JSONObject tags = first.get("tags");
tagStrings = new String[tags.size()];
for (int i = 0; i < tags.size(); i++) {
tagStrings[i] = tags.get(i).stringValue();
}
username = first.get("user").get("full_name").stringValue();
String profilepicture_url = first.get("user").get("profile_picture").stringValue();
profilepicture = loadImage(profilepicture_url, "png");
String userphoto_url = first.get("images").get("standard_resolution").get("url").stringValue();
userphoto = loadImage(userphoto_url, "png");
//noLoop();
}
void draw() {
background(255);
imageMode(CENTER);
image(brand, 100, height/1.05);
if (profilepicture != null) {
image(profilepicture, 60, 70, 90, 90);
}
imageMode(CENTER);
if (userphoto != null) {
image(userphoto, width/2, height/2.25, 550, 550);
}
textFont(InstagramFont, 20);
if (username != null) {
text(username, 110, 115);
fill(0);
}
textFont(InstagramFont, 15);
if ((tagStrings != null) && (tagStrings.length > 0)) {
String line = tagStrings[0];
for (int i = 1; i < tagStrings.length; i++) {
line += ", " + tagStrings[i];
}
text(line, 25, 720, 550, 50);
fill(0);
}
}
AFAIK it should be the
client.GET("/v1/tags/coffee/media/recent.json", params);
line that actually polls Instagram. Try wrapping that in a function like this:
void getGrams() {
client.GET("/v1/tags/coffee/media/recent.json", params);
}
then call that once in setup() and then again when you want to ...
I'd start with trying to do it on mousePressed() or keyPressed(), so that it only fires once when you really want it to
Don't try to do it in draw() without a timer (something like if(frameCount % 5000 == 0) which will fire every five seconds ((which may be too fast still but you get the idea))