I have run the following code in this page RsyntaxTextArea using Java and i run the program exactly the way that is been mentioned in this site.And i'm getting the output as intended. But i have tried to modify this java code to Groovy code, something like:
import groovy.swing.SwingBuilder
import javax.swing.*
import java.awt.*
swing = new SwingBuilder()
frame = swing.frame(title : "test", defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true, show : true, size :[100,100])
{
panel
{
RSyntaxTextArea textArea = new RSyntaxTextArea();
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
}
}
And when i try to run this script as follows:
groovyc -classpath rsyntaxtextarea.jar TextEditorDemo.groovy
I get the errors stating that:
groovy: 9: unable to resolve class RSyntaxTextArea
# line 9, column 19.
RSyntaxTextArea textArea = new RSyntaxTextArea();
^
/home/anto/Groovy/Rsyntax/ST.groovy: 9: unable to resolve class RSyntaxTextArea
# line 9, column 30.
RSyntaxTextArea textArea = new RSyntaxTextArea();
^
/home/anto/Groovy/Rsyntax/ST.groovy: 10: unable to resolve class RSyntaxTextArea
# line 10, column 7.
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
I guess i have made wrong in running the program. How i do i run the program in this case by defining the classpath too.
It doesn't look like you're importing the package for RSyntaxTextArea. Have you tried adding the following imports to your program?
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;
This code should do what you want... You needed to add the RSyntaxTextArea into the view (using the widget method)
You also needed to add it into a JScrollPane, so that it scrolls nicely when full.
import groovy.swing.SwingBuilder
import java.awt.BorderLayout as BL
import static javax.swing.JFrame.EXIT_ON_CLOSE
import org.fife.ui.rsyntaxtextarea.*
RSyntaxTextArea textArea = new RSyntaxTextArea()
textArea.syntaxEditingStyle = SyntaxConstants.SYNTAX_STYLE_JAVA
swing = new SwingBuilder()
frame = swing.frame(title:"test", defaultCloseOperation:EXIT_ON_CLOSE, size:[600,400], show:true ) {
borderLayout()
panel( constraints:BL.CENTER ) {
borderLayout()
scrollPane( constraints:BL.CENTER ) {
widget textArea
}
}
}
edit
Without using widget, your code would need to look something like this:
import groovy.swing.SwingBuilder
import java.awt.BorderLayout as BL
import static javax.swing.JFrame.EXIT_ON_CLOSE
import org.fife.ui.rsyntaxtextarea.*
RSyntaxTextArea textArea = new RSyntaxTextArea()
textArea.syntaxEditingStyle = SyntaxConstants.SYNTAX_STYLE_JAVA
swing = new SwingBuilder()
frame = swing.frame(title:"test", defaultCloseOperation:EXIT_ON_CLOSE, size:[600,400], show:true ) {
borderLayout()
panel( constraints:BL.CENTER ) {
borderLayout()
sp = scrollPane( constraints:BL.CENTER )
sp.viewport.add textArea
}
}
Related
Here is my code
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
#Service
#Slf4j
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class FileConverterService {
public void convertPptToImages() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("Sylon_GuidedPath_Sprint22Deck.ppt").getFile());
Document pdfDocument = new Document();
// PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(""));
FileInputStream is = new FileInputStream(file);
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();
Dimension pgsize = ppt.getPageSize();
pdfDocument.setPageSize(new Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
// convert to images
int idx = 1;
for (HSLFSlide slide : ppt.getSlides()) {
BufferedImage img =
new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(
RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(
RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(
RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
// clear the drawing area
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// render
slide.draw(graphics);
// save the output
ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(1f);
jpgWriter.setOutput(new FileImageOutputStream(
new File("slide-" + idx + ".jpg")));
IIOImage outputImage = new IIOImage(img, null, null);
jpgWriter.write(null, outputImage, jpgWriteParam);
jpgWriter.dispose();
idx++;
}
}
I based my code off this documentation, http://poi.apache.org/components/slideshow/how-to-shapes.html#Render
I have tried both jpeg and png, and the image seems to be fairly low resolution and the text is difficult to read compared to the original .ppt. Is there any way to increase the resolution/quality of the images?
What you can try
Applying RenderingHints to the graphics, below is a sample I created comparing the image with/without rendering hint. You can see that the character looks better with rendering hint.
Increase the compression quality for the jpeg image.
Following program demonstrates how to generate image with/without rendering hint and create image with 100% compression quality.
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
public class ImproveSlideConvertToImageQuality {
public static void main(String[] args) throws Exception {
convertPptToImages(true);
convertPptToImages(false);
}
public static void convertPptToImages(boolean withRenderHint) throws Exception {
File file = new File("test.ppt");
String suffix = withRenderHint ? "-with-hint" : "-without-hint";
try (FileInputStream is = new FileInputStream(file); HSLFSlideShow ppt = new HSLFSlideShow(is)) {
Dimension pgsize = ppt.getPageSize();
int idx = 1;
for (HSLFSlide slide : ppt.getSlides()) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
if (withRenderHint) {
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.setRenderingHint(
RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
graphics.setRenderingHint(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(
RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setRenderingHint(
RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
}
// render
slide.draw(graphics);
final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
writer.setOutput(new FileImageOutputStream(
new File("slide-" + idx + suffix + ".jpeg")));
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(1f);
// writes the file with given compression level
// from your JPEGImageWriteParam instance
IIOImage image = new IIOImage(img, null, null);
writer.write(null, image, jpegParams);
writer.dispose();
idx++;
}
}
}
}
References:
Controlling Rendering Quality
Setting jpg compression level with ImageIO in Java
I have a form in QML with two TextFields. How do I access the value entered in the fields in Python?
I'm using PyQt5.5 and Python3.
import sys
from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import QQmlApplicationEngine
if __name__ == '__main__':
myApp = QApplication(sys.argv)
engine = QQmlApplicationEngine()
context = engine.rootContext()
context.setContextProperty("main", engine)
engine.load('basic.qml')
win = engine.rootObjects()[0]
button = win.findChild(QObject, "myButton")
def myFunction():
print("handler called")
foo = win.findChild(QObject, "login")
print(dir(foo))
print(foo.text)
button.clicked.connect(myFunction)
win.show()
sys.exit(myApp.exec_())
basic.qml
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
width: 250; height: 175
Column {
spacing: 20
TextField {
objectName: "login"
placeholderText: qsTr("Login")
focus: true
}
TextField {
placeholderText: qsTr("Password")
echoMode: TextInput.Password
}
Button {
signal messageRequired
objectName: "myButton"
text: "Login"
onClicked: messageRequired()
}
}
}
Console
Traceback (most recent call last):
File "working.py", line 25, in myFunction
print(foo.text)
AttributeError: 'QQuickItem' object has no attribute 'text'
fish: “python working.py” terminated by signal SIGABRT (Abort)
You need to call the property() method of the object to get the desired property.
In your example, you need to call:
print(foo.property("text"))
rather than print(foo.text)
Note that property() returns None if the property doesn't exists.
I'm following the tutorial here... http://x01010111.com/haxeflixel.php#w3
I got to the part where he says "Awesome, but" and tried compiling, only to have nothing displayed. I tried comparing my code to his a bunch of times, going farther into the tutorial (I initially stopped when he first mentioned that there should only be a white background, and I compiled for comparison) to see if the problem would disappear (thinking it may have been somewhat outdated, etc.). I searched around looking for an explanation and found I didn't quite know what to search for, and didn't find anything that was helpful.
I haven't changed anything in my install, I've compiled many times previously without issue (numerous times in this same tutorial), so it's something in the Moving Forward section that I did wrong I'm thinking.
So, nothing is displayed, here's my PlayState.hx code.
package;
import flixel.FlxG;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.FlxObject;
import flixel.tile.FlxTilemap;
import flixel.text.FlxText;
import flixel.ui.FlxButton;
import flixel.util.FlxMath;
import flixel.util.FlxStringUtil;
import flixel.FlxCamera;
import flixel.group.FlxGroup;
import flixel.text.FlxText;
import flixel.util.FlxTimer;
import openfl.Assets;
/**
* A FlxState which can be used for the actual gameplay.
*/
class PlayState extends FlxState
{
var level:FlxTilemap;
var player:FlxSprite;
/**
* Function that is called up when to state is created to set it up.
*/
override public function create():Void
{
FlxG.camera.bgColor = 0xFF6DC2CA;
addLevel();
addPlayer(2, 22);
setCamera();
super.create();
}
/**
* Function that is called when this state is destroyed - you might want to
* consider setting all objects this state uses to null to help garbage collection.
*/
override public function destroy():Void
{
super.destroy();
}
/**
* Function that is called once every frame.
*/
override public function update():Void
{
super.update();
FlxG.collide(level, player);
playerMovement();
}
function playerMovement():Void
{
player.velocity.x = 0;
if(FlxG.keys.pressed.LEFT) player.velocity.x -= 100;
if(FlxG.keys.pressed.RIGHT) player.velocity.x += 100;
if(FlxG.keys.justPressed.SPACE && player.isTouching(FlxObject.FLOOR)) player.velocity.y = -200;
}
function addLevel():Void
{
level = new FlxTilemap();
level.loadMap(Assets.getText("assets/data/Map1_Level.csv"), "Assets/images/tiles.png", 16, 16);
add(level);
}
function setCamera():Void
{
FlxG.camera.follow(player, FlxCamera.STYLE_PLATFORMER);
FlxG.camera.setBounds(0, 0, level.width - 16, level.height - 16, true);
}
function addPlayer(X:Int, Y:Int):Void
{
player = new FlxSprite(X * 16, Y * 16 - 8);
player.makeGraphic(6, 8, 0xFFFF0000);
player.acceleration.y = 800;
add(player);
}
}
And Main.hx...
package;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.Lib;
import flixel.FlxGame;
import flixel.FlxState;
class Main extends Sprite
{
var gameWidth:Int = 320; // Width of the game in pixels (might be less / more in actual pixels depending on your zoom).
var gameHeight:Int = 240; // Height of the game in pixels (might be less / more in actual pixels depending on your zoom).
var initialState:Class<FlxState> = PlayState; // The FlxState the game starts with.
var zoom:Float = 2; // If -1, zoom is automatically calculated to fit the window dimensions.
var framerate:Int = 60; // How many frames per second the game should run at.
var skipSplash:Bool = false; // Whether to skip the flixel splash screen that appears in release mode.
var startFullscreen:Bool = false; // Whether to start the game in fullscreen on desktop targets
// You can pretty much ignore everything from here on - your code should go in your states.
public static function main():Void
{
Lib.current.addChild(new Main());
}
public function new()
{
super();
if (stage != null)
{
init();
}
else
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function init(?E:Event):Void
{
if (hasEventListener(Event.ADDED_TO_STAGE))
{
removeEventListener(Event.ADDED_TO_STAGE, init);
}
setupGame();
}
private function setupGame():Void
{
var stageWidth:Int = Lib.current.stage.stageWidth;
var stageHeight:Int = Lib.current.stage.stageHeight;
if (zoom == -1)
{
var ratioX:Float = stageWidth / gameWidth;
var ratioY:Float = stageHeight / gameHeight;
zoom = Math.min(ratioX, ratioY);
gameWidth = Math.ceil(stageWidth / zoom);
gameHeight = Math.ceil(stageHeight / zoom);
}
addChild(new FlxGame(gameWidth, gameHeight, initialState, zoom, framerate, framerate, skipSplash, startFullscreen));
}
}
I've been running into a number of problems so far with Haxeflixel and with the exception of a previous out of date tutorial it's always been something stupid that I did wrong.
Edit: I tried using debug mode to show more information, but it didn't show any errors, or anything else for that matter. I hit ~ to see if there was anything I missed there and, again, nothing. What am I looking for in debug mode?
I'm using the Flash Player Projector Content Debugger to run my .swf
Added Main.hx
Attempting to run that code with the assets provided by the tutorial I received the following runtime error in my editor output panel (I am using sublime text)
Assets.hx:149: [openfl.Assets] There is no BitmapData asset with an ID of "Assets/images/tiles.png"
If we look at PlayState.hx on line 76 we can see it is attempting to load the asset "Assets/images/tiles.png". Asset lookups are case sensitive and the asset directory is in fact lowercase by default, so this needs changing to "assets/images/tiles.png"
After doing so that code ran fine for me.
Note that I'm not using flash for debugging this, but neko. if you're having trouble reading debug output in flash you might be best testing with neko first, and then later deploying for flash or your target platfokrm.
Why does this code fail ?
I want to change the color of one panel in a series of several panels, dynamically constructed (total number of panels not known beforehand).
For some reason, this code works when referencing the name of a particular panel (for example 'panel2'), but not when I refer to it dynamically ('panelID').
import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC
import javax.swing.JOptionPane
import javax.swing.BoxLayout as BXL
swing = new SwingBuilder()
frame = swing.frame(title:'test',
defaultCloseOperation:WC.DISPOSE_ON_CLOSE) {
panel(id:'mainPanel'){
def panelID
(1..6).each {
panelID = 'panel' + it
panel(alignmentX: 0f, id: panelID , opaque:true ,background : java.awt.Color.GREEN){
label('description')
textField(id: "description$it", text: panelID, columns: 70 )
button(id: "button$panelID", text: panelID, actionPerformed : {
panelID.background = java.awt.Color.RED
panelID.repaint()
})
}
}
boxLayout(axis: BXL.Y_AXIS)
panel(id:'secondPanel' , alignmentX: 0f){
button('Quit', actionPerformed:{
dispose()
})
}
}
}
frame.pack()
frame.show()
To get the element based on it's ID, you need to access the ID as a parameter of the SwingBuilder, like so:
import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC
import javax.swing.JOptionPane
import javax.swing.BoxLayout as BXL
swing = new SwingBuilder()
frame = swing.frame(title:'test', pack:true, visible:true, defaultCloseOperation:WC.DISPOSE_ON_CLOSE) {
panel(id:'mainPanel'){
(1..6).each { num ->
def panelID = "panel$num"
def pane = panel( alignmentX:0f, id:panelID, background:java.awt.Color.GREEN ) {
label('description')
textField(id: "description$num", text:panelID, columns: 70 )
button(id: "buttonpanel$num", text:panelID, actionPerformed : {
swing."$panelID".background = java.awt.Color.RED
})
}
}
boxLayout(axis: BXL.Y_AXIS)
panel(id:'secondPanel' , alignmentX: 0f){
button('Quit', actionPerformed:{
frame.visible = false
})
}
}
}
Is there some kind of built-in method or a simple function that will convert Duration into a string in the hh:mm:ss format? For example, I am looking for something that would convert a Duration of 123402 ms into a String of "2:03".
Alternatively, you can use the flags from java.util.Formatter.
action: function() {
txt = "{%tM dur}.{%tS dur}"
}
This will result in a leading 0, as in "02.03", for dur = "123402ms".
You can convert a Duration to a String using String.valueOf(dur). You can then use the Java formatting classes to reformat the String. You have to chop the end of String because of the way JavaFX formats durations as strings (eg '123402.0ms'). If JavaFX had a Long.valueOf(dur) function then this would be easier.
See sample below:
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.control.Button;
import java.text.SimpleDateFormat;
import java.util.Date;
var fmt = new SimpleDateFormat("m:ss");
var dur: Duration = 123402ms;
var txt: String = String.valueOf(dur);
Stage {
title : "Duration Switch"
scene: Scene {
width: 400
height: 200
content: [
Text {
font : Font {
size: 24
}
x: 10, y: 30
content: bind "Duration={txt}"
},
Button {
translateY: 140
text: "Switch"
action: function() {
var durStr = String.valueOf(dur);
durStr = durStr.substring(0, durStr.indexOf("."));
var date = new Date(Long.parseLong(durStr));
txt = fmt.format(date);
}
}
]
}
}