Categories
discuss

How to add picture out of JFrame, attached to border

Hi I Would like add to my JFrame border some image. Is this Possible to attach picture to borders for JFrame and create it as 1 object ?

Something like this:

enter image description here

Answer

I’m not sure if it’s possible to add the image directly to the border of a JFrame (suggestions welcome). I decided to solve this issue by using a transparent content pane, and using an inner frame to “appear” like the outer frame.

The code is pretty simple, however, let me know if you’d like an explanation of how the code works.

Here’s the minimum code you’ll need to get up and running.

You’ll need to provide your own transparent-phone.png image, in the root of the classpath (i.e. next to your PhoneWindow.java file, in the root package).

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;

public class PhoneWindow {

    public static void main(String[] args) {
        new PhoneWindow();
    }

    public PhoneWindow() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    final JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    // create the  inner frame
                    final JInternalFrame frame2 = new JInternalFrame("My Telephone");
                    frame2.setClosable(true);
                    frame2.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
                    // add elements to the outer frame
                    frame.setUndecorated(true);
                    frame.setBackground(new Color(0, 0, 0, 0));
                    JPanel pane = new TranslucentPane();
                    frame.setContentPane(pane);
                    frame.setLayout(new BorderLayout());
                    // add inner frame and phone picture
                    frame.add(frame2, BorderLayout.CENTER);
                    frame.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/transparent-phone.png")))), BorderLayout.EAST);
                    frame.setLocationRelativeTo(null);
                    frame.setMinimumSize(new Dimension(400, 300));
                    frame.pack();
                    // show
                    frame2.setVisible(true);
                    frame.setVisible(true);
                } catch (Throwable ex) {
                    ex.printStackTrace();
                }

            }
        });
    }

    public class TranslucentPane extends JPanel {

        public TranslucentPane() {
            setOpaque(false);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setComposite(AlphaComposite.SrcOver.derive(0f));
            g2d.setColor(getBackground());
            g2d.fillRect(0, 0, getWidth(), getHeight());
        }

    }

}

Here’s the full Java class (including close and draggable behaviour)

https://gist.github.com/nickgrealy/16901a6428cb79d4f179

And here’s a screenshot of the final product

N.B. the transparent sections inside/outside the phone.

The final result with transparency.

References:

Categories
discuss

How to change Android version and code version number?

How to change Android version and code version number Android Studio? I want to change apk file (app) on Google Play and I need to change Android version and code version number. I tried with this in AndroidManifest.xml file in Android Studio:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bestsoftcorporation.circle.app"
android:versionCode="101"
android:versionName="2.0">

But it does not work. When I tried to publish it on Google Play it display that I must to change Android version name and code.

Answer

Go in the build.gradle and set the version code and name inside the defaultConfig element

defaultConfig {
    minSdkVersion 9
    targetSdkVersion 19
    versionCode 1
    versionName "1.0"
}

screenshot

Categories
discuss

IDE for AngularJS development with debugging, code complete and profiling capabilities?

What IDE would you recommend for AngularJS, or even JavaScript development in general that has similar features like Eclipse for Java based development?

I have done some research on google, but the discussions are mostly outdated and wanted to check in SO to get a more relevant recommendation.

Any help or tips would be really appreciated. Thank you.

Answer

WebStorm is the best for Javascript, AngularJs and web development in general. You can create lot of user defined code helpers and can create controllers e.t.c easily with that.

Categories
discuss

Socket Programming with Python server and Android client

I want to setup a socket interface. PC side runs a very simple socket server written in Python to test the connection:

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 5000                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

An Android client application will connect to PC:

package com.example.androidsocketclient;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

    private Socket socket;

    private static final int SERVERPORT = 5000;
    private static final String SERVER_IP = "192.168.2.184";

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

        new Thread(new ClientThread()).start();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void onClick(View view) {
        try {
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    }

}

However, I cannot establish a connection between PC and Android device. Any idea to fix this?

Answer

As you haven’t detailed if you’re using either private or public IPs, it might be any of the following issues:

If you’re using private connections, it’s obvious it’s not a router-firewall related problem as you are under the same net, so there are only a few possibilities:

  • There’s nothing listening on that port on that IP on the server-side
  • There’s a local firewall on the server-side that is blocking that connection attempt
  • You are not using WIFI so you’re not under the same net.

You should make sure you can open that service some ther way, that would help you debugging where the culprit is. If you’ve already done this, I’d suggest using some debugging tool to trace TCP packets (I don’t know either what kind of operating system you use on the destination machine; if it’s some linux distribution, tcpdump might help; under Windows systems, WireShark might be useful).

If you’re using public IPs, sum up a router blocking firewall, which means that this port might be closed/filtered on the server side, just open it.

All that assuming you have the android.permission.INTERNET permission in your AndroidManifest.xml file.

Categories
discuss

Convert Exception to JSON

Is it possible, in Java 7, to convert an Exception object into Json?

example:

try {      
    //something
} catch(Exception ex) {     
    Gson gson = new Gson();
    System.out.println(gson.toJson(ex));
}

Answer

In theory, you could also iterate over the elements in a stack trace and generate something that looks like:

{ "NullPointerException" :
    { "Exception in thread "main" java.lang.NullPointerException",
        { 
          "Book.java:16" : "com.example.myproject.Book.getTitle",
          "Author.java:25" : "at com.example.myproject.Author.getBookTitles",
          "Bootstrap.java:14" : "at com.example.myproject.Bootstrap.main()"
        }
    },
  "Caused By" :
    { "Exception in thread "main" java.lang.NullPointerException",
        { 
          "Book.java:16" : "com.example.myproject.Book.getTitle",
          "Author.java:25" : "at com.example.myproject.Author.getBookTitles",
          "Bootstrap.java:14" : "at com.example.myproject.Bootstrap.main()"
        }
    }
}

You can iterate the exception like this:

catch (Exception cause) {
    StackTraceElement elements[] = cause.getStackTrace();
    for (int i = 0, n = elements.length; i < n; i++) {       
        System.err.println(elements[i].getFileName()
            + ":" + elements[i].getLineNumber() 
            + ">> "
            + elements[i].getMethodName() + "()");
    }
}
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..