Spigot Plugin - Cannot Build 1.10 - minecraft

I have created a Spigot plugin in 1.10. It is mostly essentials but I added in a compass inventory GUI and you receive it when you first log in. For some odd reason after I implemented this you cannot obtain items in your inventory, they instantly go away. The class for the GUI is below
package me.Roofah.Essentials;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Essentials extends JavaPlugin implements Listener{
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
this.getCommand("teleport").setExecutor(new Teleport(this));;
this.getCommand("vanish").setExecutor(new Vanish(this));;
this.getCommand("unvanish").setExecutor(new Vanish(this));;
Bukkit.getServer().getLogger().info("Teleport Plugin Enabled!");
}
public Player getPlayer(String name) {
for(Player p : Bukkit.getOnlinePlayers()) {
if(p.getName().equalsIgnoreCase(name))
return p;
}
return null;
}
public void onDisable() {
Bukkit.getServer().getLogger().info("Teleport Plugin Disabled!");
}
private void teleportInWord(Player player, int x, int y, int z) {
player.teleport(new Location(player.getWorld(), x, y, z));
}
private void openGUI(Player player) {
Inventory inv = Bukkit.createInventory(null, 9, ChatColor.DARK_RED + "Warp Selector || By Roofah");
ItemStack Spawn = new ItemStack(Material.DIAMOND_AXE);
ItemMeta SpawnMeta = Spawn.getItemMeta();
ItemStack Build = new ItemStack(Material.DIAMOND_PICKAXE);
ItemMeta BuildMeta = Build.getItemMeta();
SpawnMeta.setDisplayName(ChatColor.DARK_RED + "Spawn");
Spawn.setItemMeta(SpawnMeta);
BuildMeta.setDisplayName(ChatColor.GREEN + "Build");
Build.setItemMeta(BuildMeta);
// 35
inv.setItem(3, Spawn);
inv.setItem(5, Build);
player.openInventory(inv);
}
#EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (ChatColor.stripColor(event.getInventory().getName()).equalsIgnoreCase("Warp Selector")) {
return;
}
Player player = (Player) event.getWhoClicked();
event.setCancelled(true);
if (event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR
|| !event.getCurrentItem().hasItemMeta()) {
player.closeInventory();
return;
}
switch(event.getCurrentItem().getType()){
case DIAMOND_AXE:
teleportInWord(player, 967, 90, 484);
player.closeInventory();
player.sendMessage(String.format("%sTeleported to %sSpawn%s!", ChatColor.GOLD, ChatColor.DARK_RED, ChatColor.GOLD));
break;
case DIAMOND_PICKAXE:
teleportInWord(player, 906, 96, 428);
player.closeInventory();
player.sendMessage(String.format("%sTeleported to %sBUILD%s!", ChatColor.GOLD, ChatColor.GREEN, ChatColor.GOLD));
break;
default:
player.closeInventory();
break;
}
}
#EventHandler
public void onPlayerKoin(PlayerJoinEvent event) {
event.getPlayer().getInventory().addItem(new ItemStack(Material.COMPASS));
}
#EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Action a = event.getAction();
ItemStack is = event.getItem();
if (a == Action.PHYSICAL || is == null || is.getType() == Material.AIR) {
return;
}
if (is.getType() == Material.COMPASS) {
openGUI(event.getPlayer());
}
}
}
There are 2 other classes but I could still obtain blocks without adding in the GUI.

Your situation is a logic mistake at line 73 on your code.
You have the following:
if (ChatColor.stripColor(event.getInventory().getName()).equalsIgnoreCase("Warp Selector")) //Line 73 {
return;
}
The situation is:
Whenever the inventory name is Warp Selector, return. So your code is only executing when the inventory name is not "Warp Selector".
What you probably want is to invert this logic, so that your code will execute when the inventory name is "Warp Selector".
if (!ChatColor.stripColor(event.getInventory().getName()).equalsIgnoreCase("Warp Selector") {
return;
}
//Code continues

Related

Exception in thread "pool-1-thread-7" java.lang.NullPointerException

I'm trying to figure it out y i get this exception as i wrote in the title.
i'm building a multi thread MMU (memory management unit) project, first i initialize and add some pages into the ram and to my HD also and then i create processes and running all the system. a bit of information about the project:
into runConfig i;m reading a json file with a list of processCycles and every processCycles including a list of processCycle that including a list of pageIds with a list of data of those pages.
i think i did everything ok but still i get this exception, can somebody help me?
MMUDriver is the class that run all the systems:
package hit.driver;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
import com.hit.algorithm.IAlgoCache;
import com.hit.algorithm.LRUAlgoCacheImpl;
import com.hit.algorithm.MRUAlgoCacheImpl;
import com.hit.algorithm.RandomReplacementAlgoCacheImpl;
import hit.memoryunits.HardDisk;
import hit.memoryunits.MemoryManagementUnit;
import hit.memoryunits.MemoryManagementUnitTest;
import hit.memoryunits.Page;
import hit.processes.ProcessCycles;
import hit.processes.Process;
import hit.processes.RunConfiguration;
#SuppressWarnings("unused")
public class MMUDriver {
private static final String CONFIG_FILE_NAME="Configuration.json";
// private static final String CONFIG_FILE_NAME="test.json";
//read from JSON file the lists of processCycles
private static RunConfiguration readConfigurationFile() throws JsonIOException, JsonSyntaxException, FileNotFoundException{
RunConfiguration runConfig = new Gson().fromJson(new JsonReader(new FileReader(CONFIG_FILE_NAME)), RunConfiguration.class);
return runConfig;
}
//
private static List<Process> createProcesses(List<ProcessCycles> processCycles,MemoryManagementUnit mmu ){
int i=0;
List<Process> processList = new ArrayList<Process>();
for ( ProcessCycles currentListProcess : processCycles) {
Process process = new Process(++i , mmu , currentListProcess);
processList.add(process);
}
return processList;
}
//
private static void runProcesses(List<Process> processes){
//Executor is a interface that take care of threads מתי מתחיל טרד מתי נגמר איך הם ירוצו במקביל וכו'
//thread pool - אוסף של threads
ExecutorService executorservice = Executors.newCachedThreadPool();
for (Process process : processes)
executorservice.execute(process);
executorservice.shutdown();//
}
//
public static void main(String[] args) throws java.lang.InterruptedException,
InvocationTargetException, JsonIOException, JsonSyntaxException, ClassNotFoundException, IOException{
CLI cli = new CLI(System.in,System.out);
String [] configuration;
while((configuration = cli.getConfiguration()) != null){
IAlgoCache<Long, Long> algo = null;
int capacity = Integer.valueOf(configuration[1]);
switch(configuration[0]){ //which configuration to play on LRU|MRU|RR
case "LRU":
algo = new LRUAlgoCacheImpl<Long, Long>(capacity);
break;
case "MRU":
algo = new MRUAlgoCacheImpl<Long, Long>(capacity);
break;
case "RR":
algo = new RandomReplacementAlgoCacheImpl<Long, Long>(capacity);
break;
}
MemoryManagementUnit mmu = new MemoryManagementUnit(algo, capacity);
MemoryManagementUnitTest.test(mmu);//add some pages to ram for test
RunConfiguration runConfig = readConfigurationFile(); //Getting the user request pages throw json file
List<ProcessCycles> processCycles = runConfig.getProcessesCycles();
List<Process> processes = createProcesses(processCycles , mmu);
runProcesses(processes);
Map<Long, Page<byte[]>> bla= mmu.getRam().getRamPages();
System.out.println("1");
// mmu.shoutDown();
}
}
}
Process is like a thread in this project
package hit.processes;
import java.io.IOException;
import java.util.List;
import hit.memoryunits.MemoryManagementUnit;
import hit.memoryunits.Page;
#SuppressWarnings("unused")
public class Process implements Runnable {
private int id;
private MemoryManagementUnit mmu;
private ProcessCycles processCycles;
private Thread processThread=null;
public Process(int id, MemoryManagementUnit mmu, ProcessCycles processCycles){
this.id=id;
this.mmu=mmu;
this.processCycles=processCycles;
}
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
/*
public void start(){
if(processThread==null)
processThread = new Thread(this,"process"); //
processThread.start();
}*/
#Override
public void run() {
synchronized(mmu){
//runing on all the list of processCycles
for (ProcessCycle currentProcessCycle : processCycles.getProcessCycles()) {
List<Long> pages = currentProcessCycle.getPages();
List<byte[]> data = currentProcessCycle.getData();
Page<byte[]>[] pagesList = null;
//creating a boolean array to know if the page is for writing or reading in size of pages.size()
boolean [] writePages = new boolean[pages.size()];
for (int i = 0; i < pages.size(); i++)
if(data.get(i) == null) //if the page is empty
writePages[i] = false;
else{
writePages[i] = true ;//if there is data in the page and we want to write it to the ram
}
try {
// Getting the pages from ram to see which we shall update
pagesList = mmu.getPages(pages.toArray(new Long[pages.size()]), writePages);
}
catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
for (int j = 0; j < pages.size(); j++)
if(writePages[j] == true) //if the page isn't for read only
pagesList[j].setContent(data.get(j));
try {
Thread.sleep(currentProcessCycle.getSleepMs());
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
MMU class is that class that take care of all the requests from the user and manage all the pagging
package hit.memoryunits;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.hit.algorithm.IAlgoCache;
public class MemoryManagementUnit {
private IAlgoCache<Long,Long> algo;
private RAM<Long, Page<byte[]>> ram;
public MemoryManagementUnit(IAlgoCache<Long, Long> algo, int ramCapacity) {
this.algo = algo;
this.ram= new RAM<Long, Page<byte[]>>(ramCapacity);
}
#SuppressWarnings("null")
public Page<byte[]> [] getPages(Long [] pageIds , boolean [] writePages) throws IOException, ClassNotFoundException{
for (int i = 0; i < pageIds.length; i++) {
if(algo.getElement((long) pageIds[i].hashCode())== null)//the page isn't exist in the cache
if(!ram.isFull())
{
if(writePages[i] == true){//if the page is for write we need to overwrite data
Page<byte[]> pageToRam = null;
pageToRam.setPageId(pageIds[i]);
pageToRam.setContent(null);
ram.addPage(pageToRam);// ram is not full need to upload from hd
}
else{//if the page is for read-only so we need to upload the page from HD
ram.addPage(HardDisk.getInstance().pageFault(pageIds[i]));// ram is not full need to upload from hd
}
algo.putElement(Long.valueOf(pageIds[i].hashCode()),pageIds[i]);//update cache
}
else
{
Page<byte[]> pageToRemove = ram.getPage(algo.putElement(Long.valueOf(pageIds[i].hashCode()),pageIds[i]));
ram.removePage(pageToRemove);
ram.addPage(HardDisk.getInstance().pageReplacement(pageToRemove,pageIds[i]));// ram full need to do replacement
algo.putElement(Long.valueOf(pageIds[i].hashCode()),pageIds[i]);//update cache
}
}
return ram.getPages(pageIds);
}
public RAM<Long, Page<byte[]>> getRam(){
return ram;
}
public IAlgoCache<Long,Long> getAlgo(){
return algo;
}
public void setAlgo(IAlgoCache<Long,Long> algo){
this.algo = algo;
}
public void setRam(RAM<Long, Page<byte[]>> ram){
this.ram = ram;
}
public void shoutDown() throws FileNotFoundException, IOException, ClassNotFoundException{
HardDisk.getInstance().saveToDisk(this.getRam().getRamPages());
}
}

Is TextToSpeech supported on Google Glass?

I was wondering if TextToSpeech is supported on Google Glass?
I did something like this:
public class TextToSpeechController implements TextToSpeech.OnInitListener{
private Context mContext;
private TextToSpeech tts;
public TextToSpeechController(Context context) {
Log.e("TEXT TO SPEECH CONTROLLER", "controller");
mContext = context;
tts = new TextToSpeech(context, this);
}
#Override
public void onInit(int status) {
Log.e("INIT TTS", "INIT");
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(mContext, "This Language is not supported", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(mContext, "Ready to Speak", Toast.LENGTH_LONG).show();
speakTheText("Welcome to Vision Screening App");
}
}
else {
Toast.makeText(mContext, "Can Not Speak", Toast.LENGTH_LONG).show();
}
}
public void stopTTS(){
Log.e(".....TTS", "SHUTDOWN");
tts.stop();
tts.shutdown();
}
public void speakTheText(String str){
Log.e("SPEAK TEXT!!!!", "SPEAK TEXT");
tts.speak(str, TextToSpeech.QUEUE_FLUSH, null);
}
}
and in my Activity (onCreate) I have:
controller_tts = new TextToSpeechController(getApplicationContext());
I face several problems :
First of all the onInit method is not called at all, only at the moment when I exit the current Activity.
Somehow, after using TTS, the speeker's volume turns to mute and I cannot turn the volume back from the settings(only after I reboot the Glasses)
Am I doing something wrong? or simply Google Glass does not support TTS, even thought is hard to believe that.
Any suggestion is welcome! Thank you very much!:)
Is it possible that you are calling stopTTS before TextToSpeech is initialized?
This works just fine for me on Glass:
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.MotionEvent;
import android.widget.TextView;
import java.util.Locale;
public class TTSTestActivity extends Activity
implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
private boolean initialized = false;
private String queuedText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView view = new TextView(this);
view.setText("Tap Me");
setContentView(view);
tts = new TextToSpeech(this /* context */, this /* listener */);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
initialized = true;
tts.setLanguage(Locale.ENGLISH);
if (queuedText != null) {
speak(queuedText);
}
}
}
public void speak(String text) {
// If not yet initialized, queue up the text.
if (!initialized) {
queuedText = text;
return;
}
queuedText = null;
// Before speaking the current text, stop any ongoing speech.
tts.stop();
// Speak the text.
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public boolean onGenericMotionEvent(MotionEvent event) {
// On any motion event (including touchpad tap), say 'Hello Glass'
speak("Hello Glass");
return true;
}
}
With this example, anytime you tap the touch pad (or cause any other type of motion event), you should hear "Hello Glass." Note that if text is provided before TextToSpeech has initialized, then this is queued and then spoken after initialization is a success.
This does not include any tear-down, but to do that you can always put stop/shutdown of TextToSpeech in onDestroy() of the activity.

Why is my Udp.send using Akka.io always getting timeout?

Executing this code always results in timeout error and never sending UDP packet.
Why?
I need to write somthing more because stackoverflow won't let me to send the question... ;-), but I think the question is very simple and the code is all needed.
package controllers;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.dispatch.Recover;
import akka.io.Tcp;
import akka.io.Udp;
import akka.io.UdpMessage;
import akka.japi.Procedure;
import akka.util.ByteString;
import java.net.InetSocketAddress;
import static akka.pattern.Patterns.ask;
import play.libs.Akka;
import play.mvc.Result;
import play.libs.F.Function;
import play.libs.F.Promise;
import play.mvc.*;
public class Application extends Controller {
static ActorRef myActor = Akka.system().actorOf(Props.create(Listener.class));
public static Result index() {
return async(
Akka.asPromise(
//Promise.wrap(
ask(
myActor,
UdpMessage.send(ByteString.fromString("esto es una prueba"), new InetSocketAddress("172.80.1.81", 21001)),
1000
)
// .recover(
// new Recover<Object>() {
// #Override
// public Object recover(Throwable t) throws Throwable {
// if( t instanceof AskTimeoutException ) {
// Logger.error("Got exception: ", t);
// return internalServerError("Timeout");
// }
// else {
// Logger.error("Got exception: ", t);
// return internalServerError("Got Exception: " + t.getMessage());
// }
// }
// })
).map(
new Function<Object,Result>() {
public Result apply(Object response) {
return ok(response.toString());
}
}
)
);
}
//http://doc.akka.io/docs/akka/2.2-M2/java/io.html
//https://gist.github.com/kafecho/5353393
//how to terminate actor on shutdown http://stackoverflow.com/questions/10875101/how-to-stop-an-akka-thread-on-shutdown
public static class Listener extends UntypedActor {
final ActorRef nextActor;
public Listener() {
this(null);
}
public Listener(ActorRef nextActor) {
this.nextActor = nextActor;
// request creation of a bound listen socket
final ActorRef mgr = Udp.get(getContext().system()).getManager();
mgr.tell(UdpMessage.bind(getSelf(), new InetSocketAddress("localhost",
31001)), getSelf());
}
#Override
public void onReceive(Object msg) {
if (msg instanceof Udp.Bound) {
final Udp.Bound b = (Udp.Bound) msg;
getContext().become(ready(getSender()));
} else
unhandled(msg);
}
private Procedure<Object> ready(final ActorRef socket) {
return new Procedure<Object>() {
#Override
public void apply(Object msg) throws Exception {
if (msg instanceof Udp.Received) {
final Udp.Received r = (Udp.Received) msg;
// echo server example: send back the data
socket.tell(UdpMessage.send(r.data(), r.sender()),
getSelf());
// or do some processing and forward it on
final Object processed = new Object();//TODO parse data etc., e.g. using PipelineStage
if(nextActor!=null){
nextActor.tell(processed, getSelf());
}
} else if (msg.equals(UdpMessage.unbind())) {
socket.tell(msg, getSelf());
} else if (msg instanceof Udp.Unbound) {
getContext().stop(getSelf());
} else if (msg instanceof Udp.Send){
socket.tell(msg, getSelf());
} else
unhandled(msg);
}
};
}
}
}

How to remove all comments from docx file with docx4j?

I'd like to remove all the comments from a docx file using docx4j.
I can remove the actual comments with a piece of code like is shown below, but I think I also need to remove the comment references from the main document part as well (otherwise the document is corrupted), but I can't figure out how to do that.
CommentsPart cmtsPart = wordMLPackage.getMainDocumentPart().getCommentsPart();
org.docx4j.wml.Comments cmts = cpart.getJaxbElement();
List<Comments.Comment> coms = cmts.getComment();
coms.clear();
Any guidance appreciated!
I also posted this question on the docx4j forum: http://www.docx4java.org/forums/docx-java-f6/how-to-remove-all-comments-from-docx-file-t1329.html.
Thanks.
You can use TraversalUtil to find the relevant objects (CommentRangeStart, CommentRangeEnd, R.CommentReference), and then remove them.
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.docx4j.TraversalUtil;
import org.docx4j.TraversalUtil.CallbackImpl;
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Body;
import org.docx4j.wml.CommentRangeEnd;
import org.docx4j.wml.CommentRangeStart;
import org.docx4j.wml.ContentAccessor;
import org.docx4j.wml.R.CommentReference;
import org.jvnet.jaxb2_commons.ppp.Child;
public class Foo {
public static void main(String[] args) throws Exception {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(new java.io.File(System.getProperty("user.dir") + "/Foo.docx"));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart
.getJaxbElement();
Body body = wmlDocumentEl.getBody();
CommentFinder cf = new CommentFinder();
new TraversalUtil(body, cf);
for (Child commentElement : cf.commentElements) {
System.out.println(commentElement.getClass().getName());
Object parent = commentElement.getParent();
List<Object> theList = ((ContentAccessor)parent).getContent();
boolean removeResult = remove(theList, commentElement );
System.out.println(removeResult);
}
}
private static boolean remove(List<Object> theList, Object bm) {
// Can't just remove the object from the parent,
// since in the parent, it may be wrapped in a JAXBElement
for (Object ox : theList) {
if (XmlUtils.unwrap(ox).equals(bm)) {
return theList.remove(ox);
}
}
return false;
}
static class CommentFinder extends CallbackImpl {
List<Child> commentElements = new ArrayList<Child>();
#Override
public List<Object> apply(Object o) {
if (o instanceof javax.xml.bind.JAXBElement
&& (((JAXBElement)o).getName().getLocalPart().equals("commentReference")
|| ((JAXBElement)o).getName().getLocalPart().equals("commentRangeStart")
|| ((JAXBElement)o).getName().getLocalPart().equals("commentRangeEnd")
)) {
System.out.println(((JAXBElement)o).getName().getLocalPart());
commentElements.add( (Child)XmlUtils.unwrap(o) );
} else
if (o instanceof CommentReference ||
o instanceof CommentRangeStart ||
o instanceof CommentRangeEnd) {
System.out.println(o.getClass().getName());
commentElements.add((Child)o);
}
return null;
}
#Override // to setParent
public void walkJAXBElements(Object parent) {
List children = getChildren(parent);
if (children != null) {
for (Object o : children) {
if (o instanceof javax.xml.bind.JAXBElement
&& (((JAXBElement)o).getName().getLocalPart().equals("commentReference")
|| ((JAXBElement)o).getName().getLocalPart().equals("commentRangeStart")
|| ((JAXBElement)o).getName().getLocalPart().equals("commentRangeEnd")
)) {
((Child)((JAXBElement)o).getValue()).setParent(XmlUtils.unwrap(parent));
} else {
o = XmlUtils.unwrap(o);
if (o instanceof Child) {
((Child)o).setParent(XmlUtils.unwrap(parent));
}
}
this.apply(o);
if (this.shouldTraverse(o)) {
walkJAXBElements(o);
}
}
}
}
}
}

How to build a custom draw2d layoutmanager?

I would like to have a layout manager that can arrange two elements as follows:
one main element ABCDEF centered
one "postscript" element XYZ, positioned on the top right corner of the encapsulating figure
For example:
***********XYZ*
* ABCDEF *
***************
Can I use an existing layoutmanager for this? How do I build a custom layout manager that supports it?
Many thanks for your advice.
You can do that by using XYLayout.
There is a sample you can build on:
import org.eclipse.draw2d.AbstractLayout;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.LayoutManager;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.Panel;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.geometry.PrecisionRectangle;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class HHH {
public static void main(String[] args) {
Display d = new Display();
Shell s = new Shell();
s.setLayout(new FillLayout());
FigureCanvas canvas = new FigureCanvas(s);
Figure content = new Figure();
content.setLayoutManager(new XYLayout());
PostScriptedFigure figure = new PostScriptedFigure();
content.add(figure, new Rectangle(100, 100, -1, -1));
figure.setMainFigure(new Label("The Main figure"));
figure.setPostScriptFigure(new Label("ps"));
figure.setBorder(new LineBorder());
canvas.setContents(content);
s.setSize(600, 500);
s.open();
while (!s.isDisposed()) {
if (!d.readAndDispatch()) {
d.sleep();
}
}
}
}
class PostScriptedFigure extends Panel {
private IFigure mainFigure, postScriptFigure;
private class PostScriptedLayoutManager extends AbstractLayout {
#Override
public void layout(IFigure container) {
final Rectangle clientArea = container.getClientArea();
final IFigure mainFigure = getMainFigure();
final IFigure postScriptFigure = getPostScriptFigure();
if (mainFigure != null) {
final Rectangle bounds = new PrecisionRectangle();
bounds.setSize(mainFigure.getPreferredSize(SWT.DEFAULT, SWT.DEFAULT));
final Rectangle mainClientArea = clientArea.getCopy();
if (postScriptFigure != null) {
mainClientArea.shrink(new Insets(postScriptFigure.getPreferredSize().height(), 0, 0, 0));
}
bounds.translate(mainClientArea.getCenter().getTranslated(bounds.getSize().getScaled(0.5f).getNegated()));
mainFigure.setBounds(bounds);
}
if (postScriptFigure != null) {
final Rectangle bounds = new PrecisionRectangle();
bounds.setSize(postScriptFigure.getPreferredSize(SWT.DEFAULT, SWT.DEFAULT));
bounds.translate(clientArea.getTopRight().getTranslated(bounds.getSize().getNegated().width(), 0));
postScriptFigure.setBounds(bounds);
}
// note that other potentionally added figures are ignored
}
#Override
protected Dimension calculatePreferredSize(IFigure container, int wHint, int hHint) {
final Rectangle rect = new PrecisionRectangle();
final IFigure mainFigure = getMainFigure();
if (mainFigure != null) {
rect.setSize(mainFigure.getPreferredSize());
}
final IFigure postScriptFigure = getPostScriptFigure();
if (postScriptFigure != null) {
rect.resize(mainFigure != null ? 0 : postScriptFigure.getPreferredSize().width() , postScriptFigure.getPreferredSize().height());
}
// note that other potentionally added figures are ignored
final Dimension d = rect.getSize();
final Insets insets = container.getInsets();
return new Dimension(d.width + insets.getWidth(), d.height + insets.getHeight()).union(getBorderPreferredSize(container));
}
}
public PostScriptedFigure() {
super.setLayoutManager(new PostScriptedLayoutManager());
}
#Override
public void setLayoutManager(LayoutManager manager) {
// prevent from setting wrong layout manager
}
public IFigure getMainFigure() {
return mainFigure;
}
public void setMainFigure(IFigure mainFigure) {
if (getMainFigure() != null) {
remove(getMainFigure());
}
this.mainFigure = mainFigure;
add(mainFigure);
}
public IFigure getPostScriptFigure() {
return postScriptFigure;
}
public void setPostScriptFigure(IFigure postScriptFigure) {
if (getPostScriptFigure() != null) {
remove(getPostScriptFigure());
}
this.postScriptFigure = postScriptFigure;
add(postScriptFigure);
}
}