iTextSharp different results on Windows 7 vs Windows 8.1 - itext

When I run the following code on Windows 7 and 8.1 I get different results. On Windows 7 if I re-run the code on the newly created file it throws exceptions while the Windows 8.1 code works fine.
Any Clues?????
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string a = #"C:\temp\Materials\20130911134612877_3.pdf";
string b = #"C:\temp\Materials\20130911134612877_4.pdf";
Program p = new Program();
p.Open(a);
p.SaveSource(b);
}
public List<Bitmap> Bitmaps { get; private set; }
private string sourceFileName { get; set; }
private string destPath { get; set; }
public List<int> Source { get; set; }
public List<int> Destination { get; set; }
public void Open(string fileName)
{
this.sourceFileName = fileName;
this.destPath = Path.Combine(Path.GetDirectoryName(fileName), "Processed");
if (!Directory.Exists(destPath))
{
Directory.CreateDirectory(this.destPath);
}
string original = Path.Combine(Path.GetDirectoryName(fileName), "Orginal", Path.GetFileName(fileName));
if (!File.Exists(original))
{
string originalPath = Path.GetDirectoryName(original);
if (!Directory.Exists(originalPath))
{
Directory.CreateDirectory(originalPath);
}
File.Copy(fileName, original);
}
if (this.Bitmaps != null)
{
for (int _i = 0; _i < this.Bitmaps.Count; _i++)
{
this.Bitmaps[_i].Dispose();
}
}
PDFDocument doc = GetDocument(fileName);
this.Bitmaps = new List<Bitmap>();
this.Source = new List<int>();
this.Destination = new List<int>();
for (int i = 0; i < doc.Count; i++)
{
this.Source.Add(i);
this.Bitmaps.Add(doc.GetImage(i));
}
doc.Close();
}
public void SaveSource(string file)
{
if (this.Source.Count != 0)
{
PDFDocument pdf = new PDFDocument();
pdf.FileName = file;
foreach (int i in this.Source)
{
pdf.Add(this.Bitmaps[i]);
}
pdf.Close();
}
else
{
if (File.Exists(this.sourceFileName))
{
File.Delete(this.sourceFileName);
}
}
}
private PDFDocument GetDocument(string file)
{
PDFDocument doc = null;
doc = new PDFDocument();
doc.Open(file);
return doc;
}
public static void MergePdfFiles(IEnumerable<string> files, string output)
{
iTextSharp.text.Document doc;
iTextSharp.text.pdf.PdfCopy pdfCpy;
doc = new iTextSharp.text.Document();
pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(output, System.IO.FileMode.Create));
doc.Open();
foreach (string file in files)
{
// initialize a reader
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(file);
int pageCount = reader.NumberOfPages;
// set page size for the documents
doc.SetPageSize(reader.GetPageSizeWithRotation(1));
for (int pageNum = 1; pageNum <= pageCount; pageNum++)
{
iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, pageNum);
pdfCpy.AddPage(page);
}
reader.Close();
}
doc.Close();
}
}
public class MyImageRenderListener : IRenderListener
{
public void RenderText(TextRenderInfo renderInfo) { }
public void BeginTextBlock() { }
public void EndTextBlock() { }
public Bitmap Image = null;
public void RenderImage(ImageRenderInfo renderInfo)
{
try
{
PdfImageObject image = renderInfo.GetImage();
if (image == null) return;
using (MemoryStream ms = new MemoryStream(image.GetImageAsBytes()))
{
Bitmap i = (System.Drawing.Bitmap)Bitmap.FromStream(ms);
Image = (System.Drawing.Bitmap)i.Clone();
i.Dispose();
// int dpi = i.Height / 11;
int yDPI = Image.Height / 11;
int xDPI = (Image.Width * 2) / 17;
xDPI = Math.Abs(xDPI - 300) < 10 ? 300 : xDPI;
yDPI = Math.Abs(yDPI - 300) < 10 ? 300 : yDPI;
xDPI = Math.Abs(xDPI - 600) < 10 ? 600 : xDPI;
yDPI = Math.Abs(yDPI - 600) < 10 ? 600 : yDPI;
if (xDPI == yDPI)
{
Image.SetResolution(xDPI, yDPI);
}
else
{
}
}
}
catch (IOException)
{
/*
* pass-through; image type not supported by iText[Sharp]; e.g. jbig2
*/
}
}
}
public class PDFDocument
{
public string FileName { get; set; }
~PDFDocument()
{
this.Close();
}
public static void AddImage(Stream inputPdfStream, Stream outputPdfStream, Stream inputImageStream)
{
PdfReader reader = new PdfReader(inputPdfStream);
iTextSharp.text.Rectangle size = reader.GetPageSize(1);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(size.Width - 98, size.Height - 98);
PdfStamper stamper = new PdfStamper(reader, outputPdfStream);
int page = 1;
// for (int page = 1; page <= reader.NumberOfPages; page++)
{
PdfContentByte pdfContentByte = stamper.GetOverContent(page);
pdfContentByte.AddImage(image);
}
stamper.Close();
}
public void Open(string fileName)
{
this.reader = new PdfReader(fileName);
this.parser = new PdfReaderContentParser(reader);
this.listener = new MyImageRenderListener();
}
public int Count { get { return reader.NumberOfPages; } }
public Bitmap GetImage(int index)
{
parser.ProcessContent(index + 1, listener);
return listener.Image;
}
public Bitmap GetImage2(int index)
{
PdfDictionary page = reader.GetPageN(index + 1);
return GetImagesFromPdfDict(page);
}
private PdfReaderContentParser parser = null;
private MyImageRenderListener listener = null;
private PdfReader reader = null;
private Bitmap GetImagesFromPdfDict(PdfDictionary dict)
{
PdfDictionary res = (PdfDictionary)(PdfReader.GetPdfObject(dict.Get(PdfName.RESOURCES)));
PdfDictionary xobj = (PdfDictionary)(PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT)));
Bitmap bm = null;
if (xobj != null)
{
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)(PdfReader.GetPdfObject(obj));
PdfName subtype = (PdfName)(PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE)));
if (PdfName.IMAGE.Equals(subtype))
{
int xrefIdx = ((PRIndirectReference)obj).Number;
PdfObject pdfObj = this.reader.GetPdfObject(xrefIdx);
PRStream str = (PRStream)(pdfObj);
iTextSharp.text.pdf.parser.PdfImageObject pdfImage = new iTextSharp.text.pdf.parser.PdfImageObject(str);
bm = (System.Drawing.Bitmap)pdfImage.GetDrawingImage();
bm.SetResolution(300.0f, 300.0f);
break;
}
else if (PdfName.FORM.Equals(subtype) || PdfName.GROUP.Equals(subtype))
{
GetImagesFromPdfDict(tg);
}
}
}
}
return bm;
}
public void Split(string fileName)
{
throw new NotImplementedException();
}
public void Save(System.Drawing.Bitmap bm, string filename)
{
Save(bm, filename, RotateFlipType.RotateNoneFlipNone);
}
const float PAGE_LEFT_MARGIN = 0;
const float PAGE_RIGHT_MARGIN = 0;
const float PAGE_TOP_MARGIN = 0;
const float PAGE_BOTTOM_MARGIN = 0;
public void Save(System.Drawing.Bitmap bm, string filename, System.Drawing.RotateFlipType rotate)
{
Bitmap image = bm;
if (rotate != RotateFlipType.RotateNoneFlipNone)
{
image.RotateFlip(rotate);
}
using (FileStream stream = new FileStream(filename, FileMode.Create))
{
using (iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN))
{
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream);
pdfDocument.Open();
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms);
img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN));
pdfDocument.Add(img);
pdfDocument.Close();
writer.Close();
}
}
}
public void Add(System.Drawing.Bitmap bm)
{
this.Add(bm, RotateFlipType.RotateNoneFlipNone);
}
FileStream stream;
iTextSharp.text.Document pdfDocument;
iTextSharp.text.pdf.PdfWriter writer;
public void Add(System.Drawing.Bitmap bm, System.Drawing.RotateFlipType rotate)
{
if (this.stream == null)
{
this.stream = new FileStream(this.FileName, FileMode.Create);
this.pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN);
this.writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream);
this.pdfDocument.Open();
}
Bitmap image = bm;
if (rotate != RotateFlipType.RotateNoneFlipNone)
{
image.RotateFlip(rotate);
}
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
ms.Seek(0, SeekOrigin.Begin);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms);
img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN));
pdfDocument.Add(img);
}
}
public void Close()
{
if (this.pdfDocument != null)
{
this.pdfDocument.Close();
this.pdfDocument.Dispose();
this.writer.Close();
this.writer.Dispose();
this.stream.Close();
this.stream.Dispose();
this.pdfDocument = null;
this.writer = null;
this.pdfDocument = null;
}
if (this.reader != null)
{
this.reader.Close();
}
}
public void Tag(string oldFile, Stream fs, string text)
{
float x;
float y;
// open the reader
PdfReader reader = new PdfReader(oldFile);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
float height = 60;
float width = 150;
x = size.Width - 40 - width;
y = size.Height - height;
Document document = new Document(size);
// open the writer
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
cb.Rectangle(x, y, width, height);
cb.SetColorFill(BaseColor.WHITE);
cb.Fill();
// close the streams and voilá the file should be changed :)
// write the text in the pdf content
cb.BeginText();
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(bf, 20);
// put the alignment and coordinates here
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x + 5, y + 10, 0);
cb.EndText();
writer.Flush();
document.Close();
reader.Close();
// fs.Seek(0, SeekOrigin.Begin);
}
}
}

Related

Multi-Client Chat and file transfer in linux

\I want to make a socket application that will run on Linux and provide multiple messaging and file transfer. Can you share sample code? Can you help me i am a second year computer engineering student?
I found a similar code in my research, but I cannot connect to my linux server from different computers.I learned this code from github #HondaPL.
This is client codes
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using MessengerLogic;
using System.IO;
namespace Messenger
{
public class Connection
{
public static int BufferSize = 1024;
public static string nick;
public static IPAddress ip = IPAddress.Parse("-.-.-.-");
public static int port = 1234;
public static TcpClient client = new TcpClient();
public static List<string> users = new List<string>();
public static bool isEnd = false;
public static string[] fromServer = new string[30];
public void Connect(string nickname)
{
nick = nickname;
client.Connect(ip, port);
nickname += "$Welcome$";
byte[] buffer = Encoding.ASCII.GetBytes(nickname);
NetworkStream ns = client.GetStream();
Console.WriteLine(nickname);
ns.Write(buffer, 0, buffer.Length);
Thread thread = new Thread(o => ReceiveData((TcpClient)o));
thread.Start(client);
}
static void ReceiveData(TcpClient client)
{
NetworkStream ns = client.GetStream();
byte[] receivedBytes = new byte[1024];
int byte_count;
StringParser parser = new StringParser();
while ((byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length)) > 0)
{
fromServer = new string[30];
users.Clear();
string message = Encoding.ASCII.GetString(receivedBytes, 0, byte_count);
fromServer = parser.Parser(message);
if (fromServer[0] == "List")
{
for (int i = 1; i < fromServer.Length; i++)
{
users.Add(fromServer[i]);
}
isEnd = true;
}
else
{
Console.WriteLine(message);
Console.WriteLine(fromServer[0]);
Console.WriteLine(fromServer[1]);
FrmOnlineUsers.frm.AssignValues(fromServer[0], fromServer[1]);
FrmOnlineUsers.frm.MessageFromClient();
}
}
}
public List<string> Refresh()
{
NetworkStream ns = client.GetStream();
string temp = nick;
temp += "$List$";
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(temp);
ns.Write(buffer, 0, buffer.Length);
while (!isEnd)
{
}
isEnd = false;
return users;
}
public void SendMessage(string who, string msg)
{
NetworkStream ns = client.GetStream();
string temp = $"{who}$Message${msg}$";
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(temp);
ns.Write(buffer, 0, buffer.Length);
}
public void FileSend(string filepath, string nick, string fileName)
{
NetworkStream ns = client.GetStream();
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
byte[] bytesToSend = new byte[fs.Length];
int numBytesRead = fs.Read(bytesToSend, 0, bytesToSend.Length);
int totalBytes = 0;
//Tutaj trzeba dodać, aby pobierał nazwę pliku
string temp = $"{nick}$File${fileName}${fs.Length}";
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(temp);
ns.Write(buffer, 0, buffer.Length);
Thread.Sleep(1000);
for (int i = 0; i <= fs.Length / BufferSize; i++)
{
if (fs.Length - (i * BufferSize) > BufferSize)
{
ns.Write(bytesToSend, i * BufferSize,
BufferSize);
totalBytes += BufferSize;
}
else
{
ns.Write(bytesToSend, i * BufferSize,
(int)fs.Length - (i * BufferSize));
totalBytes += (int)fs.Length - (i * BufferSize);
}
}
fs.Close();
}
}
}

save list in binary file in unity

I have a code that saves data in the data file are saved without any problem.But I also tried to save an array but the array was not saved and I get an error.I keep the data (and also the array) in BinaryFormatter.The error indicates the line bf.Serialize (file, data) before closing the file in the save function.
the code
public class SaveLoadScript : MonoBehaviour
{
public int allMoneyOfplayer, allXpOfPlayer, laval, maxXp, howMuchUpMaxXp;
public float highTime;
public List<GunScript> gun = new List<GunScript>();
public void Start()
{
Save();
}
public void Update()
{
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/saveG.file");
PlayerData data = new PlayerData();
data.money = allMoneyOfplayer;
data.xp = allXpOfPlayer;
if (highTime > data.time)
data.time = highTime;
data.laval = laval;
data.maxXp = maxXp;
data.howMuchUpMaxXp = howMuchUpMaxXp;
for (int i = 0; i < gun.Count; i++)
data.gun.Add(gun[i]);
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/saveG.file"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/saveG.file", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
allMoneyOfplayer = data.money;
allXpOfPlayer = data.xp;
highTime = data.time;
laval = data.laval;
maxXp = data.maxXp;
howMuchUpMaxXp = data.howMuchUpMaxXp;
file.Close();
}
}
}
[System.Serializable]
class PlayerData
{
public int money;
public int xp;
public float time;
public int laval;
public int maxXp;
public int howMuchUpMaxXp;
public List<GunScript> gun = new List<GunScript>();
}
the error
SerializationException: Type 'GunScript' in Assembly 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers (System.RuntimeType type) (at :0)
System.Runtime.Serialization.FormatterServices+<>c__DisplayClass9_0.b__0 (System.Runtime.Serialization.MemberHolder _) (at :0)
System.Collections.Concurrent.ConcurrentDictionary2[TKey,TValue].GetOrAdd (TKey key, System.Func2[T,TResult] valueFactory) (at :0)
System.Runtime.Serialization.FormatterServices.GetSerializableMembers (System.Type type, System.Runtime.Serialization.StreamingContext context) (at :0)
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo () (at :0)
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize (System.Type objectType, System.Runtime.Serialization.ISurrogateSelector surrogateSelector, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.Formatters.Binary.SerObjectInfoInit serObjectInfoInit, System.Runtime.Serialization.IFormatterConverter converter, System.Runtime.Serialization.SerializationBinder binder) (at :0)
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize (System.Type objectType, System.Runtime.Serialization.ISurrogateSelector surrogateSelector, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.Formatters.Binary.SerObjectInfoInit serObjectInfoInit, System.Runtime.Serialization.IFormatterConverter converter, System.Runtime.Serialization.SerializationBinder binder) (at :0)
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArray (System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo objectInfo, System.Runtime.Serialization.Formatters.Binary.NameInfo memberNameInfo, System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo memberObjectInfo) (at :0)
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write (System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo objectInfo, System.Runtime.Serialization.Formatters.Binary.NameInfo memberNameInfo, System.Runtime.Serialization.Formatters.Binary.NameInfo typeNameInfo) (at :0)
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize (System.Object graph, System.Runtime.Remoting.Messaging.Header[] inHeaders, System.Runtime.Serialization.Formatters.Binary.__BinaryWriter serWriter, System.Boolean fCheck) (at :0)
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize (System.IO.Stream serializationStream, System.Object graph, System.Runtime.Remoting.Messaging.Header[] headers, System.Boolean fCheck) (at :0)
[System.Serializable] //<-- add this attribute
public class GunScript
I don't get any errors but my script doesn't load or possibly save my array...
here's the first script
[System.Serializable]
public class PlayerData
{
public float health;
public float thirst;
public float hunger;
public float oxygen;
public float[] position;
public int[] inventoryIDs;
public PlayerData (Health healthO, SaveLoad saveload)
{
//Save int items
health = healthO.health;
thirst = healthO.thirst;
hunger = healthO.hunger;
oxygen = healthO.oxygen;
//set and save location array
position = new float[3];
position[0] = healthO.transform.position.x;
position[1] = healthO.transform.position.y;
position[2] = healthO.transform.position.z;
//set and save inventory IDs
inventoryIDs = new int[50];
for(int i = 0; i < 50; i++)
{
inventoryIDs[i] = saveload.IDs[i];
}
}
}
here's the next
public class SaveLoad : MonoBehaviour
{
public GameObject player;
public int[] IDs;
public GameObject[] objects;
Inventory inventory;
Health health;
void Start()
{
IDs = new int[50];
objects = new GameObject[50];
inventory = player.GetComponent<Inventory>();
health = player.GetComponent<Health>();
}
void Update()
{
//Add IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = inventory.slot[i].GetComponent<Slot>().ID;
}
//debug save load test
if (Input.GetKeyDown(KeyCode.Z))
{
SaveP();
}
if (Input.GetKeyDown(KeyCode.X))
{
LoadP();
}
}
public void SaveP()
{
SaveSystem.SavePlayer(health, this);
}
public void LoadP()
{
PlayerData data = SaveSystem.LoadPlayer();
//load stats
health.thirst = data.thirst;
health.hunger = data.hunger;
health.health = data.health;
health.oxygen = data.oxygen;
//Load position
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
player.transform.position = position;
//load IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = data.inventoryIDs[i];
}
//Load Items
for (int i = 0; i < 50; i++)
{
if(objects[IDs[i]] != null)
{
GameObject itemObject = (GameObject)Instantiate(objects[IDs[i]], new Vector3(0, 0, 0), Quaternion.identity);
Item item = itemObject.GetComponent<Item>();
inventory.AddItem(itemObject, item.ID, item.type, item.name, item.description, item.icon);
} else
{
return;
}
}
}
}
Here's the last script
public static class SaveSystem
{
public static string fileName = "FileSave.bin";
public static void SavePlayer(Health health, SaveLoad SL)
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
// Create file stream
FileStream file = File.Create(GetFullPath());
//Save data
PlayerData data = new PlayerData(health, SL);
bf.Serialize(file, data);
//Close stream
file.Close();
}
public static PlayerData LoadPlayer()
{
if (SaveExists())
{
try
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
//Create file stream
FileStream file = File.Open(GetFullPath(), FileMode.Open);
//Load data
PlayerData pd = (PlayerData)bf.Deserialize(file);
//close stream
file.Close();
//return data
return pd;
}
catch (SerializationException)
{
Debug.Log("Failed to load file at: " + GetFullPath());
}
}
return null;
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static string GetFullPath()
{
return Application.persistentDataPath + "/" + fileName;
}
}
there are all connected with the save load script loading and saving the variables into the player and items to the inventory sots. the inventory IDs array isn't saving or loading

Camera 2 api full screen not to stretch

private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
private static final SparseIntArray DEFAULT_ORIENTATIONS = new SparseIntArray();
private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();
private static final long DELAY = 1000;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private long startTime = 0L;
int num = 1;
List<VideoModel> videoList;
private Handler customHandler = new Handler();
private static final String TAG = "RecordVideoActivity";
private String videoName;
static {
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_0, 90);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_90, 0);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_180, 270);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
static {
INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
}
private AutoFitTextureView mTextureView;
private ImageButton mRecordButton;
private ImageView mDots;
private ImageButton mCheckPoint;
private CameraDevice mCameraDevice;
private CameraCaptureSession mPreviewSession;
private TextureView.SurfaceTextureListener mSurfaceTextureListener
= new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
int width, int height) {
openCamera(width, height);
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
int width, int height) {
configureTransform(width, height);
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
private Size mPreviewSize;
private Size mVideoSize;
private MediaRecorder mMediaRecorder;
private boolean mIsRecordingVideo;
private HandlerThread mBackgroundThread;
private Handler mBackgroundHandler;
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice cameraDevice) {
mCameraDevice = cameraDevice;
startPreview();
mCameraOpenCloseLock.release();
if (null != mTextureView) {
configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
}
}
#Override
public void onDisconnected(#NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
#Override
public void onError(#NonNull CameraDevice cameraDevice, int error) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
finish();
}
};
private Integer mSensorOrientation;
private String mNextVideoAbsolutePath;
private CaptureRequest.Builder mPreviewBuilder;
private CameraManager manager;
private String cameraId;
private boolean isFlashSupported;
private ImageButton flashButton;
private ImageButton switchCamera;
private ImageButton revertVideo;
public static final String CAMERA_BACK = "0";
private TextView mChronometer;
private String flashOpt;
private long lastSavedTime;
private String prepend;
private static Size chooseVideoSize(Size[] choices) {
for (Size size : choices) {
if (size.getWidth() == size.getHeight() * 4 / 3 && size.getWidth() <= 1080) {
return size;
}
}
Log.e(TAG, "Couldn't find any suitable video size");
return choices[choices.length - 1];
}
private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
// Collect the supported resolutions that are at least as big as the preview Surface
List<Size> bigEnough = new ArrayList<>();
int w = aspectRatio.getWidth();
int h = aspectRatio.getHeight();
for (Size option : choices) {
if (option.getHeight() == option.getWidth() * h / w &&
option.getWidth() >= width && option.getHeight() >= height) {
bigEnough.add(option);
}
}
// Pick the smallest of those, assuming we found any
if (bigEnough.size() > 0) {
return Collections.min(bigEnough, new CompareSizesByArea());
} else {
Log.e(TAG, "Couldn't find any suitable preview size");
return choices[0];
}
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera2_video_image);
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) + File.separator + AppConstants.APPDIRRECORDING);
if (dir.isDirectory()) {
deleteDirectory(dir);
}
videoList = new ArrayList<>();
mTextureView = findViewById(R.id.textureView);
mRecordButton = findViewById(R.id.videoOnlineImageButton);
mRecordButton.setImageResource(R.drawable.ic_video);
mCheckPoint = findViewById(R.id.checkPoint);
mCheckPoint.setVisibility(View.GONE);
mDots = findViewById(R.id.dot);
mRecordButton.setOnClickListener(this);
flashButton = findViewById(R.id.flashVideo);
switchCamera = findViewById(R.id.switchVideo);
revertVideo = findViewById(R.id.revertVideo);
revertVideo.setVisibility(View.GONE);
mChronometer = findViewById(R.id.chronometer);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
flashOpt = prefs.getString(getString(R.string.flash_option), getString(R.string.auto));
if (flashOpt.equals(getString(R.string.flash_off)))
flashButton.setImageResource(R.drawable.flash_auto);
else if (flashOpt.equals(getString(R.string.flash_on)))
flashButton.setImageResource(R.drawable.flash_on);
else
flashButton.setImageResource(R.drawable.flash_off);
findViewById(R.id.checkPoint).setOnClickListener(this);
findViewById(R.id.flashVideo).setOnClickListener(this);
findViewById(R.id.switchVideo).setOnClickListener(this);
findViewById(R.id.revertVideo).setOnClickListener(this);
}
#Override
public void onResume() {
super.onResume();
startBackgroundThread();
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
if(mIsRecordingVideo)
mRecordButton.setImageResource(R.drawable.ic_video_stop);
else
mRecordButton.setImageResource(R.drawable.ic_video);
mCheckPoint.setEnabled(true);
startTime=SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
#Override
public void onPause() {
closeCamera();
mCheckPoint.setEnabled(false);
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
stopBackgroundThread();
super.onPause();
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int hour = mins / 60;
mChronometer.setText("" + hour + ":"
+ String.format("%02d", mins) + ":"
+ String.format("%02d", secs));
customHandler.postDelayed(this, 0);
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.videoOnlineImageButton: {
if (mIsRecordingVideo) {
mDots.setVisibility(View.GONE);
mChronometer.setVisibility(View.GONE);
switchCamera.setVisibility(View.VISIBLE);
mCheckPoint.setVisibility(View.GONE);
stopRecordingVideo();
Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaStoreUpdateIntent.setData(Uri.fromFile(new File(mNextVideoAbsolutePath)));
sendBroadcast(mediaStoreUpdateIntent);
} else {
mCheckPoint.setVisibility(View.VISIBLE);
switchCamera.setVisibility(View.GONE);
mChronometer.setVisibility(View.VISIBLE);
mDots.setVisibility(View.VISIBLE);
startRecordingVideo();
}
break;
}
case R.id.switchVideo: {
facingCamera = !facingCamera;
closeCamera();
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
break;
}
case R.id.flashVideo: {
if (onFlashCheck()) {
CameraCharacteristics cameraCharacteristics = null;
try {
cameraCharacteristics = manager.getCameraCharacteristics(cameraId);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Boolean available = cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
isFlashSupported = available == null ? false : available;
switchFlash();
}
break;
}
}
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#SuppressLint("MissingPermission")
private void openCamera(int width, int height) {
final Activity activity = this;
if (null == activity || activity.isFinishing()) {
return;
}
manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
Log.d(TAG, "tryAcquire");
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
cameraId = manager.getCameraIdList()[1];
if (facingCamera) {
cameraId = manager.getCameraIdList()[1];
flashButton.setVisibility(View.GONE);
} else {
cameraId = manager.getCameraIdList()[0];
flashButton.setVisibility(View.VISIBLE);
}
// Choose the sizes for camera preview and video recording
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics
.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
if (map == null) {
throw new RuntimeException("Cannot get available preview/video sizes");
}
mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
width, height, mVideoSize);
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
} else {
mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
}
configureTransform(width, height);
mMediaRecorder = new MediaRecorder();
manager.openCamera(cameraId, mStateCallback, null);
} catch (CameraAccessException e) {
Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
activity.finish();
} catch (NullPointerException e) {
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.");
}
}
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
closePreviewSession();
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mMediaRecorder) {
mMediaRecorder.release();
mMediaRecorder = null;
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.");
} finally {
mCameraOpenCloseLock.release();
}
}
private void startPreview() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
return;
}
try {
closePreviewSession();
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
Surface previewSurface = new Surface(texture);
mPreviewBuilder.addTarget(previewSurface);
mCameraDevice.createCaptureSession(Collections.singletonList(previewSurface),
new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession session) {
mPreviewSession = session;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession session) {
Toast.makeText(RecordVideoActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void updatePreview() {
if (null == mCameraDevice) {
return;
}
try {
setUpCaptureRequestBuilder(mPreviewBuilder);
HandlerThread thread = new HandlerThread("CameraPreview");
thread.start();
mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void setUpCaptureRequestBuilder(CaptureRequest.Builder builder) {
if (onFlashCheck()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
flashButton.setVisibility(View.VISIBLE);
}
});
if (flashOpt.equals(getString(R.string.auto)))
builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
else if (flashOpt.equals(getString(R.string.flash_off)))
builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
else
builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
} else
runOnUiThread(new Runnable() {
#Override
public void run() {
flashButton.setVisibility(View.GONE);
}
});
}
private void configureTransform(int viewWidth, int viewHeight) {
if (null == mTextureView || null == mPreviewSize) {
return;
}
int rotation = getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max(
(float) viewHeight / mPreviewSize.getHeight(),
(float) viewWidth / mPreviewSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
}
mTextureView.setTransform(matrix);
}
private void setUpMediaRecorder() throws IOException {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
File file = getVideoFilePath(this);
mNextVideoAbsolutePath = file.getAbsolutePath();
videoName = file.getName();
mMediaRecorder.setOutputFile(mNextVideoAbsolutePath);
mMediaRecorder.setVideoEncodingBitRate(10000000);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
switch (mSensorOrientation) {
case SENSOR_ORIENTATION_DEFAULT_DEGREES:
mMediaRecorder.setOrientationHint(DEFAULT_ORIENTATIONS.get(rotation));
break;
case SENSOR_ORIENTATION_INVERSE_DEGREES:
mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
break;
}
mMediaRecorder.prepare();
}
private File getVideoFilePath(Context context) {
File appDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) + File.separator + AppConstants.APPDIRRECORDING);
if (!appDir.isDirectory()) {
appDir.mkdirs();
}
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "VIDEO_" + timestamp + ".mp4";
File videoFile = null;
try {
videoFile = File.createTempFile(prepend, ".mp4", appDir);
} catch (IOException e) {
e.printStackTrace();
}
return videoFile;
}
private void startRecordingVideo() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
return;
}
try {
closePreviewSession();
setUpMediaRecorder();
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
List<Surface> surfaces = new ArrayList<>();
// Set up Surface for the camera preview
Surface previewSurface = new Surface(texture);
surfaces.add(previewSurface);
mPreviewBuilder.addTarget(previewSurface);
// Set up Surface for the MediaRecorder
Surface recorderSurface = mMediaRecorder.getSurface();
surfaces.add(recorderSurface);
mPreviewBuilder.addTarget(recorderSurface);
mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull final CameraCaptureSession cameraCaptureSession) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPreviewSession = cameraCaptureSession;
updatePreview();
mIsRecordingVideo = true;
startTime = SystemClock.uptimeMillis();
mChronometer.setVisibility(View.VISIBLE);
customHandler.postDelayed(updateTimerThread, 0);
mRecordButton.setImageResource(R.drawable.ic_video_stop);
mMediaRecorder.start();
mCheckPoint.setEnabled(true);
}
});
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(RecordVideoActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}, mBackgroundHandler);
} catch (CameraAccessException | IOException e) {
e.printStackTrace();
}
}
private void closePreviewSession() {
if (mPreviewSession != null) {
mPreviewSession.close();
mPreviewSession = null;
}
}
#SuppressLint("ResourceType")
private void stopRecordingVideo() {
mIsRecordingVideo = false;
customHandler.removeCallbacks(updateTimerThread);
mRecordButton.setImageResource(R.drawable.ic_video);
if(mMediaRecorder!=null) {
try {
mMediaRecorder.stop();
} catch (RuntimeException e) {
e.printStackTrace();
}
mMediaRecorder.reset();
}
}
static class CompareSizesByArea implements Comparator<Size> {
#Override
public int compare(Size lhs, Size rhs) {
return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
(long) rhs.getWidth() * rhs.getHeight());
}
}
#Override
protected void onDestroy() {
customHandler.removeCallbacks(updateTimerThread);
}
I have implemented following coding in my app.i used camera 2 api for video recording.i feel that video streaming is stretched. mainly when i switch camera into front one.pls help me to resolve this problem
I have implemented following coding in my app.i used camera 2 api for video recording.i feel that video streaming is stretched. mainly when i switch camera into front one.pls help me to resolve this problem
Change aspect ratio values in AutoFitTextureView class or use Textureview instead of AutoFitTextureview.

change pdf image background using Itextsharp

I am trying to change background color of all images of pdf using Itextshap.
How can i loop through all images and change background color of the images
I used below code to extract pdf images
public static void ExtractImagesFromPDF(string sourcePdf, string outputPath)
{
// NOTE: This will only get the first image it finds per page.
PdfReader pdf = new PdfReader(sourcePdf);
RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);
try
{
for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
{
PdfDictionary pg = pdf.GetPageN(pageNumber);
// recursively search pages, forms and groups for images.
PdfObject obj = FindImageInPDFDictionary(pg);
if (obj != null)
{
int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
PdfStream pdfStrem = (PdfStream)pdfObj;
byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
if ((bytes != null))
{
using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
{
memStream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
// must save the file while stream is open.
if (!Directory.Exists(outputPath))
Directory.CreateDirectory(outputPath);
string path = Path.Combine(outputPath, String.Format(#"{0}.jpg", pageNumber));
System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
System.Drawing.Imaging.ImageCodecInfo jpegEncoder = Utilities.GetImageEncoder("JPEG");
img.Save(path, jpegEncoder, parms);
}
}
}
}
}
catch
{
throw;
}
finally
{
pdf.Close();
raf.Close();
}
}
private static PdfObject FindImageInPDFDictionary(PdfDictionary pg)
{
PdfDictionary res =
(PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
PdfDictionary xobj =
(PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
if (xobj != null)
{
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
PdfName type =
(PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
//image at the root of the pdf
if (PdfName.IMAGE.Equals(type))
{
return obj;
}// image inside a form
else if (PdfName.FORM.Equals(type))
{
return FindImageInPDFDictionary(tg);
} //image inside a group
else if (PdfName.GROUP.Equals(type))
{
return FindImageInPDFDictionary(tg);
}
}
}
}
return null;
}
Many thanks in advance

Check manually a JMenuItem in a JPopUpMenu?

I have a JPopUpMenu with several JCheckBoxMenuItem's on it.
Actually what I would like to do is basicly to select an item of the JPopUpMenu with a specific index.
For exemple, a method like myPopUpMenu.setSelected(2), which would select "Algérie" in my JPopUpMenu.
The problem is that I don't know any method which would allow me to check an item manually...
Here's the code of my JPopUpMenu :
MainVue.java:
public class MainVue extends JFrame implements ActionListener {
private static final JScrollPopupMenu menuProduit = new JScrollPopupMenu();
private static final JScrollPopupMenu menuPays = new JScrollPopupMenu();
private static List<String> listeFiltres = new ArrayList<String>();
private String listeDeFiltres;
private String[] tableauFiltrePermanent;
private String listeFiltrePermanent;
private String[] tableauPays = { "Autres", "Afrique du sud", "Algérie", "Allemagne", "Arabie Saoudite", "Argentine",
"Australie", "Bangladesh", "Belgique", "Brésil", "Bulgarie", "Canada", "Chine", "Corée du sud", "Egypte",
"Emirats-Arabes Unis", "Espagne", "Etats-Unis", "Ethiopie", "Europe", "France", "Hongrie", "Inde",
"Indonésie", "Irak", "Iran", "Israél", "Italie", "Japon", "Jordanie", "Kazakhstan", "Koweit", "Liban",
"Libye", "Malaisie", "Maroc", "Mexique", "Monde", "Oman", "Pakistan", "Pays-Bas", "Philippines", "Poligne",
"Portugal", "Qatar", "République tchéque", "Roumanie", "Russie", "Taïwan", "Tunisie", "Turquie",
"Ukraine" };
private String[] tableauProduit = { "Blé", "Colza", "Mais", "Orge", "Orge de Brasserie", "Palme", "Soja",
"Tournesol", "Tourteaux De Colza", "Tourteaux de Soja", "Huile de Soja", "Huile De Colza" };
private List<JCheckBoxMenuItem> listJCBProduit = new ArrayList<JCheckBoxMenuItem>();
private List<JCheckBoxMenuItem> listJCBPays = new ArrayList<JCheckBoxMenuItem>();
public static PropertiesConfiguration prop;
public MainVue(Modele modele, Controleur controleur) throws ClassNotFoundException, SQLException, IOException {
prop = new PropertiesConfiguration("config.properties");
for (int i = 0; i < tableauProduit.length; i++) {
listJCBProduit.add(new JCheckBoxMenuItem(tableauProduit[i]));
}
for (int j = 0; j < listJCBProduit.size(); j++) {
JCheckBoxMenuItem produitActuel = listJCBProduit.get(j);
menuProduit.add(produitActuel);
produitActuel.addActionListener(new OpenAction(menuProduit, boutonProduit));
}
for (int i = 0; i < tableauPays.length; i++) {
listJCBPays.add(new JCheckBoxMenuItem(tableauPays[i]));
}
for (int j = 0; j < listJCBPays.size(); j++) {
JCheckBoxMenuItem paysActuel = listJCBPays.get(j);
menuPays.add(paysActuel);
paysActuel.addActionListener(new OpenAction(menuPays, boutonPays));
}
listeDeFiltres = "";
for (int p = 0; p < listeFiltres.size(); p++) {
String filtreActuel = listeFiltres.get(p);
if (listeDeFiltres == "") {
listeDeFiltres += filtreActuel;
} else {
listeDeFiltres += "," + filtreActuel;
}
}
prop.setProperty("listeFiltres", listeDeFiltres);
}
}
Here's the JScrollPopUpMenu component :
JScrollPopUpMenu.java:
package fr.views;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
public class JScrollPopupMenu extends JPopupMenu {
protected int maximumVisibleRows = 10;
public JScrollPopupMenu() {
this(null);
}
public JScrollPopupMenu(String label) {
super(label);
setLayout(new ScrollPopupMenuLayout());
super.add(getScrollBar());
addMouseWheelListener(new MouseWheelListener() {
#Override public void mouseWheelMoved(MouseWheelEvent event) {
JScrollBar scrollBar = getScrollBar();
int amount = (event.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL)
? event.getUnitsToScroll() * scrollBar.getUnitIncrement()
: (event.getWheelRotation() < 0 ? -1 : 1) * scrollBar.getBlockIncrement();
scrollBar.setValue(scrollBar.getValue() + amount);
event.consume();
}
});
}
private JScrollBar popupScrollBar;
protected JScrollBar getScrollBar() {
if(popupScrollBar == null) {
popupScrollBar = new JScrollBar(JScrollBar.VERTICAL);
popupScrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override public void adjustmentValueChanged(AdjustmentEvent e) {
doLayout();
repaint();
}
});
popupScrollBar.setVisible(false);
}
return popupScrollBar;
}
public int getMaximumVisibleRows() {
return maximumVisibleRows;
}
public void setMaximumVisibleRows(int maximumVisibleRows) {
this.maximumVisibleRows = maximumVisibleRows;
}
public void paintChildren(Graphics g){
Insets insets = getInsets();
g.clipRect(insets.left, insets.top, getWidth(), getHeight() - insets.top - insets.bottom);
super.paintChildren(g);
}
protected void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
if(maximumVisibleRows < getComponentCount()-1) {
getScrollBar().setVisible(true);
}
}
public void remove(int index) {
// can't remove the scrollbar
++index;
super.remove(index);
if(maximumVisibleRows >= getComponentCount()-1) {
getScrollBar().setVisible(false);
}
}
public void show(Component invoker, int x, int y){
JScrollBar scrollBar = getScrollBar();
if(scrollBar.isVisible()){
int extent = 0;
int max = 0;
int i = 0;
int unit = -1;
int width = 0;
for(Component comp : getComponents()) {
if(!(comp instanceof JScrollBar)) {
Dimension preferredSize = comp.getPreferredSize();
width = Math.max(width, preferredSize.width);
if(unit < 0){
unit = preferredSize.height;
}
if(i++ < maximumVisibleRows) {
extent += preferredSize.height;
}
max += preferredSize.height;
}
}
Insets insets = getInsets();
int widthMargin = insets.left + insets.right;
int heightMargin = insets.top + insets.bottom;
scrollBar.setUnitIncrement(unit);
scrollBar.setBlockIncrement(extent);
scrollBar.setValues(0, heightMargin + extent, 0, heightMargin + max);
width += scrollBar.getPreferredSize().width + widthMargin;
int height = heightMargin + extent;
setPopupSize(new Dimension(width, height));
}
super.show(invoker, x, y);
}
protected static class ScrollPopupMenuLayout implements LayoutManager{
#Override public void addLayoutComponent(String name, Component comp) {}
#Override public void removeLayoutComponent(Component comp) {}
#Override public Dimension preferredLayoutSize(Container parent) {
int visibleAmount = Integer.MAX_VALUE;
Dimension dim = new Dimension();
for(Component comp :parent.getComponents()){
if(comp.isVisible()) {
if(comp instanceof JScrollBar){
JScrollBar scrollBar = (JScrollBar) comp;
visibleAmount = scrollBar.getVisibleAmount();
}
else {
Dimension pref = comp.getPreferredSize();
dim.width = Math.max(dim.width, pref.width);
dim.height += pref.height;
}
}
}
Insets insets = parent.getInsets();
dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);
return dim;
}
#Override public Dimension minimumLayoutSize(Container parent) {
int visibleAmount = Integer.MAX_VALUE;
Dimension dim = new Dimension();
for(Component comp : parent.getComponents()) {
if(comp.isVisible()){
if(comp instanceof JScrollBar) {
JScrollBar scrollBar = (JScrollBar) comp;
visibleAmount = scrollBar.getVisibleAmount();
}
else {
Dimension min = comp.getMinimumSize();
dim.width = Math.max(dim.width, min.width);
dim.height += min.height;
}
}
}
Insets insets = parent.getInsets();
dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);
return dim;
}
#Override public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
int width = parent.getWidth() - insets.left - insets.right;
int height = parent.getHeight() - insets.top - insets.bottom;
int x = insets.left;
int y = insets.top;
int position = 0;
for(Component comp : parent.getComponents()) {
if((comp instanceof JScrollBar) && comp.isVisible()) {
JScrollBar scrollBar = (JScrollBar) comp;
Dimension dim = scrollBar.getPreferredSize();
scrollBar.setBounds(x + width-dim.width, y, dim.width, height);
width -= dim.width;
position = scrollBar.getValue();
}
}
y -= position;
for(Component comp : parent.getComponents()) {
if(!(comp instanceof JScrollBar) && comp.isVisible()) {
Dimension pref = comp.getPreferredSize();
comp.setBounds(x, y, width, pref.height);
y += pref.height;
}
}
}
}
}
Thanks in advance for any help !
The index which you get from getIndex() method use as follows. You are adding ScrollBar in your JScrollPopupMenu at 0 index. So to remove casting error update your code as follow.
int index = getIndex("name");
((JCheckBoxMenuItem)menuProduit.getComponentAtIndex(index+1)).setState(true);