Categories
discuss

Java Swing adding mouse Listener (inner class) for an array of buttons leads to malfunction

Ok, so the program I want to build is simple. There are five buttons named from 0 to 4. If any of the buttons are pressed, then the number 0 to 4 is printed in console.

enter image description here

I have used a GridLayout to place the buttons in the frame. And to set up each button I have created a method, inicializarIG().

This inicializarIG() method creates an array of 5 buttons and inside a for loop it does:

  • Create an instance of a button for each cell in the array of buttons.
  • Set up a mouseListener for each button. The value to print in each Listener is different, it is determined by the index of the loop (AND I WANT TO DO IT BY USING THE INDEX!).
  • Add The button to the main frame.

Surprisingly, This simple program doesn´t work properly. It always print the number “5” no matter what button is pressed:

enter image description here

NOTE: I had to put the index var outside the inicializarIG() method in order to fulfill the var scope for the Listeners. I don’t know if the problem is related, just saying in cause it might help.

THE CODE:

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;


public class IGrafica {

    private JFrame frame;
    public int index=0;



    public IGrafica(){
        frame = new JFrame();
        configureFrame();
        inicializarIG();

    }

    public void configureFrame(){
        frame.setBounds(100,100,400,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(1,5)); //
    }


    public void inicializarIG(){

        //Buttons

        JButton [] botones = new JButton [5];

        //Loop to set up buttons and add the mouseListener
        for (index = 0; index < botones.length; index++) {
            botones[index] = new JButton(Integer.toString(index));


            //Set up each listener 
            botones[index].addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    System.out.println(index);
                    //texto.setBackground(colores[index]);
                }           
            });

            //Add the button
            frame.getContentPane().add(botones[index]);

        }       
    }



    public void visualizate(){
        frame.setVisible(true);
    }



    public static void main(String[] args) {        
        IGrafica window = new IGrafica();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                window.visualizate();
            }
        });

    }
}

Thank you in advance. Any idea will be welcomed.

Jesús

Answer

First of all, don’t use a MouseListener for this, but rather use an ActionListener, since this works best for buttons. Next of all, you need to remember that your listener is a class of its own, and it needs a variable of its own to store its own index, else it uses the final value of the loop index which is not what you want. Either this or use the ActionEvent’s actionCommand property, a value which will match the text of the button. So:

botones[index].addActionListener(new MyActionListener(index));

and

// a private inner class
private class MyActionListener implements ActionListener {
    private int index;

    public MyActionListener(int index) {
        this.index = index;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("index is: " + index);
        System.out.println("Action Command is: " + e.getActionCommand());
    }
}

Or if you want to use an anonymous inner class:

        botones[index].addActionListener(new ActionListener() {
            private int myIndex;

            {
                this.myIndex = index;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("index is: " + myIndex);
            }
        });
Categories
discuss

How to set hibernate.hbm2ddl.auto in Spring with Annotations and pure Java

How would one go about setting up the following in Spring using only Java and annotations.

<property name="hibernate.hbm2ddl.auto" value="update"/>

I amIt should be possible and I do believe it is a lot cleaner to make projects xml free.

PS: This shouldn’t be important but I’m running this on Heroku.

Answer

Added this to the class where the dataSource() is and it fixed my issue.

final Properties hibernateProperties() {
    final Properties hibernateProperties = new Properties();

    hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
    hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    hibernateProperties.setProperty("hibernate.show_sql", "true");

    return hibernateProperties;
}

Full example is here https://github.com/arose13/Heroku-Spring-Postgres-Example.

EDIT PS: For this line hibernateProperties.setProperty("hibernate.hbm2ddl.auto","update"); check out this stackoverflow question to figure out the best value if update isn’t right for you.

Categories
discuss

Debug Cordova Plugin

How do you debug the non-js portion of a cordova plugin? I have found several discussions on Stack Overflow, but none of them have given me an answer on how I throw my plugin into an IDE, and be able to breakpoint it.

Debugging the JS is no problem and makes sense, but I have no idea how to either print out a log from the android/ios side or hit breakpoints.

I am in the process of making a small change to InAppBrowser to allow Cookie read/writing and I desperately need to know how to monitor this.

Any help would be vastly appreciated.

Answer

Create a new cordova project

cordova create debugPlugins com.debug.plugis debugPlugins

go to the new folder

cd debugPlugins

add ios and android platforms

cordova platform add ios android

and the inAppBrowser plugin (or any other you want to debug)

cordova plugin add cordova-plugin-inappbrowser

When you added android and ios platforms, two native project where created, you can open and debug them.

  • For ios, go to platforms/ios and open the debugPlugins.xcodeproj
  • For android open android studio, go to File->New->Import Project and select the platforms/android folder
Categories
discuss

Android WebView app crashing in emulator: null Application Context?

I’m developing a very simple Android app on a Mac in AndroidStudio and I’ve created an AVD based on the Nexus S. The app compiles with no issues, the emulator launches and then I get errors in logcat and the app crashes. In the emulator, an error dialog displays with the message “Unfortunately App has stopped”

Here’s the logcat output (error level):

10-01 13:59:27.813  14114-14114/com.company.app E/SysUtils﹕ ApplicationContext is null in ApplicationStatus
10-01 13:59:27.832  14114-14114/com.company.app E/libEGL﹕ validate_display:255 error 3008 (EGL_BAD_DISPLAY)
10-01 13:59:27.832  14114-14114/com.company.app E/libEGL﹕ validate_display:255 error 3008 (EGL_BAD_DISPLAY)
10-01 13:59:27.832  14114-14114/com.company.app E/chromium﹕ [ERROR:gl_surface_egl.cc(327)] No suitable EGL configs found.
10-01 13:59:27.832  14114-14114/com.company.app E/chromium﹕ [ERROR:gl_surface_android.cc(23)] GLSurfaceEGL::InitializeOneOff failed.
10-01 13:59:27.832  14114-14114/com.company.app E/chromium﹕ [ERROR:browser_main_loop.cc(698)] GLSurface::InitializeOneOff failed
10-01 13:59:27.854  14114-14114/com.company.app E/DataReductionProxySettingListener﹕ No DRP key due to exception:java.lang.ClassNotFoundException: com.android.webview.chromium.Drp
10-01 13:59:28.530  14114-14165/com.company.app A/chromium﹕ [FATAL:gl_surface_android.cc(58)] Check failed: kGLImplementationNone != GetGLImplementation() (0 vs. 0)
10-01 13:59:28.530  14114-14165/com.company.app A/libc﹕ Fatal signal 6 (SIGABRT), code -6 in tid 14165 (GpuThread)

I’m assuming that the first error related to ApplicationContext is the cause of the other errors, but I’m not sure about that. I’ve tried about 10 different methods for setting context, but the ApplicationContext error persists.

My main questions: Is the ApplicationContext error the root cause of the crash? If not, what is? What might I try to fix it?

Here’s the complete application code for reference:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.company.app" >
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <uses-permission android:name="android.permission.INTERNET" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

MainActivity.java

package com.company.app;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebSettings;

public class MainActivity extends AppCompatActivity {

    private String appUrl = "http://company.com/mobile/index.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView myWebView = (WebView) findViewById(R.id.webView);
        myWebView.setWebViewClient(new MyWebViewClient());

        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        myWebView.loadUrl(appUrl);
    }
}

MyWebViewClient.java

package com.company.app;

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MyWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().equals("company.com")) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    }
}

Answer

Here’s the logcat output

That is not a Java stack trace, and therefore is not what you’re looking for.

I’m assuming that the first error related to ApplicationContext is the cause of the other errors, but I’m not sure about that

That is some spurious message that you will see, even from apps that run fine.

If not, what is?

As ozbek notes, your <uses-permission> element needs to be moved outside of <application> and made a direct child of <manifest>. Your Java stack trace should mention a missing INTERNET permission.

It is possible that there are other problems, but that’s definitely one.

Categories
discuss

How can I animate a calculated position with JQuery

So I have a variable with a calculated position that centers the element with JQuery, reason I did this is because I will not know the width of the element so I made it dynamic like so.

var $x = $("#line").outerWidth();

var $result = "calc( 50% - " + $x +"px / 2 )";

Then I tried to animate it to the center (value of $result) like so:

   $("#line").animate({ 
        "left": $result,
        "top" : "15px"

    }, 1000 );

Sadly this did not work, only the top value moved.

Any advice is greatly appreciated, thank you.

Answer

jsBin demo

If you already use calc (CSS3) than you’ll have nothing against using in your CSS:

Using CSS3 transition and calc()

#line{
    transition: 1s;
    /*...other stuff...*/
}

and in your jQuery (instead of .animate())

var outW2 = $("#line").outerWidth() / 2;

$("#line").css({ 
  left : "calc(50% - "+ outW2 +"px)",
  top  : 70
});

Using .animate() and negative margin (for centering)

For all older browsers, you can simply use .animate() as you did,
moving the element to 50% but also to a -half-width left margin (to center it):

var outW2 = $("#line").outerWidth() / 2;

$("#line").animate(){
  left: "50%",
  marginLeft : -outW2
}, 1000);

jsBin demo (crossbrowser solution)

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..