How to pass str variable (line 125) from AsyncTask to onCreate, namely youTubePlayer.loadVideo (myStr); (string56)? - android-asynctask

How to pass str variable (line 125) from AsyncTask to onCreate, namely youTubePlayer.loadVideo (myStr); (string56)?
Please write the same code in the comments, but only with the necessary corrections
public class MainActivity extends YouTubeBaseActivity {
public String titleList;
YouTubePlayerView player;
private final String API_KEY = "xxxxxxxxxx";
public String VIDEO_CODE = "xxxxxxxxx";
// благодоря этому классу мы будет разбирать данные на куски
public Elements title;
// то в чем будем хранить данные пока не передадим адаптеру
// Listview Adapter для вывода данных
private ArrayAdapter<String> adapter;
// List view
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = (YouTubePlayerView)findViewById(R.id.player);
lv = (ListView) findViewById(R.id.listView1);
// запрос к нашему отдельному поток на выборку данных
new NewThread().execute();
// Добавляем данные для ListView
player.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
youTubePlayer.loadVideo(myStr);
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast toast = Toast.makeText(getApplicationContext(),
youTubeInitializationResult.toString(), Toast.LENGTH_SHORT);
toast.show();
}
});
// определение данных
}
/** А вот и внутрений класс который делает запросы, если вы не читали статьи у меня в блоге про отдельные
* потоки советую почитать */
public class NewThread extends AsyncTask<String, Void, String> {
// Метод выполняющий запрос в фоне, в версиях выше 4 андроида, запросы в главном потоке выполнять
// нельзя, поэтому все что вам нужно выполнять - выносите в отдельный тред
#Override
protected String doInBackground(String... arg) {
// класс который захватывает страницу
Document doc;
Random r = new Random();
//https://www.google.ru/search?q=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82&newwindow=1&dcr=0&source=lnt&tbs=qdr:h - за последние 24 часа
String eng = "abcdefghijklmnopqrstuvwxyz";
String dig = "0123456789-_";
String sum = eng + eng.toUpperCase() + dig;
char a = sum.charAt(r.nextInt(sum.length()) );
char b = sum.charAt(r.nextInt(sum.length()) );
char c = sum.charAt(r.nextInt(sum.length()) );
char d = sum.charAt(r.nextInt(sum.length()) );
char k = sum.charAt(r.nextInt(sum.length()) );
String aS = Character.toString(a);
String bS = Character.toString(b);
String cS = Character.toString(c);
String dS = Character.toString(d);
String kS = Character.toString(k);
String fullname =aS + bS + cS + dS + kS;
String url_get_page = "https://www.google.ru/search?newwindow=1&dcr=0&source=hp&ei=jZbMWqbyHtPX6QST_4OQCQ&q=youtube+" + fullname;
try {
// определяем откуда будем воровать данные
doc = Jsoup.connect(url_get_page).get();
// задаем с какого места, я выбрал заголовке статей
title = doc.select("a");
String linkHref = title.attr("href");
String linkInnerH = title.html();
// чистим наш аррей лист для того что бы заполнить
// и в цикле захватываем все данные какие есть на странице
} catch (IOException e) {
e.printStackTrace();
}
// ничего не возвращаем потому что я так захотел)
String lol = title.toString();
int beginning = lol.indexOf(".com/watch?v=");;
char[] link = new char[50];
try {
lol.getChars(beginning + 13, beginning + 24, link, 0);
} catch (Exception ex) {
}
String myStr = new String(link);
return null;
}
#Override
protected void onPostExecute(String result) {
// после запроса обновляем листвью
}
}
}
How to pass str variable (line 125) from AsyncTask to onCreate, namely youTubePlayer.loadVideo (myStr); (string56)?
Please write the same code in the comments, but only with the necessary corrections

Related

Insert Image into PDF Document

Is it possible to add an image to the PDF document? My layout has one (Button) and one (ImageView), I would like that when I click (Button), it will open the Gallery to select the image, show it in (ImageView) and add it to the PDF document, as if it were a generator curriculum, thank you in advance.
*Using com.itextpdf:itextg:5.5.10
here is the complete code of what you wanted. Try this and let me know.
In the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_to_pdf);
imageView = findViewById(R.id.imageView);
galleryBtn = findViewById(R.id.gallery);
convertBtn = findViewById(R.id.convert);
galleryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "PDF_" + timeStamp + "_";
File storageDir = getAlbumDir();
try {
pdfPath = File.createTempFile(
imageFileName, /* prefix */
".pdf", /* suffix */
storageDir /* directory */
);
} catch (IOException e) {
e.printStackTrace();
}
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(photoPickerIntent, GALLERY_INTENT);
}
});
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(ImageToPDF.this, "Please select the image from gallery", Toast.LENGTH_LONG).show();
} else {
convertToPDF(pdfPath);
}
}
});
}
Create a directory for PDF file:
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ "/dcim/"
+ "Image to pdf");
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
On camera activity intent result:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT) {
if (resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
bitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(bitmap);
cursor.close();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("Canceled", "Image not selected");
}
}
}
Now code to convert image to PDF and save to the directory:
private void convertToPDF(File pdfPath) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(width, height, 1).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
try {
pdfDocument.writeTo(new FileOutputStream(pdfPath));
Toast.makeText(ImageToPDF.this, "Image is successfully converted to PDF", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
pdfDocument.close();
}

Why do i get this exception when calling the google calendar event?

This code is export event to google calendar, it is working fine in local but after upload the service in IIS server,i am getting this exception occurred.System.ServiceModel.ProtocolException: 'The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/XML; charset=utf-8).
public partial class UNGCCalendarEvent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button 1_Click(object sender, EventArgs e)
{
// WCFServiceClient client = new WCFServiceClient();
using (UNGCCalenderSoapClient uNGC = new UNGCCalenderSoapClient())
{
uNGC.Endpoint.Binding.SendTimeout = new TimeSpan(0, 2, 30);
// EntityExtractionClient nlp = new EntityExtractionClient();
uNGC.InnerChannel.OperationTimeout = new TimeSpan(0, 50, 0);
string EventSummary = TextSumary.Text.ToString();
string EventLocation = TextLocation.Text.ToString();
string EventDescription = TextDescription.Text.ToString();
string EventStartDateTime = TextStartDate.Text.ToString();
string EventEndDateTime = TextEndDate.Text.ToString();
string CustomCalenderName = TextCustomCalenderName.Text.ToString();
string StartDatetimeZone = TextStartDatetimeZone.Text.ToString();
string EndDatetimeZone = TextEndDatetimeZone.Text.ToString();
string[] attendees = Textattendees.Text.Split(',');
var a = new ArrayOfString { Textattendees.Text };
string attachmentsfileUrl = TextattachmentsfileUrl.Text.ToString();
//string s = new string(attendees);
//string a = uNGC.UNGCCalenderService(EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime));
string calendar = uNGC.ExportGoogleEvents(EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime), CustomCalenderName, StartDatetimeZone, EndDatetimeZone, attachmentsfileUrl, a);
uNGC.Close();
}
}
protected void BtnUpdate_Click(object sender, EventArgs e)
{
UNGCCalenderSoapClient uNGC = new UNGCCalenderSoapClient();
// UNGCCalender arrString = UNGCCalenderSoapClient.ArrayOfString();
string EventID = TextEventID.Text.ToString();
string EventSummary = TextSumary.Text.ToString();
string EventLocation = TextLocation.Text.ToString();
string EventDescription = TextDescription.Text.ToString();
string EventStartDateTime = TextStartDate.Text.ToString();
string EventEndDateTime = TextEndDate.Text.ToString();
string CustomCalenderName = TextCustomCalenderName.Text.ToString();
string StartDatetimeZone = TextStartDatetimeZone.Text.ToString();
string EndDatetimeZone = TextEndDatetimeZone.Text.ToString();
string[] attendees = Textattendees.Text.Split(',');
string attachmentsfileUrl = TextattachmentsfileUrl.Text.ToString();
//string s = new string(attendees);
//string a = uNGC.UNGCCalenderService(EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime));
// string calendar = uNGC.UpdateGoogleEvents(EventID,EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime), CustomCalenderName, StartDatetimeZone, EndDatetimeZone, attachmentsfileUrl, arrString.AddRange(attendees));
}
}

How to assign OnActivityResult values to the Listview?

I have a Listview and Click Events in the respective listItems and need to get result back from the click events and populate on the List.
My BaseAdapter class is
public class RemnantListAdapter : BaseAdapter<InventorySlabs>
{
private PartialInventory context;
private List<InventorySlabs> RemnantList;
public RemnantListAdapter(PartialInventory partialInventory, List<InventorySlabs> remnantList)
{
this.context = partialInventory;
this.RemnantList = remnantList;
}
public override InventorySlabs this[int position]
{
get
{
return RemnantList[position];
}
}
public override int Count
{
get
{
return RemnantList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override int ViewTypeCount
{
get
{
return Count;
}
}
public override int GetItemViewType(int position)
{
return position;
}
private class remnantHolder : Object
{
public Button EditRemnant1;
public TextView Remnant1 = null;
public TextView Rem_StockNMaterial1 = null;
public TextView Rem_Dimensions1 = null;
public TextView Rem_Status1 = null;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
remnantHolder holder = null;
if (convertView == null)
{
convertView = (convertView ?? context.LayoutInflater.Inflate(Resource.Layout.remnant_list, parent, false));
holder = new remnantHolder();
holder.EditRemnant1 = convertView.FindViewById<Button>(Resource.Id.editRemnant1);
holder.Remnant1 = convertView.FindViewById<TextView>(Resource.Id.remnant1);
holder.Rem_StockNMaterial1 = convertView.FindViewById<TextView>(Resource.Id.remnant_mtrl1);
holder.Rem_Dimensions1 = convertView.FindViewById<TextView>(Resource.Id.remnant_dimens1);
holder.Rem_Status1 = convertView.FindViewById<TextView>(Resource.Id.remnant_status1);
try
{
InventorySlabs remnantModel = this.RemnantList[position];
if (remnantModel != null)
{
holder.Remnant1.Text = "#" + remnantModel.ExtSlabNo;
holder.Rem_StockNMaterial1.Text = remnantModel.SellName + "-" + remnantModel.Depth + "-" + remnantModel.Finish;
double sqft = (remnantModel.Width * remnantModel.Height) / 144;
holder.Rem_Dimensions1.Text = "(" + remnantModel.Width.ToString() + " * " + remnantModel.Height.ToString() + ")" + sqft.ToString("N2");
holder.Rem_Status1.Text = remnantModel.Status;
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
context.StartActivityForResult(intent, 1);
}
};
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
convertView.Tag = holder;
}
else
{
holder = (remnantHolder)convertView.Tag;
}
return convertView;
}
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
if (remSlab != null)
{
remnantData.Width = double.Parse(data.GetStringExtra("remWidth"));
remnantData.Height = double.Parse(data.GetStringExtra("remHeight"));
double sqft = (remnantData.Width * remnantData.Height) / 144;
Rem_Dimensions.Text = "(" + remnantData.Width.ToString() + " * " + remnantData.Height.ToString() + ")" + sqft.ToString("N2");
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
}
}
In my Main Activity
I am calling the Result as
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
}
After editing the details in Edit view of the ListItem and close the Popup, I am not knowing how to Pass the Values to the Holder to Update in Listview.
You could pass the positon to the new activity in the click event and pass it back with the result intent.
For example:
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
intent.PutExtra("Position", position );
context.StartActivityForResult(intent, 1);
}
};
And in the new activity:
protected override void OnCreate(Bundle savedInstanceState)
{
Intent intent = Intent;
var position =intent.GetIntExtra("Position", -1);
base.OnCreate(savedInstanceState);
Intent data = new Intent();
String text = "extSlabNo";
data.PutExtra("extSlabNo", text);
data.PutExtra("remWidth", 10);
data.PutExtra("remHeight", 20);
data.PutExtra("Position", position);
SetResult(Result.Ok, data);
}
Then you could modify the data in the adapter according to the positon value:
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
int position = data.GetIntExtra("Position", -1);
if (remSlab != null && position >= 0)
{
RemnantList[position].Width = data.GetIntExtra("remWidth", -1);
RemnantList[position].Height = data.GetIntExtra("remHeight", -1);
NotifyDataSetChanged();
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
And reset the adapter in MainActivity OnActivityResult() method :
public class MainActivity : AppCompatActivity
{
RemnantListAdapter remnantListAdapter;
ListView listView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
List<InventorySlabs> remnantList = new List<InventorySlabs>();
for(var i = 0; i < 10; i++)
{
InventorySlabs inventorySlabs = new InventorySlabs();
inventorySlabs.Depth = i.ToString();
inventorySlabs.ExtSlabNo = i.ToString();
inventorySlabs.Finish = "Finish" + i.ToString();
inventorySlabs.Height = 200;
inventorySlabs.SellName = "SellName" + i.ToString();
inventorySlabs.Status = "Status" + i.ToString();
inventorySlabs.Width = 400;
remnantList.Add(inventorySlabs);
}
listView = FindViewById<ListView>(Resource.Id.listView1);
remnantListAdapter = new RemnantListAdapter(this, remnantList);
listView.Adapter = remnantListAdapter;
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
listView.Adapter = remnantListAdapter;
}
}

how can i make the unity gui window dragable

i am trying to make my window dragable
i'm currently making a multiplayer game and the status to be shown has this window
public bool finishSession = false;
public bool showHelp = false;
private ArrayList messages = new ArrayList();
private string currentTime = "";
private string newMessage = "";
private Vector2 windowScrollPosition;
private SmartFox smartFox;
private GUIStyle windowStyle;
private GUIStyle userEventStyle;
private GUIStyle systemStyle;
public Rect rctWindow;
public float windowPanelPosX;
public float windowPanelPosY;
public float windowPanelWidth;
public float windowPanelHeight;
public StatusWindow() {
smartFox = SmartFoxConnection.Connection;
}
public void AddSystemMessage(string message) {
messages.Add(new StatusMessage(StatusMessage.StatusType.SYSTEM, message));
windowScrollPosition.y = 100000;
}
public void AddStatusMessage(string message) {
messages.Add(new StatusMessage(StatusMessage.StatusType.STATUS, message));
windowScrollPosition.y = 100000;
}
public void AddTimeMessage(string message) {
//messages.Add(new StatusMessage(StatusMessage.StatusType.TIME, message));
//windowScrollPosition.y = 100000;
currentTime = message;
}
public void Draw(float panelPosX, float panelPosY, float panelWidth, float panelHeight) {
windowPanelPosX = panelPosX;
windowPanelPosY = panelPosY;
windowPanelWidth = panelWidth;
windowPanelHeight = panelHeight;
// Status history panel
rctWindow = new Rect(windowPanelPosX, windowPanelPosY, windowPanelWidth, windowPanelHeight);
rctWindow = GUI.Window (1, rctWindow, DoMyWindow, "Interreality Portal Status", GUI.skin.GetStyle("window"));
GUI.DragWindow();
}
void DoMyWindow(int windowID)
{
windowStyle = GUI.skin.GetStyle("windowStyle");
systemStyle = GUI.skin.GetStyle("systemStyle");
userEventStyle = GUI.skin.GetStyle("userEventStyle");
//Cuadro blanco
GUILayout.BeginArea (new Rect (10, 25, windowPanelWidth - 20, windowPanelHeight - 70), GUI.skin.GetStyle ("whiteBox"));
GUILayout.BeginVertical ();
//General information area
if (smartFox != null && smartFox.LastJoinedRoom != null) {
GUILayout.Label ("Current room: " + smartFox.LastJoinedRoom.Name);
//if (currentGameState == GameState.RUNNING ) {
//GUILayout.Label(trisGameInstance.GetGameStatus()); //ACPR
//}
}
GUILayout.Label ("Activity: 1 - Construct");
GUILayout.Label ("Elapsed time: " + currentTime);
//Message area
windowScrollPosition = GUILayout.BeginScrollView (windowScrollPosition);
foreach (StatusMessage message in messages) {
DrawStatusMessage (message);
}
GUILayout.EndScrollView ();
//Cierra cuadro blanco
GUILayout.EndVertical ();
GUILayout.EndArea ();
//Logout area
GUILayout.BeginArea (new Rect (windowPanelWidth / 2, windowPanelHeight - 70 + 30, windowPanelWidth / 2 + 10, 30));//, GUI.skin.GetStyle("whiteBox"));
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Help", GUI.skin.GetStyle ("greenBtn"))) {
showHelp = true;
}
GUILayout.Space (10);
if (GUILayout.Button ("End Session", GUI.skin.GetStyle ("redBtn"))) {
finishSession = true;
}
GUILayout.EndHorizontal ();
GUILayout.EndArea ();
GUI.DragWindow();
}
private void DrawStatusMessage(StatusMessage message) {
GUILayout.BeginHorizontal();
GUILayout.Space(5);
switch (message.GetStatusType()) {
case StatusMessage.StatusType.SYSTEM:
GUILayout.Label(message.GetMessage(), systemStyle);
break;
case StatusMessage.StatusType.STATUS:
GUILayout.Label(message.GetMessage(), windowStyle);
break;
case StatusMessage.StatusType.TIME:
GUILayout.Label(message.GetMessage(), userEventStyle);
break;
default:
// Ignore and dont print anything
break;
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(1);
GUI.DragWindow();
}
class StatusMessage {
public enum StatusType {
IGNORE = 0,
SYSTEM,
STATUS,
TIME,
};
private StatusType type;
private string message;
public StatusMessage() {
type = StatusType.IGNORE;
message = "";
}
public StatusMessage(StatusType type, string message) {
this.type = type;
this.message = message;
}
public StatusType GetStatusType() {
return type;
}
public string GetMessage() {
return message;
}
}
}
but when i'mm trying to drag the window it doesn't drag it
i tried a simpler class with jnothing that works fine but when i call this window it doesn't drag
StatusWindow statusWindow = null;
void Start(){
statusWindow = new StatusWindow();
}
public Rect windowRect = new Rect(20, 20, 120, 50);
void OnGUI() {
windowRect = GUI.Window(0, windowRect, DoMyWindow, "My Window");
statusWindow.Draw (100, 100, 100, 100);
}
void DoMyWindow(int windowID) {
GUI.Button(new Rect(10, 20, 100, 20), "Can't drag me");
GUI.DragWindow();
}
If anyone who knows much about Unity GUI can help that would be great

JOGL: Black panel on windows

I have a class that extends a GLJPanel and has a GLEventListener with
#Override
public void display( GLAutoDrawable glautodrawable ) {
System.out.println("Painting");
if(image!=null){
GL2 gl2 = glautodrawable.getGL().getGL2();
int format = GL.GL_LUMINANCE;
int type = GL.GL_UNSIGNED_SHORT;
DataBufferUShort db = (DataBufferUShort) image.getRaster().getDataBuffer();
short[] shorts = db.getData(0);
Buffer buffer = ShortBuffer.wrap(shorts);
gl2.glDrawPixels(image.getWidth(), image.getHeight(), format , type, buffer );
}
}
On Linux the image is displayed as I expect and the display method is called. On Windows the same code displays a black screen and it doesn't look like it calls the display method. The gears demo runs no problem on the Windows system.
EDIT:
I have narrowed it down to issues with GridBagLayout. Setting the gbc.anchor equal to LINE_START, LINE_END and CENTER is causing the image to appear or not
int bitdepth = 10;
GLProfile.initSingleton();
GLProfile glProfile = GLProfile.getDefault();
GLCapabilities glCapabilities = new GLCapabilities( glProfile );
glCapabilities.setBlueBits(bitdepth);
glCapabilities.setGreenBits(bitdepth);
glCapabilities.setRedBits(bitdepth);
glCapabilities.setAlphaBits(2);
glCapabilities.setDoubleBuffered(true);
glCapabilities.setHardwareAccelerated(true);
glCapabilities.setNumSamples(4);
glCapabilities.setBackgroundOpaque(false);
glCapabilities.setSampleBuffers(true);
GraphicsConfiguration gc = DeviceController.getConfOfRightMostMonitorAndLargest();
JFrame jf = new JFrame(gc);
jf.setExtendedState(JFrame.MAXIMIZED_BOTH);
GLCanvas canvas = new GLCanvas(glCapabilities);
canvas.addGLEventListener(new GLEventListener() {
#Override
public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
int arg4) {
// TODO Auto-generated method stub
}
#Override
public void init(GLAutoDrawable arg0) {
// TODO Auto-generated method stub
}
#Override
public void dispose(GLAutoDrawable arg0) {
// TODO Auto-generated method stub
}
#Override
public void display(GLAutoDrawable drawable) {
System.out.println("Painting");
BufferedImage image = null;
try {
image = ImageIO.read(new File("img.tiff"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(image!=null){
GL2 gl2 = drawable.getGL().getGL2();
//gl2.glClear(GL.GL_COLOR_BUFFER_BIT);
int format = GL.GL_LUMINANCE;
int type = GL.GL_UNSIGNED_SHORT;
DataBufferUShort db = (DataBufferUShort) image.getRaster().getDataBuffer();
short[] shorts = db.getData(0);
Buffer buffer = ShortBuffer.wrap(shorts);
//gl2.glViewport(0, 0, image.getWidth(), image.getHeight());
gl2.glDrawPixels(image.getWidth(), image.getHeight(), format , type, buffer );
}
}
});
JPanel jp = new JPanel();
jp.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.weightx=1;
gbc.weighty=1;
gbc.anchor= GridBagConstraints.CENTER;
jp.add(canvas,gbc);
JScrollPane jsp = new JScrollPane();
jsp.getViewport().add(jp);
JLayeredPane jlp = new JLayeredPane();
jlp.setLayout(new GridBagLayout());
jlp.add(jsp, gbc);
//jsp.getViewport().add(dsc);
gbc = new GridBagConstraints();
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.weightx=1;
gbc.weighty=1;
gbc.fill=GridBagConstraints.NONE;
gbc.anchor= GridBagConstraints.CENTER;
jf.getContentPane().setLayout(new GridBagLayout());
jf.getContentPane().add(jlp,gbc);
jf.setVisible(true);

Resources