Java application on Microsoft Surface not full screen - java

I have a Java application, developed in eclipse and with an exe wrapper. It runs full screen on a win 7 desktop, but not on a Win 8 surface (original) with Intel HD Graphics 4000. When run on the surface it has black space all around it. I found multiple references to updating the graphics driver to get extra options about how the screen scales. The latest drivers from Intel are rejected when I try to install them. If I try to do an update via device manager it says I am current. Looking for any suggestions/info. Thank you.
--- add ons ---
Surface has Java 8 update 65
public class Fullscreen
{
private static GraphicsDevice _device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
private static DisplayMode _oldMode = null;
public static Drawable _drawable;
public static BufferStrategy _bufStrat;
public static int _frameCount;
public static long _secondTrack;
//==========================================================================
/**
* Set some video related stuff
* #param frame - The App's JFrame
* #return - true if sucessful
*/
public static boolean set( JFrame frame )
{
frame.setResizable ( false );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
if (MainBase._fullScreen) // Is true for this version
{
frame.setUndecorated ( true );
frame.setIgnoreRepaint ( true );
if (MainBase._fullScreen && !_device.isFullScreenSupported())
{
System.err.println( "Full screen not supported" );
return false;
}
try
{
_device.setFullScreenWindow( frame );
}
catch ( Exception e )
{
_device.setFullScreenWindow( null );
System.err.println( "Failed setting full screen" );
return false;
}
_oldMode = _device.getDisplayMode();
//TODO: what to do about display refresh vs frame rate
DisplayMode displayMode = new DisplayMode( MainBase._screenW, MainBase._screenH, 32, 60); //MainBase._fps );
if (displayMode != null && _device.isDisplayChangeSupported())
{
try
{
_device.setDisplayMode( displayMode );
}
catch (Exception e)
{
_device.setDisplayMode( _oldMode );
_device.setFullScreenWindow( null );
System.err.println( "Failed setting full screen mode" );
return false;
}
}
}
//System.out.println( "Display Mode W " + MainBase._screenW + " H " + MainBase._screenH + " BitDepth " + 32 );
return true;
}
----- Important info although not solved -----
I tried to update the surface to Win 10. The update failed. I then rolled back to Win 8. After I reinstalled my extra stuff the application ran at full screen. Until it crashed and I had to kill it in Task Manager. After that it was back to not full screen. Something obviously got tweaked or carried of from that run. Not a solution but an important lead to follow.

Related

Java & Eclipse: Can I print to different output consoles at the same time?

I am learning Java (SE 8) using the Eclipse IDE (Oxygen) on Windows. I have done some "hobby" programming before but this is my first formal class in the subject. I want to be able to print the output that the assignment requires in the normal console (System.out.println) and print informational what's happening text into a different console at the same time.
In pseudocode what I want is something like:
printToConsole1("Normal program outputs.");
printToConsole2("Behind the scenes information.");
Can I do anything like this in Java?
Using a logging framework like Logback or Log4j2, you can write messages at specific logging levels or from different loggers to two separate files. In this vein, you can accomplish what you're looking for; you would write out the "normal" output to either the console or one file, and the behind-the-scenes information to a separate file.
How to configure these in your application is well outside the scope of Stack Overflow, but I strongly encourage you to peruse them.
Hey, there's no one saying you can't have two terminal windows open, y'know?
You can print to standard err (System.err.println()) and my IDE (which is not Eclipse) will format those lines differently -- they show up in red, making them easy spot.
Regarding swing-console, no I was thinking of something different. Namely just using the logging framework as Makoto suggested, and then just using a log handler that will display log lines to a window. The following is a short example I created.
/**
* A log handler which creates a visible window for logging output.
*
* <p>A WindowHandler is a standard log handler which may be utilized
* in just the same was as any other log handler.</p>
*
* <p>In addition, a convenience static method is provided, WindowHandler.show(),
* which will programmatically install a root handler and display a window,
* allowing debugging output to be easily captured and viewed on screen.</p>
*
* #author Brenden
*/
public class WindowHandler extends java.util.logging.Handler {
// These static globals must be accessed on the EDT only!
private static WindowHandler globalHandler;
private static final ArrayList<WeakReference<WindowHandler>> windowList =
new ArrayList<>();
private JTextArea text;
private JFrame logWindow;
/**
* Returns the window component (usually a JFrame) associated with this
* WindowHandler.
*
* #return The top-level window for this handler.
*/
public Component getWindow() {
return logWindow;
}
/**
* Returns the JTextArea associated with the logging output captured by
* this handler.
*
* #return A JTextArea where logging is displayed.
*/
public JTextArea getTextArea() {
return text;
}
/**
* A list of ALL WindowHandler created so far in the system.
*
* <p>This list is useful for getting a list of windows on screen, for
* example, and then performing some operation on these windows. For
* example, hiding all windows, or closing them, or tiling them on screen
* for easier viewing.</p>
*
* #return An array list of all current window handlers.
*/
public static ArrayList<WindowHandler> getHandlers() {
ArrayList<WindowHandler> retVal = new ArrayList<>();
for( WeakReference<WindowHandler> wr : windowList ) {
WindowHandler h = wr.get();
if( h != null ) retVal.add( h );
}
return retVal;
}
/**
* A convenience method for starting an instance of a WindowHandler.
*
* <p>Call this method at the beginning of your program. After calling
* this method, all debugging output will be captured by the
* WindowHandler. Note that individual loggers still have their respective
* log levels. WindowHandler is set to Level.ALL by default, but won't
* receive output from loggers that have their own levels set too high
* to capture output.</p>
*/
public static synchronized void show() {
utilEDTWait( () -> {
if( globalHandler == null ) {
Logger root = Logger.getLogger( "" );
root.addHandler( globalHandler = new WindowHandler() );
} else {
globalHandler.getWindow().setVisible( true );
}
} );
}
/**
* Creates a new WindowHandler.
*
* <p>This method creates a new handler, sets its level to ALL, and creates
* the necessary Swing components on the EDT, and displays those components
* as well. After creation, this handler may still be configured as normal
* for any other logging handler.</p>
*/
public WindowHandler() {
utilEDTWait( () -> {
setLevel( Level.ALL );
JFrame frame = new JFrame( "DEBUG" );
text = new JTextArea();
text.setEditable( false );
text.setPreferredSize( new Dimension( 300, 300 ) );
JScrollPane scroll = new JScrollPane( text );
frame.add( scroll );
frame.setDefaultCloseOperation( JFrame.HIDE_ON_CLOSE );
frame.pack();
frame.setLocation( windowList.size()*20, windowList.size()*20 );
frame.setVisible( true );
logWindow = frame;
windowList.add( new WeakReference<>( this ) );
} );
}
#Override
public void publish( LogRecord record ) {
SwingUtilities.invokeLater( () -> {
StringBuilder log = new StringBuilder( text.getText() );
log.append( record.getMessage() );
log.append( " -- " );
log.append( record.getLoggerName() );
log.append( " : " );
log.append( record.getLevel() );
log.append( " // " );
log.append( new Date( record.getMillis() ) );
log.append( "\n" );
text.setText( log.toString() );
} );
}
#Override
public void flush() {
}
#Override
public void close() throws SecurityException {
}
private static void utilEDTWait( Runnable r ) {
if( SwingUtilities.isEventDispatchThread() ) {
r.run();
} else {
try {
SwingUtilities.invokeAndWait( r );
} catch( InterruptedException ex ) {
Thread.currentThread().interrupt();
throw new RuntimeException( ex );
} catch( InvocationTargetException ex ) {
Logger.getLogger( WindowHandler.class.getName() ).log( Level.SEVERE, null, ex );
}
}
}
}
No. Your Java Application has the same limitations as any process: a standard input (System.in), a standard output (System.out), and standard error output (System.err), and both the regular and error output are displayed in the same Console. They are, however, displayed using different colors. Typically you would either wrap invocations of one using a master boolean value as an on/off switch, or use a logging library of some kind that would make the two kinds of output easier to differentiate.
Separating the two into consoles of their own would make for an interesting feature request.

Bukkit ProtocolLib Nametags

I am trying to change the name above a players entity. I have successfully done this but it has a side effect of changeing the players skin to the default. How can I change the player's nametag without resetting their skin.
Plugin Librarys Used
ProtocolLib
PacketWrapper
Code used to change name
public void changeNameOnHead(Player player, String name) {
PlayerInfoData pid = new
PlayerInfoData(WrappedGameProfile.fromPlayer(player), 1,
EnumWrappers.NativeGameMode.SURVIVAL,
WrappedChatComponent.fromText(player.getName()));
WrapperPlayServerPlayerInfo wpspi = new WrapperPlayServerPlayerInfo();
wpspi.setAction(EnumWrappers.PlayerInfoAction.REMOVE_PLAYER);
wpspi.setData(Collections.singletonList(pid));
for (Player p: Bukkit.getOnlinePlayers()) {
if (p.equals(player)) {
continue;
}
p.hidePlayer(player);
wpspi.sendPacket(p);
}
ProtocolLibrary.getProtocolManager().addPacketListener(
new PacketAdapter(RoleplayEngine.Instance,
PacketType.Play.Server.PLAYER_INFO) {
#Override
public void onPacketSending(PacketEvent event) {
if (event.getPacket().getPlayerInfoAction().read(0) != EnumWrappers.PlayerInfoAction.ADD_PLAYER) {
return;
}
PlayerInfoData pid =
event.getPacket().getPlayerInfoDataLists().read(0).get(0);
if (pid.getProfile().getUUID() !=
player.getUniqueId()) return;
PlayerInfoData newPid = new PlayerInfoData(
pid.getProfile().withName(name),
pid.getPing(),
pid.getGameMode(),
WrappedChatComponent.fromText(name)
);
event.getPacket().getPlayerInfoDataLists().write(0,
Collections.singletonList(newPid));
}
}
);
for (Player p: Bukkit.getOnlinePlayers()) {
if (p.equals(player)) {
continue;
}
p.showPlayer(player);
}
}
You can try to use this library available in github to change the player's name and skin.
Quick example of usage:
PlayerDisplayModifier p = new PublicDisplayModifier(plugin);
p.changeDisplay(myPlayer, "SkinPlayer", "NewName");
This works if your server is 1.8 and lower, not sure if it works on higher versions.
If your server version is higher than 1.8, you can try using NickNamerIntegratedApi, a plugin that also has an API for devs. It's open sourced, so you can probably dig for the piece of code that makes the nick change possible
Lastly, you can also try to use md-5's iTAG, and a good fork of it by ataranlen

Parrot AR.Drone 2.0 - JavaDrone (Get the drone details E.G. Battery Level, Altitude, Speed etc)?

I am working on Parrot AR. Drone project. The libraries are downloaded and implemented in this project from JavaDrone website (https://code.google.com/p/javadrone/downloads/list). However, although I did included the all the correct libraries and make the right class call to get the method, it still cannot return me the correct information. All the results returned appeared to be "false". Any idea what happening on this code? Please help me :(
So what I did is I have 2 buttons : (i) connect (ii) take off buttons. The Connect button function is for establish connection to drone while Take off button is used for make the drone fly move a bit and return me the drone's NAV navigation data. Sadly all the returned NAV data appears not working.
Note : This code is working fine upon code compilation. But it just cannot return me the correct & valid NAV data from drone.
private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("Connect?");
drone = new ARDrone();
data = new NavData();
drone.playLED(10,10,10);
drone.connect();
drone.clearEmergencySignal();
System.err.println("Ready to connect!!");
// Wait until drone is ready
drone.waitForReady(CONNECT_TIMEOUT);
System.err.println("Drone State: " + drone.getState());
// do TRIM operation
drone.trim();
System.err.println("Congratulation! You have connected to Drone!");
System.out.println("You can issue flight commands now!");
batteryStatus.setText("0" + "%");
batteryStatus.setForeground(Color.ORANGE);
batteryStatus.setText("" + data.getBattery());
}
private void jButtonTakeOffActionPerformed(java.awt.event.ActionEvent evt) {
System.err.println("Current Drone State : " + drone.getState().toString());
System.err.println("Taking off");
drone.takeOff();
Thread.sleep(4000);
System.err.println("**********\nMOVE\n**********");
drone.move(0.0f, 150.5f, 500.0f, 0.0f);
Thread.sleep(1000);
System.err.println("******************************************");
System.err.println("Drone Infomation");
System.err.println("Battery Too High ? " + data.isBatteryTooHigh());
System.err.println("Battery Too Low ? " + data.isBatteryTooLow());
System.err.println("Drone Flying ? " + data.isFlying());
System.err.println("Control Received ? " + data.isControlReceived());
System.err.println("Motor Down ? " + data.isMotorsDown());
System.err.println("Not Enough Power ?" + data.isNotEnoughPower());
System.err.println("Trim Received ? " + data.isTrimReceived());
System.err.println("Trim Running? " + data.isTrimRunning());
System.err.println("Trim succeded? " + data.isTrimSucceeded());
System.err.println("PIC Number OK? "+ data.isPICVersionNumberOK());
System.err.println("******************************************");
Thread.sleep(5000);
drone.sendAllNavigationData();
drone.land();
}
Output :
******************************************
Drone Infomation
Battery Life: 0.0%
Battery Too High ? false
Battery Too Low ? false
Drone Flying ? false
Control Received ? false
Motor Down ? false
Not Enough Power ?false
Trim Received ? false
Trim Running? false
Trim succeded? false
PIC Number OK? false
********************************************
Update:
What I did was followed John's suggestion. I did implemented all the neccessary methods and NavDataListener for getting the NavData from drone.
import com.codeminders.ardrone.ARDrone;
import com.codeminders.ardrone.ARDrone.VideoChannel;
import com.codeminders.ardrone.NavData;
import com.codeminders.ardrone.NavDataListener;
public class arDrone extends javax.swing.JFrame implements Runnable, NavDataListener{
public ARDrone drone;
public NavData data = new NavData();
public arDrone(String text) {
//FreeTTS speech text
this.text=text;
}
public arDrone() {
initComponents();
setIcon();
initDrone();
}
private void initDrone() {
try {
drone = new ARDrone();
data = new NavData();
drone.addNavDataListener(this);
} catch (UnknownHostException ex) {
System.err.println(ex);
return;
}
}
public void navDataReceived(NavData nd) {
System.err.println("Testing navDataReceived is running...");
updateBatteryStatus(nd.getBattery());
this.flying.set(nd.isFlying());
}
private void updateBatteryStatus(final int value) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
batteryStatus.setText(value + "%");
if (value < 15) {
batteryStatus.setForeground(Color.RED);
} else if (value < 50) {
batteryStatus.setForeground(Color.ORANGE);
} else {
batteryStatus.setForeground(Color.GREEN);
}
}
});
}
The problem is that you are not doing anything to actually get navdata. You can't just create a NavData object and hope it gets filled in with valid data--It won't.
You need to use the com.codeminders.ardrone.NavDataListener interface.
Implement the NavDataListener interface, and the
navDataReceived method.
Add your listener using the ARDrone
method addNavDataListener.
In your navDataRecieved method
you will receive a NavData object with valid telemetry data.
Do you set the Drone IP address? According to sources the default IP for the drone is 192.168.1.1.
You can call another constructor to set the IP:
drone = new ARDrone(InetAddress.getByName("xxx.xxx.xxx.xxx"));
replace xxx.xxx.xxx.xxx with the actual drone IP.

LeJOS NXT Programming

iam a beginner in Programming and trying to make a Cleaning Robot NXT
i attached ( Ultrasonic Sensor) ,and ( Sound Sensor )
the job of the Robot is that when i Clap it have to start moving Forward and when the UltraSonic Sensor sees Something on the way it must turns around and keep going Forward .
The Problem is that when it turns it doesn't keep moving Forward till i clap again !!!!!
and this is the code that i wrote :
public static void main(String[] args) {
// TODO Auto-generated method stub
TouchSensor touch = new TouchSensor(SensorPort.S2);
SoundSensor sound = new SoundSensor( SensorPort.S4 );
UltrasonicSensor sonic = new UltrasonicSensor( SensorPort.S3);
Motor.A.setSpeed( 400 );
Motor.C.setSpeed( 400 );
Button.waitForAnyPress();
int SoundValue;
SoundValue = sound.readValue();
System.out.print(SoundValue);
do {
if ( sound.readValue() > 50 ) {
// PROBLEM:
while ( sonic.getDistance() > 30 ){
Motor.B.backward();
Motor.A.backward();
Motor.C.backward();
}
{
Motor.A.rotate( -185, true );
Motor.C.rotate( 185, true );
}
};
}
while( Button.readButtons() != Button.ID_ESCAPE );
}
Can any one help solving this Problem please?????
thnx Any way .
The think the loop is slightly wrong...
Basically, I think you need a flag to indicate that the bot should be moving, so that when you clap, it flips the flag...
boolean move = false;
do {
if ( sound.readValue() > 50 ) {
move = !move;
}
while ( sonic.getDistance() > 30 ){
Motor.B.backward();
Motor.A.backward();
Motor.C.backward();
}
if (move) {
Motor.A.rotate( -185, true );
Motor.C.rotate( 185, true );
}
} while( Button.readButtons() != Button.ID_ESCAPE );
Or something similar. Otherwise, it will only move when there is another sound
I'd also just like to say, I'm very jealous ;)

How to Detect workstation/System Screen Lock/unlock in windows OS using java?

I'm trying to note down workstation/System screen Lock and Unlock of each employee working in windows OS. I needed to store these record in a DataBase, using JAVA. I have searched all over and got on idea how to do it using JAVA. where ever I searched I get code for VB only.
You can do it in pure Java using JNA. Add jna.jar and jna-platform.jar to your project. And in this file com.sun.jna.platform.win32.Win32WindowDemo there is a full example of lock and unlock listener and much more. Here is the necessary code from thah Win32WindowDemo:
public class WorkstationLockListening implements WindowProc
{
/**
* Instantiates a new win32 window test.
*/
public WorkstationLockListening()
{
// define new window class
final WString windowClass = new WString("MyWindowClass");
final HMODULE hInst = Kernel32.INSTANCE.GetModuleHandle("");
WNDCLASSEX wClass = new WNDCLASSEX();
wClass.hInstance = hInst;
wClass.lpfnWndProc = WorkstationLockListening.this;
wClass.lpszClassName = windowClass;
// register window class
User32.INSTANCE.RegisterClassEx(wClass);
getLastError();
// create new window
final HWND hWnd = User32.INSTANCE.CreateWindowEx(User32.WS_EX_TOPMOST, windowClass, "'TimeTracker hidden helper window to catch Windows events", 0, 0, 0, 0, 0, null, // WM_DEVICECHANGE contradicts parent=WinUser.HWND_MESSAGE
null, hInst, null);
getLastError();
System.out.println("window sucessfully created! window hwnd: " + hWnd.getPointer().toString());
Wtsapi32.INSTANCE.WTSRegisterSessionNotification(hWnd, Wtsapi32.NOTIFY_FOR_THIS_SESSION);
MSG msg = new MSG();
while (User32.INSTANCE.GetMessage(msg, hWnd, 0, 0) != 0)
{
User32.INSTANCE.TranslateMessage(msg);
User32.INSTANCE.DispatchMessage(msg);
}
/// This code is to clean at the end. You can attach it to your custom application shutdown listener
Wtsapi32.INSTANCE.WTSUnRegisterSessionNotification(hWnd);
User32.INSTANCE.UnregisterClass(windowClass, hInst);
User32.INSTANCE.DestroyWindow(hWnd);
System.out.println("program exit!");
}
/*
* (non-Javadoc)
*
* #see com.sun.jna.platform.win32.User32.WindowProc#callback(com.sun.jna.platform .win32.WinDef.HWND, int, com.sun.jna.platform.win32.WinDef.WPARAM, com.sun.jna.platform.win32.WinDef.LPARAM)
*/
public LRESULT callback(HWND hwnd, int uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WinUser.WM_DESTROY:
{
User32.INSTANCE.PostQuitMessage(0);
return new LRESULT(0);
}
case WinUser.WM_SESSION_CHANGE:
{
this.onSessionChange(wParam, lParam);
return new LRESULT(0);
}
default:
return User32.INSTANCE.DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
/**
* Gets the last error.
*
* #return the last error
*/
public int getLastError()
{
int rc = Kernel32.INSTANCE.GetLastError();
if (rc != 0)
System.out.println("error: " + rc);
return rc;
}
/**
* On session change.
*
* #param wParam
* the w param
* #param lParam
* the l param
*/
protected void onSessionChange(WPARAM wParam, LPARAM lParam)
{
switch (wParam.intValue())
{
case Wtsapi32.WTS_SESSION_LOCK:
{
this.onMachineLocked(lParam.intValue());
break;
}
case Wtsapi32.WTS_SESSION_UNLOCK:
{
this.onMachineUnlocked(lParam.intValue());
break;
}
}
}
/**
* On machine locked.
*
* #param sessionId
* the session id
*/
protected void onMachineLocked(int sessionId)
{
System.out.println("Machine locked right now!");
}
/**
* On machine unlocked.
*
* #param sessionId
* the session id
*/
protected void onMachineUnlocked(int sessionId)
{
System.out.println("Machine unlocked right now!");
}
}
We have solved this problem in Google Group Workstation Lock / Unlock listener. You can find there my own implementation but this code right here is much better! Enjoy :)
One more way, without any windows system libs, ect.
Main idea - screenshots for locked PC will be totally black, so you can take one and simply check that some critical points are black
-16777216 - magic number, that means FFFFFFFFFF000000xH and last 00 00 00 means RGB color code (actually black color)
BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
boolean isBlack;
isBlack = (image.getRGB(1,1)==-16777216)
&(image.getRGB(1,image.getHeight()-1)==-16777216)
&(image.getRGB(image.getWidth()-1,1)==-16777216)
&(image.getRGB(image.getWidth()-1,image.getHeight()-1)==-16777216)
&(image.getRGB(image.getWidth()/2,image.getHeight()/2)==-16777216);
return isBlack;
Actually, there could be only one case with incorrect lock identification - when you have totally black wallpaper, with hidden taskbar and hidden icons.
Use JNI (Java Native Interface) to invoke functions from the Windows system dll.
Here is the sample code for use of functions which check workstation locking state: http://brutaldev.com/post/2008/05/23/Checking-if-the-workstation-is-locked.aspx
And here is the article about invoking dll-functions from Java via JNI:
http://edn.embarcadero.com/article/20679
With JDK9 (JDK11) you can use java.awt.Desktop :
Desktop tempDesktop = Desktop.getDesktop();
tempDesktop.addAppEventListener(new UserSessionListener() {
#Override
public void userSessionDeactivated(UserSessionEvent aE) {
LOG.info("Desktop:userSessionDeactivated Reason=" + aE.getReason() + " Source=" + aE.getSource());
// Windows Key L:
// Tue Aug 31 11:22:49 CEST 2021:info:MainController:userSessionDeactivated Reason=LOCK
// Close Lid:
// Tue Aug 31 11:24:38 CEST 021:info:MainController:userSessionDeactivated Reason=LOCK
// Tue Aug 31 11:24:39 CEST 2021:info:MainController:systemAboutToSleep Source=java.awt.Desktop#741f67cd
ptcUserStatus = PtcUserStatus.AWAY;
}
#Override
public void userSessionActivated(UserSessionEvent aE) {
LOG.info("Desktop:userSessionActivated Reason=" + aE.getReason() + " Source=" + aE.getSource());
// Logon after Windows Key L
// Tue Aug 31 11:22:53 CEST 2021:info:MainController:userSessionActivated Reason=LOCK
// Open Lid:
// Tue Aug 31 11:24:56 CEST 2021:info:MainController:systemAwoke Source=java.awt.Desktop#741f67cd
// Tue Aug 31 11:25:06 CEST 2021:info:MainController:userSessionActivated Reason=LOCK
ptcUserStatus = PtcUserStatus.BACK;
}
});
Have a look at Unlock Administrator
The purpose of the program is allow the admin at assign who can unlock the computer but it also has logging capability. It also allows you to run a script whenever the computer is locked or unlocked. This may be helpful to you.
Using JDIC Library,
To Check the system is Locked or Not
SystemInfo.isSessionLocked()

Categories