How to download IntelliJ IDEA JavaBeans component of the JAR file - java

How to insert a palette component of the jar file?
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: user
* Date: 05.07.13
* Time: 17:51
* To change this template use File | Settings | File Templates.
*/
public class ImageViewerBean extends JLabel {
private File file=null;
int XPREFSIZE=200;
int YPREFSIZE=200;
public ImageViewerBean(){
setBorder(BorderFactory.createEtchedBorder());
}
public void setFileName(String fileName)
{
File file1=new File(fileName);
try {
setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
file=null;
setIcon(null);
}
}
public String getFileName(){
if (file!=null)
return file.getPath();
else
return null;
}
public Dimension getPreferredSize(){
return new Dimension(XPREFSIZE,YPREFSIZE);
}
}
Manifest:
Manifest-Version: 1.0
Name: C:\Users\user\IdeaProjects\AWTLearn\src\ImageViewerBean.java
Java-Bean: True
In the manifesto, all strictly no extra spaces at the end of an empty string.

Please check Adding GUI Components and Forms to the Palette on the IDEA web help page.

Related

How do I save an SVG file to clipboard using processing/java?

I am creating a program using processing(java) that outputs an SVG file for me to add it to PowerPoint and other programs.
I figured it would be a lot more convenient for the program to directly copy the generated file to my system clipboard, instead of having to copy the file from the output directory.
The trouble is that I can't find a way to set the contents of the clipboard to an SVG file. I've found ways that work with images, but not SVG. To clarify, I want the pasted file to be an SVG too because I want to edit the shapes and lines in PowerPoint afterward.
I am also open to javascript solutions which may work on the web. The goal is to be able to paste an editable collection of shapes, lines, and texts into PowerPoint.
All help is appreciated, thanks in advance!
Edit: Here is the code that works for images:
import java.awt.image.*;
import java.awt.*;
import java.awt.datatransfer.*;
import javax.imageio.*;
void setup() {
size(200, 200);
background(0);
Image img=null;
try {
img = ImageIO.read(new File("path/to/file.jpg"));//path to image file
}
catch (IOException e) {
print(e);
}
ImageSelection imageSelection = new ImageSelection(img);
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.getSystemClipboard().setContents(imageSelection, null);
}
void draw() {
}
public class ImageSelection implements Transferable {
private Image image;
public ImageSelection(Image image) {
this.image = image;//added on
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (flavor.equals(DataFlavor.imageFlavor) == false) {
throw new UnsupportedFlavorException(flavor);//usually with transferable
}
return image;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(DataFlavor.imageFlavor);//usually with transferable
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {
DataFlavor.imageFlavor//usually with transferable
};
}
}
There is a bit of confusion with the code you posted: so far it looks like for some reason you want to load an image and copy that to the clipboard, not an SVG.
If you want to copy an SVG to the clipboard for PowerPoint there are a few hoops to jump through:
Use the PShapeSVG source code to understand to get the SVG markup
Use the right MIME type: I simply tried this solution
Putting it together:
import processing.svg.*;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.SystemFlavorMap;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
void setup(){
PGraphicsSVG svg = (PGraphicsSVG)createGraphics(300,300,SVG);
svg.beginDraw();
svg.background(#4db748);
svg.noFill();
svg.strokeWeight(27);
int a = 80;
int b = 220;
svg.line(a,a,b,b);
svg.line(a,b,b,a);
svg.line(a,a,b,a);
svg.line(a,b,b,b);
svg.ellipse(150, 150, 250, 250);
copyToClipboard(svg);
// normally you would call endDraw, but this will obviously throw an error if you didn't specify a filename in createGraphics()
//svg.endDraw();
println("svg copied to clipboard");
exit();
}
String getSVGString(PGraphicsSVG svg){
// make a binary output stream
ByteArrayOutputStream output = new ByteArrayOutputStream();
// make a writer for it
Writer writer = PApplet.createWriter(output);
// same way the library writes to disk we write to the byte array stream
try{
((SVGGraphics2D) svg.g2).stream(writer, false);
} catch (SVGGraphics2DIOException e) {
e.printStackTrace();
}
// convert bytes to an UTF-8 encoded string
return new String( output.toByteArray(), StandardCharsets.UTF_8 );
}
void copyToClipboard(PGraphicsSVG svg){
// get the SVG markup as a string
String svgString = getSVGString(svg);
println(svgString);
// access the system clipboard
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
// get an binary clipboard with the correct SVG MIME type
SvgClip strSVG = new SvgClip(svgString);
// commit the clipboard encoded SVG to clipboard
clip.setContents(strSVG, null);
}
// blatant copy/adapation of https://stackoverflow.com/questions/33726321/how-to-transfer-svg-image-to-other-programs-with-dragndrop-in-java
class SvgClip implements Transferable{
String svgString;
DataFlavor svgFlavor = new DataFlavor("image/svg+xml; class=java.io.InputStream","Scalable Vector Graphic");
DataFlavor [] supportedFlavors = {svgFlavor};
SvgClip(String svgString){
this.svgString = svgString;
SystemFlavorMap systemFlavorMap = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
systemFlavorMap.addUnencodedNativeForFlavor(svgFlavor, "image/svg+xml");
}
#Override public DataFlavor[] getTransferDataFlavors(){
return this.supportedFlavors;
}
#Override public boolean isDataFlavorSupported(DataFlavor flavor){
return true;
}
#Override public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException{
return new ByteArrayInputStream(svgString.getBytes(StandardCharsets.UTF_8));
}
}
Note Call copyToClipboard(svg) after your last drawing command, but before PGraphicsSVG's endDraw() call (otherwise it will return an empty SVG document)
The result in PowerPoint:

Problem when executing personnal JAR File in my program

I want to create a Java class that I use to export images. This class will be exported in .JAR file which will allow me to integrate it directly into another project by passing as input parameter the name of the file and in return I would have this image in PNG format.
That's what I tried:
package militarySymbolsLibrary;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class MainEntry {
public static void main(String agrs[]) {
}
public static BufferedImage generateImage(String symbolCode) {
File imageFile = new File("/pictures/SSGPU-------.png");
BufferedImage image;
try {
image = ImageIO.read(imageFile);
} catch (IOException e) {
image = null;
e.printStackTrace();
}
return image;
}
}
Pictures are stocked in folder pictures like this treeview below:
src
MainEntry.java
pictures
SSGPU-------.png
Then I export this class in .JAR file, I add it to my other program, I pass a parameter (picture's name except for this test) and normally my class return PNG file. But I have an error telling me that the file path is not the rigth one.
How can I solve this problem?
Thank you

Extension of `MavenProjectWizard` possible?

What I want: I have an editor plug-in for my custom DSL. I want to offer the user to set up a new DSL project with a project wizard. Normally these projects are Maven projects, so I want to provide setting up the project directly as a Maven project. To do that I want to extend the class MavenProjectWizardin the package org.eclipse.m2e.core.ui.internal.wizards.MavenProjectWizard and then add another wizard page with the details regarding the DSL project.
What I have: This is my try to do it at the moment:
/*
* Copyright (c) 2017 RWTH Aachen. All rights reserved.
*
* http://www.se-rwth.de/
*/
package de.se_rwth.transformationeditor.wizard;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.m2e.core.ui.internal.wizards.MavenProjectWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
import jline.internal.Log;
/**
* Offers a wizard to create a new Transformation project
*
* #author (last commit) $Philipp Nolte$
* #version $Revision$, $12.1.2017$
* #since 0.0.3
*/
#SuppressWarnings("restriction")
public class CDProjectWizard extends MavenProjectWizard{
protected CDWizardPageOne one;
protected WizardPage currentPage;
private IWorkbench workbench;
public CDProjectWizard() {
super();
}
/**
* #see org.eclipse.jface.wizard.IWizard#addPages()
*/
#Override
public void addPages() {
one = new CDWizardPageOne();
addPage(one);
super.addPages();
}
/**
* #see org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard#init(org.eclipse.ui.IWorkbench,
* org.eclipse.jface.viewers.IStructuredSelection)
*/
#Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
super.init(workbench, selection);
this.workbench = workbench;
}
/**
* #see org.eclipse.jface.wizard.IWizard#getWindowTitle()
*/
#Override
public String getWindowTitle() {
return "New Class Diagram Transformation Project";
}
/**
* Creates a new Transformation project with the project name given in the
* wizard. Inside this project a new folder named "Transformations" is
* created. If a project with the same name already exists, an error window is
* shown. In addition to that, checks if user wants to create CD or MA xample
* files and creates them if wanted.
*
* #see org.eclipse.jface.wizard.IWizard#performFinish()
*/
#Override
public boolean performFinish() {
if (this.canFinish()) {
// Create new project
String projectName = this.one.getProjectNameText();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(projectName);
try {
if (!project.exists()) {
project.create(null);
}
else {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
MessageDialog.openError(this.workbench.getActiveWorkbenchWindow().getShell(),
"Project creation error", "Project with this name already exists");
return false;
}
if (!project.isOpen()) {
project.open(null);
}
String transformationFolderName = "Transformations";
// Check subfolder name
if (!one.getRootFolderText().isEmpty()) {
transformationFolderName = one.getRootFolderText();
}
IFolder binFolder = project.getFolder(transformationFolderName);
if (!binFolder.exists()) {
one.createNewFolder(binFolder, false, true, null);
// Checks if user wants to create a CD example file
if (one.createCDExampleFile()) {
InputStream demoFileContents = null;
try {
// If the user wants to, an example file is created
URL url = new URL("platform:/plugin/cdtrans-editor/src/main/resources/exampleFiles/RefactorCDs");
InputStream inputStream = url.openConnection().getInputStream();
binFolder.getFile("RefactorCDs.cdtr").create(inputStream, true, null);
}
catch (IOException e) {
Log.error("TransProjectWizard: Error while creating Demo file", e);
MessageDialog.openError(this.workbench.getActiveWorkbenchWindow().getShell(),
"Example file creation error", "There was an error while creating the example file");
}
finally {
if (demoFileContents != null) {
try {
demoFileContents.close();
}
catch (IOException e) {
Log.error("TransProjectWizard: Error while closing file stream", e);
}
}
}
}
BasicNewResourceWizard.selectAndReveal(binFolder, this.workbench.getActiveWorkbenchWindow());
}
}
catch (CoreException e) {
Log.error("TransProjectWizard: Error while creating new Project", e);
}
}
return true;
}
}
But if I start this there is a runtime error if I try to open the wizard which says:
I already tried to export the plug-in and install it in a fresh Eclipse installation, where the m2e package is installed, but with the same result.
Any thoughts on how to fix it?

getResourceAsStream() works on Windows but not on Linux

I have a following class in my project:
package com.test.schedule.payloads;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Loads payload from file
*/
public class FilePayload{
private static final Logger LOGGER = Logger.getLogger(FilePayload.class);
private final String filename;
public FilePayload(String filename) {
this.filename = filename;
}
public String getAsString() {
try {
return IOUtils.toString(new InputStreamReader(FilePayload.class.getResourceAsStream(filename), Charsets.UTF_8));
} catch (IOException e) {
LOGGER.error("Error while loading file: '" + filename +'\'', e);
return "";
}
}
}
In resources directory of my project (maven one) I have file in following path:
com/test/schedule/payloads/schedule-payload.xml
When I execute getAsString() with filename equal to "schedule-payload.xml" on Windows everything works fine. But when the same code is executed on Linux server it returns null on getResourceAsStream(). I have no idea how to fix it so code works both on Windows and Linux. Any help would be very appreciated.
Check, that everything on your path to this file "com/test/schedule/payloads/schedule-payload.xml" is lowercase, as linux paths are case sensitive and windows paths are not case sensitive.

jFilechooser show folder

I want to show the parent folder of current directory in jfilechooser.
I want to display that folder with .. which refers to the parent folder
Use the constructor which takes file path as argument like this.
JFileChooser jfc = new JFileChooser(".\\..");
Check out JFileChooser(File currentDirectory).
This is an "attempt" to implement the functionality that you request, the problem I have is that it's not possible replicate entirely what the system is doing.
Basically, the directory combo box is expecting some kind of native File object (in the case of Windows, a sun.awt.shell.Win32ShellFolder2). But there doesn't seem to be any way by which we can create them from within the provided API (and you won't want to create them manually, as it will break the Look and Feel and cross platform functionality).
import core.util.MethodInvoker;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;
import javax.swing.plaf.ComponentUI;
public class TestFileChooser {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
System.out.println(UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFileChooser fc = new JFileChooser(new MyFileSystemView());
fc.showOpenDialog(null);
}
});
}
public static class MyFileSystemView extends FileSystemView {
#Override
public File[] getFiles(File dir, boolean useFileHiding) {
File[] files = super.getFiles(dir, useFileHiding);
List<File> fileList = new ArrayList<>(Arrays.asList(files));
if (!isFileSystemRoot(dir)) {
File newPath = FileSystemView.getFileSystemView().createFileObject(dir, "/..");
fileList.add(0, newPath);
}
files = fileList.toArray(files);
return files;
}
#Override
public File createNewFolder(File containingDir) throws IOException {
File newFolder = new File(containingDir + File.separator + "New Folder");
if (!newFolder.mkdir()) {
newFolder = null;
}
return newFolder;
}
}
}

Categories

Resources