How do I draw a pixmap to root window with xcb? - linux

I'm trying to write a window manager with a wallpaper switcher:
void smoke_change_background(smoke_wm_state_t *config, char *desktop) {
struct smoke_desktop_list_element_t *node = smoke_desktop_list_node(config->tree, desktop);
if (node->background != 0) {
xcb_intern_atom_reply_t *xpmap = xcb_intern_atom_reply(config->connection,
xcb_intern_atom(config->connection,
false,
strlen("_X_ROOTPMAP_ID"),
"_X_ROOTPMAP_ID"),
NULL);
xcb_intern_atom_reply_t *esetr = xcb_intern_atom_reply(config->connection,
xcb_intern_atom(config->connection,
false,
strlen("ESETROOT_PMAP_ID"),
"ESETROOT_PMAP_ID"),
NULL);
xcb_get_property_reply_t *xrepl = xcb_get_property_reply(config->connection,
xcb_get_property(config->connection,
0,
config->screen->root,
xpmap->atom,
XCB_ATOM_PIXMAP,
0,
32),
NULL);
uint32_t *xp = (uint32_t*) xcb_get_property_value(xrepl);
xcb_get_property_reply_t *erepl = xcb_get_property_reply(config->connection,
xcb_get_property(config->connection,
0,
config->screen->root,
esetr->atom,
XCB_ATOM_PIXMAP,
0, 32),
NULL);
uint32_t *ep = (uint32_t*) xcb_get_property_value(erepl);
xcb_change_property(config->connection,
XCB_PROP_MODE_REPLACE,
config->screen->root,
xpmap->atom,
XCB_ATOM_PIXMAP,
32, 1,
(void*) &node->background);
xcb_change_property(config->connection,
XCB_PROP_MODE_REPLACE,
config->screen->root,
esetr->atom,
XCB_ATOM_PIXMAP,
32, 1,
(void*) &node->background);
xcb_free_pixmap(config->connection, *xp);
xcb_free_pixmap(config->connection, *ep);
uint32_t values[1];
values[0] = node->background;
xcb_change_window_attributes(config->connection, config->screen->root, XCB_CW_BACK_PIXMAP, values);
xcb_clear_area(config->connection, false, config->screen->root, 0, 0, 0, 0);
xcb_flush(config->connection);
}
}
This code should change the root's pixmap and it should be displayed in my Xephyr window, but it is not. What's wrong?

Related

Printing text and bitmap using MFC

I need to print some text (using font specified), than print a bitmap, using MFC. I can draw text on bitmap, than print this bitmap, using code below - but I need to print text, and than print bitmap in the bottom. The bitmap must be loaded from file.
CFont j1;
j1.CreateFont(
120, // nHeight
120, // nWidth
0, // nEscapement
0, // nOrientation
FW_NORMAL, // nWeight
FALSE, // bItalic
FALSE, // bUnderline
0, // cStrikeOut
RUSSIAN_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
DEFAULT_QUALITY, // nQuality
DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily
"Arial"); // lpszFacename // lpszFacename
int w = 600, h = 400;
CClientDC dc(this);
CBitmap bmp;
CDC memdc;
memdc.CreateCompatibleDC(&dc);
bmp.CreateCompatibleBitmap(&dc, w, h);
if (!bmp.Attach(::LoadImage(
::GetModuleHandle(NULL), "D:\\UPM\\BMP\\Login.bmp", IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE))) {
AfxMessageBox(_T("Error loading bitmap!")); return;
}
BITMAP bm;
bmp.GetBitmap(&bm);
auto oldbmp = memdc.SelectObject(bmp);
CFont* pOldFont = memdc.SelectObject(&j1);
//draw on bitmap
///memdc.FillSolidRect(0, 0, w, h, RGB(200, 200, 200));
memdc.SetTextColor(RGB(255, 0, 0));
CRect rc(0, 0, w, h);
memdc.DrawText("qwerty\nrtrtrt\nttttt", &rc, DT_WORDBREAK | DT_EXPANDTABS | DT_CENTER);
///pDC->DrawText(dpu, strRect, DT_WORDBREAK | DT_EXPANDTABS | DT_CENTER);
//dc.BitBlt(0, 0, w, h, &memdc, 0, 0, SRCCOPY);//optional: draw the bitmap on dialog
CPrintDialog pd(false);
if (pd.DoModal() == IDOK)
{
CDC PrintDC;
HDC hdc = pd.GetPrinterDC();
PrintDC.Attach(hdc);
DOCINFO docinfo = { sizeof(docinfo) };
docinfo.lpszDocName = "Print test";
PrintDC.StartDoc(&docinfo);
PrintDC.StartPage();
PrintDC.BitBlt(0, 0, w, h, &memdc, 0, 0, SRCCOPY);
PrintDC.EndPage();
PrintDC.EndDoc();
}
dc.SelectObject(oldbmp);
CClientDC dc(this);
dc.DrawText(...);
...
PrintDC.BitBlt(0, 0, w, h, &memdc, 0, 0, SRCCOPY);
You are drawing text on display's "client DC", then drawing a bitmap on a "printer DC".
Use instead a paint function for everything, and a paint_bitmap function to make things easier.
void paint_bitmap(CDC& dc, CBitmap &bmp, CRect rc)
{
CDC memdc;
memdc.CreateCompatibleDC(&dc);
auto oldbmp = memdc.SelectObject(&bmp);
dc.BitBlt(rc.left, rc.top, rc.Width(), rc.Height(), &memdc, 0, 0, SRCCOPY);
memdc.SelectObject(oldbmp);
}
void paint(CDC& dc)
{
CBitmap bmp;
if (!bmp.Attach(...))...
dc.DrawText(L"text", &rc, ...);
rc.OffsetRect(0, 200);
paint_bitmap(dc, bmp, rc);
}
...
CPrintDialog pd(false);
if (pd.DoModal() == IDOK)
{
HDC hdc = pd.GetPrinterDC();
if (hdc)
{
...
dc.StartPage();
paint(dc); //<- use this for printer or display
dc.EndPage();
}
To print directly to default printer:
CPrintDialog pd(false);
if (pd.GetDefaults() && pd.m_pd.hDC)
{
CDC dc;
dc.Attach(pd.m_pd.hDC);
DOCINFO docinfo = { sizeof(docinfo) };
docinfo.lpszDocName = L"Print test";
dc.StartDoc(&docinfo);
dc.StartPage();
paint(dc);
dc.EndPage();
dc.EndDoc();
}
else
{
MessageBox(L"no default printer...");
}
or if you want a particular printer which you are sure is there, use
HDC hdc = CreateDC(L"WINSPOOL", L"Microsoft Print to PDF", NULL, NULL);
if (hdc)
{
CDC dc;
dc.Attach(hdc);
...
//DeleteDC(hdc); CDC will take care of delete
}

Mismatch between print preview and real print output

I want to print a bitmap. To avoid printing small bitmap I set CScrollView mode as MM_LOMETRIC with sizes 3830 x 1995. I have created the bitmap and made the bitblt to the screen. There were everythig just like I want on the screen and on the print preview but when I printed the document I've got very bad result.
The same picture on print preview.
It seems to me that printer does not see a bitmap the same way as print preview does.
Pay attantion that the first ractangle puts directly on the DC and memDC puts into it.
Are there any ideas how to fix this mismatch between print previw and the real printing?
Project files
void OnDraw()
{
CPen pen;
pen.CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
CPen* OldPen = pDC->SelectObject(&pen);
CRect rcView;
GetClientRect(rcView);
int iClientWidth = rcView.right;
int iClientHeight = rcView.bottom;
int iMemWidth = 1900;
int iMemHeight = 950;
CDC memDC;
CBitmap memBitmap;
memDC.CreateCompatibleDC(pDC);
memBitmap.CreateCompatibleBitmap(pDC, iMemWidth, iMemHeight);
memDC.SelectObject(&memBitmap);
memDC.SetMapMode(MM_LOMETRIC);
CPen pen1;
pen1.CreatePen(PS_SOLID, 3, RGB(0, 0, 0));
memDC.SelectObject(&pen1);
CBrush brBK;
brBK.CreateSolidBrush(RGB(255, 255, 255));
memDC.SelectObject(&brBK);
RECT rc;
rc.left = 0;
rc.top = 0;
rc.right = iMemWidth;
rc.bottom = iMemHeight;
memDC.FillRect(&rc, &brBK);
memDC.Rectangle(rc.left, rc.top, rc.right, -rc.bottom);
memDC.MoveTo(0, 0);
memDC.LineTo(1900, -950);
memDC.MoveTo(0, -950);
memDC.LineTo(200, -750);
CFont font;
font.CreateFont(
50, // nHeight
0, // nWidth
0, // nEscapement
0, // nOrientation
FW_NORMAL, // nWeight
FALSE, // bItalic
FALSE, // bUnderline
0, // cStrikeOut
ANSI_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
DEFAULT_QUALITY, // nQuality
DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily
_T("Arial"));
memDC.SelectObject(&font);
memDC.TextOut(100, -100, _T("Hello"));
pDC->BitBlt(10, -10, iMemWidth, -iMemHeight, &memDC, 0, 0, SRCCOPY);
font.DeleteObject();
brBK.DeleteObject();
memDC.DeleteDC();
memBitmap.DeleteObject();
pen.DeleteObject();
pen1.DeleteObject();
}
void OnInitialUpdate()
{
CScrollView::OnInitialUpdate();
CSize sizeTotal;
sizeTotal.cx = 3830;
sizeTotal.cy = 1995;
SetScrollSizes(MM_LOMETRIC, sizeTotal);
}

Processing: How do I make a triggered sound stop?

When the picture of the woman moves over one of the moving hexagons, a few things happen. I have a sound(police) that is triggered when she touches one of them. The problem is that the sound continues even when she is not on the hexagon even longer. Plus, if she touches the hexagon again the sound is triggered again over the first sound. So now I have a mess of the same sound playing over each other.
I want her to move over a hexagon, the sound is triggered. When she moves off the hexagon the sound instantly stops until she moves over it again.
Here's the code:
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.effects.*;
import ddf.minim.signals.*;
import ddf.minim.spi.*;
import ddf.minim.ugens.*;
Minim minim;
AudioSample police;
color underhex = color(255, 0, 0);
PImage woman;
float headX = 50, headY = 50;
float ss = 0;
float fade=30, fade2=9;
PShape hexagon, trapezoid, trapezoid2;
float[] hspeed = {2.4, 2.8, 3.2, 3.6, 4, 4.4, 4.8};
float[] g = {0, 0, 0, 0, 0, 0, 0};
void setup() {
size(900, 600, P3D);
background(250);
noStroke();
minim = new Minim(this);
police = minim.loadSample("PoliceSiren.mp3", 1024);
hexagon = createShape(GROUP);
PShape trapezoid = createShape(QUAD, 100, 50, 325, 50, 375, 180, 50, 180);
PShape trapezoid2 = createShape(QUAD, 50, 180, 375, 180, 325, 320, 100, 320);
hexagon.scale(0.25);
hexagon.addChild(trapezoid);
hexagon.addChild(trapezoid2);
hexagon.setFill(color(255, 0, 0, 50));
woman = loadImage("woman.png");
}
void draw() {
background(250);
image(woman, headX, headY, 70, 81);
for (int p = 0; p < 5; p++) {
pushMatrix();
translate(g[p], 120*p);
underhex = get(int(g[p])+30, int(120*p)+30);
shape(hexagon, 0, 0);
//ellipse(width/2,height/2,50,50);
popMatrix();
g[p]+=hspeed[p];
if (int(g[p]) > 830 || int(g[p]) < 0) {
hspeed[p] *= -1;
}
if (red(underhex) < 20 && green(underhex) < 20 && blue(underhex) < 20) {
println("she's here"+random(5));
fill(0, 240);
rect(0, 0, 900, 600);
strokeWeight(30);
fill(0, 0, 255, fade);
stroke(0, 0, 255, fade);
ellipse(250, 200, 100, 100);
fill(255, 0, 0, fade);
stroke(255, 0, 0, fade);
ellipse(290, 330, 100, 100);
fill(0, 0, 255, fade);
stroke(0, 0, 255, fade);
ellipse(680, 200, 100, 100);
fill(255, 0, 0, fade);
stroke(255, 0, 0, fade);
ellipse(640, 330, 100, 100);
noStroke();
police.trigger();
fade += fade2;
if (fade<0 || fade>255) {
fade2 *= -1;
}
}
}
if (keyPressed) {
if (keyCode == UP) {
headY-=random(2, 6);
} else if (keyCode == DOWN) {
headY+=random(2, 6);
} else if (keyCode == LEFT) {
headX-=random(2, 6);
} else if (keyCode == RIGHT) {
headX+=random(2, 6);
}
}
}
Try using AudioPlayer instead of AudioSample. It provides isPlaying() which is handy to check if the sound is already playing or not.
e.g.
//at the top
AudioPlayer police;
//in setup()
police = minim.loadFile("PoliceSiren.mp3");
//in draw() instead of police.trigger()
if(!police.isPlaying() || ){
police.play();
}
Update
It sounds like looping is what you're after:
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.effects.*;
import ddf.minim.signals.*;
import ddf.minim.spi.*;
import ddf.minim.ugens.*;
Minim minim;
AudioPlayer police;
color underhex = color(255, 0, 0);
PImage woman;
float headX = 50, headY = 50;
float ss = 0;
float fade=30, fade2=9;
PShape hexagon, trapezoid, trapezoid2;
float[] hspeed = {2.4, 2.8, 3.2, 3.6, 4, 4.4, 4.8};
float[] g = {0, 0, 0, 0, 0, 0, 0};
void setup() {
size(900, 600, P3D);
background(250);
noStroke();
minim = new Minim(this);
//police = minim.loadSample("PoliceSiren.mp3", 1024);
police = minim.loadFile("PoliceSiren.mp3");
hexagon = createShape(GROUP);
PShape trapezoid = createShape(QUAD, 100, 50, 325, 50, 375, 180, 50, 180);
PShape trapezoid2 = createShape(QUAD, 50, 180, 375, 180, 325, 320, 100, 320);
hexagon.scale(0.25);
hexagon.addChild(trapezoid);
hexagon.addChild(trapezoid2);
hexagon.setFill(color(255, 0, 0, 50));
woman = loadImage("woman.png");
}
void draw() {
background(250);
image(woman, headX, headY, 70, 81);
for (int p = 0; p < 5; p++) {
pushMatrix();
translate(g[p], 120*p);
underhex = get(int(g[p])+30, int(120*p)+30);
shape(hexagon, 0, 0);
//ellipse(width/2,height/2,50,50);
popMatrix();
g[p]+=hspeed[p];
if (int(g[p]) > 830 || int(g[p]) < 0) {
hspeed[p] *= -1;
}
if (red(underhex) < 20 && green(underhex) < 20 && blue(underhex) < 20) {
println("she's here"+random(5));
fill(0, 240);
rect(0, 0, 900, 600);
strokeWeight(30);
fill(0, 0, 255, fade);
stroke(0, 0, 255, fade);
ellipse(250, 200, 100, 100);
fill(255, 0, 0, fade);
stroke(255, 0, 0, fade);
ellipse(290, 330, 100, 100);
fill(0, 0, 255, fade);
stroke(0, 0, 255, fade);
ellipse(680, 200, 100, 100);
fill(255, 0, 0, fade);
stroke(255, 0, 0, fade);
ellipse(640, 330, 100, 100);
noStroke();
if(!police.isPlaying()){
police.loop();
}
fade += fade2;
if (fade<0 || fade>255) {
fade2 *= -1;
}
}else{
if(police.isLooping()){
police.pause();
}
}
}
if (keyPressed) {
if (keyCode == UP) {
headY-=random(2, 6);
} else if (keyCode == DOWN) {
headY+=random(2, 6);
} else if (keyCode == LEFT) {
headX-=random(2, 6);
} else if (keyCode == RIGHT) {
headX+=random(2, 6);
}
}
}
Also checkout mute(),unmute(),isMuted(): perhaps you can keep the sound looping but muted and only unmute when the collision happens

How do I stop sound chopping in Processing while using Minim?

I have been working on the piece of code below in Processing using the sound library Minim, and have been trying to stop the audio recorded into the program from chopping the sound, rendering it somewhat unaudible.
Setup():
import ddf.minim.spi.*;
import ddf.minim.signals.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.ugens.*;
import ddf.minim.effects.*;
Minim sound;
AudioOutput speak;
AudioInput mic;
Sampler samp;
MultiChannelBuffer bigBuf;
AudioPlayer loadAudio;
slider frequency, amplitude;
button mute, record, play, stop;
trigger freqBut, ampBut, load;
float[] mainLeft = new float[1024];
float[] mainRight = new float[1024];
float amp = 1;
boolean muted = false, recording = false, playInit = false;
int sampleCount = 0;
int tempCount = 0;
int tempFreq = 0;
boolean tempUnder = false;
int tempTimeNew = 0;
int tempTimeOld = 0;
void setup() {
size(512, 300);
// UI
frequency = new slider(10, 60, 300, 20, 0, 30, true, color(120), color(180), color(255), color(80, 0, 0));
amplitude = new slider(10, 90, 300, 20, 0, 20, false, color(120), color(180), color(255), color(0, 0, 80));
mute = new button(10, 10, 40, 40, color(120), color(180), color(255));
record = new button(60, 10, 40, 40, color(120), color(180), color(255));
play = new button(110, 10, 40, 40, color(120), color(180), color(255));
stop = new button(160, 10, 40, 40, color(120), color(180), color(255));
load = new trigger(210, 10, 40, 40, color(120), color(210), color(180), color(255));
freqBut = new trigger(320, 60, 20, 20, color(40, 0, 0), color(220, 0, 0), color(180, 0, 0), color(255));
ampBut = new trigger(320, 90, 20, 20, color(0, 0, 40), color(0, 0, 220), color(0, 0, 180), color(255));
// Minim
sound = new Minim(this);
mic = sound.getLineIn();
speak = sound.getLineOut(sound.STEREO, mic.bufferSize(), mic.sampleRate());
loadAudio = sound.loadFile("sound.mp3");
loadAudio.loop();
loadAudio.mute();
bigBuf = new MultiChannelBuffer(mic.bufferSize(), 2);
samp = new Sampler(bigBuf, mic.sampleRate(), 2);
samp.patch(speak);
}
And draw():
void draw() {
float[] micLeft;
float[] micRight;
micLeft = mic.left.toArray();
micRight = mic.right.toArray();
if (record.state == true) {
recording = !recording;
}
if (recording == true) {
int temp = mainLeft.length - 1;
mainLeft = expand(mainLeft, temp + micLeft.length);
mainRight = expand(mainRight, temp + micRight.length);
sampleCount++;
for (int i = 0; i < micLeft.length - 1; i++) {
mainLeft[i + temp] = micLeft[i];
mainRight[i + temp] = micRight[i];
}
}
// Play
if (play.state == true) {
playInit = true;
}
if (playInit == true) {
println("playing");
if (tempTimeOld > tempTimeNew) {
tempUnder = true;
}
tempTimeOld = tempTimeNew;
tempTimeNew = millis() % micLeft.length;
println(millis() % (micLeft.length));
if (tempUnder == true) {
if (tempCount == sampleCount) {
playInit = false;
tempCount = 0;
}
else {
// Amplitude
if (ampBut.state == true) {
amp = map(amplitude.value, amplitude.minVal, amplitude.maxVal, 0.05, 20);
}
else {
amp = 1;
}
if (freqBut.state == true) {
float newFreq = map(frequency.value, frequency.minVal, frequency.maxVal, 140, 940);
tempFreq = 0;
for (int i = 0; i < micLeft.length - 2; i++) {
if (micLeft[i] < micLeft[i + 1]) {
tempFreq ++;
}
}
for (int i = 0; i < micLeft.length - 1; i++) {
bigBuf.setSample(0, i, mainLeft[int(i * newFreq / tempFreq) + (tempCount * micLeft.length)] * amp);
bigBuf.setSample(1, i, mainRight[int(i * newFreq / tempFreq) + (tempCount * micRight.length)] * amp);
}
}
else {
for (int i = 0; i < micLeft.length - 1; i++) {
bigBuf.setSample(0, i, mainLeft[i + (tempCount * micLeft.length)] * amp);
bigBuf.setSample(1, i, mainRight[i + (tempCount * micRight.length)] * amp);
}
}
samp.trigger();
tempCount++;
}
}
}
}
Any advise on solving this problem would be a really big help.
And sorry if it have not been asking to right way, it is my first question, and the guide confused me a little.

Periodically refresh data

I want to display data periodically but I get error when I try to display the data.
Timeline fiveSecondsWonder = new Timeline(new KeyFrame(Duration.seconds(3), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
GridPane gp = new GridPane();
gp.setPadding(new Insets(10, 10, 10, 10));
gp.setHgap(20);
gp.setVgap(10);
//gp.setGridLinesVisible(true);
gp.add(new Label("Operating System Name"), 0, 0);
gp.add(new Label(System.getProperty("os.name")), 1, 0);
gp.add(new Label("Operating System Version"), 0, 1);
gp.add(new Label(System.getProperty("os.version")), 1, 1);
gp.add(new Label("System Architecture"), 0, 2);
gp.add(new Label(System.getProperty("os.arch")), 1, 2);
gp.add(new Label("Total Memory"), 0, 3);
String memStrLong = Long.toString(Runtime.getRuntime().totalMemory());
gp.add(new Label(memStrLong), 1, 3);
gp.add(new Label("Used Memory"), 0, 4);
String fStrLong = Long.toString(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
gp.add(new Label(fStrLong), 1, 4);
gp.add(new Label("Java Version"), 0, 5);
gp.add(new Label(System.getProperty("java.version")), 1, 5);
gp.add(new Label("Number of Processors"), 0, 6);
String pStrLong = Long.toString(Runtime.getRuntime().availableProcessors());
gp.add(new Label(pStrLong), 1, 6);
gp.add(new Label("Maximum available Memory"), 0, 7);
String amStrLong = Long.toString(Runtime.getRuntime().maxMemory());
gp.add(new Label(amStrLong), 1, 7);
}
}));
fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);
fiveSecondsWonder.play();
Vbox.getChildren().add(gp);
Can you help me to implement properly this example, please?
EDIT: Second test:
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
#Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
final GridPane gp = new GridPane();
#Override
public void run() {
gp.getChildren().clear();
gp.setPadding(new Insets(10, 10, 10, 10));
gp.setHgap(20);
gp.setVgap(10);
//gp.setGridLinesVisible(true);
gp.add(new Label("Operating System Name"), 0, 0);
gp.add(new Label(System.getProperty("os.name")), 1, 0);
gp.add(new Label("Operating System Version"), 0, 1);
gp.add(new Label(System.getProperty("os.version")), 1, 1);
gp.add(new Label("System Architecture"), 0, 2);
gp.add(new Label(System.getProperty("os.arch")), 1, 2);
gp.add(new Label("Total Memory"), 0, 3);
String memStrLong = Long.toString(Runtime.getRuntime().totalMemory());
gp.add(new Label(memStrLong), 1, 3);
gp.add(new Label("Used Memory"), 0, 4);
String fStrLong = Long.toString(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
gp.add(new Label(fStrLong), 1, 4);
gp.add(new Label("Java Version"), 0, 5);
gp.add(new Label(System.getProperty("java.version")), 1, 5);
gp.add(new Label("Number of Processors"), 0, 6);
String pStrLong = Long.toString(Runtime.getRuntime().availableProcessors());
gp.add(new Label(pStrLong), 1, 6);
gp.add(new Label("Maximum available Memory"), 0, 7);
String amStrLong = Long.toString(Runtime.getRuntime().maxMemory());
gp.add(new Label(amStrLong), 1, 7);
vb.getChildren().add(gp);
}
}, 0, 1, TimeUnit.SECONDS);
I also tested this but with the data is not updated.
public class Sandbox extends Application {
private final StringProperty totalMemoryProperty = new SimpleStringProperty();
private final StringProperty usedMemoryProperty = new SimpleStringProperty();
private final StringProperty maxMemoryProperty = new SimpleStringProperty();
public static void main(final String[] args) throws Exception {
launch(args);
}
#Override
public void start(final Stage stage) throws Exception {
final GridPane gp = new GridPane();
gp.setPadding(new Insets(10, 10, 10, 10));
gp.setHgap(20);
gp.setVgap(10);
gp.add(new Label("Operating System Name"), 0, 0);
gp.add(new Label(System.getProperty("os.name")), 1, 0);
gp.add(new Label("Operating System Version"), 0, 1);
gp.add(new Label(System.getProperty("os.version")), 1, 1);
gp.add(new Label("System Architecture"), 0, 2);
gp.add(new Label(System.getProperty("os.arch")), 1, 2);
gp.add(new Label("Java Version"), 0, 5);
gp.add(new Label(System.getProperty("java.version")), 1, 5);
gp.add(new Label("Number of Processors"), 0, 6);
String pStrLong = Long.toString(Runtime.getRuntime().availableProcessors());
gp.add(new Label(pStrLong), 1, 6);
gp.add(new Label("Total Memory"), 0, 3);
gp.add(new Label("Used Memory"), 0, 4);
gp.add(new Label("Maximum available Memory"), 0, 7);
final Label totalMemoryLabel = new Label();
totalMemoryLabel.textProperty().bind(totalMemoryProperty);
gp.add(totalMemoryLabel, 1, 3);
final Label usedMemoryLabel = new Label();
usedMemoryLabel.textProperty().bind(usedMemoryProperty);
gp.add(usedMemoryLabel, 1, 4);
final Label maxMemoryLabel = new Label();
maxMemoryLabel.textProperty().bind(maxMemoryProperty);
gp.add(maxMemoryLabel, 1, 7);
final VBox rootNode = new VBox();
rootNode.getChildren().add(gp);
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
#Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
final Runnable runnable = new Runnable() {
#Override
public void run() {
String memStrLong = Long.toString(Runtime.getRuntime().totalMemory());
totalMemoryProperty.setValue(memStrLong);
String fStrLong = Long.toString(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
usedMemoryProperty.setValue(fStrLong);
String amStrLong = Long.toString(Runtime.getRuntime().maxMemory());
maxMemoryProperty.setValue(amStrLong);
}
};
Platform.runLater(runnable);
}
}, 0, 1, TimeUnit.SECONDS);
final Scene scene = new Scene(rootNode, 1024, 768);
stage.setScene(scene);
stage.show();
}
}
I made your code work with databinding, use Platform.runLater() to go back to the GUI thread to update javafx components.
If you want to use ScheduledService here is a basic example:
public class Sandbox extends Application {
public static void main(final String[] args) throws Exception {
launch(args);
}
class MyService extends ScheduledService<List<String>> {
#Override
protected Task<List<String>> createTask() {
final Task<List<String>> voidTask = new Task<List<String>>() {
#Override
protected List<String> call() throws Exception {
List<String> results = new ArrayList<>();
final String memStrLong = Long.toString(Runtime.getRuntime().totalMemory());
results.add(memStrLong);
final String fStrLong = Long.toString(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
results.add(fStrLong);
final String amStrLong = Long.toString(Runtime.getRuntime().maxMemory());
results.add(amStrLong);
return results;
}
};
return voidTask;
}
}
#Override
public void start(final Stage stage) throws Exception {
final GridPane gp = new GridPane();
gp.setPadding(new Insets(10, 10, 10, 10));
gp.setHgap(20);
gp.setVgap(10);
gp.add(new Label("Operating System Name"), 0, 0);
gp.add(new Label(System.getProperty("os.name")), 1, 0);
gp.add(new Label("Operating System Version"), 0, 1);
gp.add(new Label(System.getProperty("os.version")), 1, 1);
gp.add(new Label("System Architecture"), 0, 2);
gp.add(new Label(System.getProperty("os.arch")), 1, 2);
gp.add(new Label("Java Version"), 0, 5);
gp.add(new Label(System.getProperty("java.version")), 1, 5);
gp.add(new Label("Number of Processors"), 0, 6);
final String pStrLong = Long.toString(Runtime.getRuntime().availableProcessors());
gp.add(new Label(pStrLong), 1, 6);
gp.add(new Label("Total Memory"), 0, 3);
gp.add(new Label("Used Memory"), 0, 4);
gp.add(new Label("Maximum available Memory"), 0, 7);
final Label totalMemoryLabel = new Label();
gp.add(totalMemoryLabel, 1, 3);
final Label usedMemoryLabel = new Label();
gp.add(usedMemoryLabel, 1, 4);
final Label maxMemoryLabel = new Label();
gp.add(maxMemoryLabel, 1, 7);
final VBox rootNode = new VBox();
rootNode.getChildren().add(gp);
final MyService service = new MyService();
service.setDelay(new Duration(300));
service.setPeriod(new Duration(1000));
service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(final WorkerStateEvent workerStateEvent) {
List<String> results = (List<String>) workerStateEvent.getSource().getValue();
totalMemoryLabel.setText(results.get(0));
usedMemoryLabel.setText(results.get(1));
maxMemoryLabel.setText(results.get(2));
}
});
service.start();
final Scene scene = new Scene(rootNode, 1024, 768);
stage.setScene(scene);
stage.show();
}
}

Resources