Local Notification NOT SHOWING CodeNameOne - java

I'm a CodeNameOne beginner. I'm trying to make a local notification, it doesn't seem to work,I don't get anything displayed. here's the start function.
Is there anything missing? Should I add variables in the build settings?
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hi World"));
hi.show();
LocalNotification n = new LocalNotification();
n.setId("demo-notification");
n.setAlertBody("It's time to take a break and look at me");
n.setAlertTitle("Break Time!");
//n.setAlertSound("/notification_sound_beep-01a.mp3");
// alert sound file name must begin with notification_sound
Display.getInstance().scheduleLocalNotification(
n,
System.currentTimeMillis() + 10 * 1000, // fire date/time
LocalNotification.REPEAT_MINUTE // Whether to repeat and what frequency
);
}

Related

In Java, one of my alert boxes is showing twice and the nested alert box is not showing at all

I am working on a school project where I am working with a mySQL database. The specific part I'm working on right now is what happens when a user of the system attempts to delete an appointment from the database. I have three alerts, one works, one is presenting twice, and the other isn't working at all. The first loop, the one that verifies a choice is selected does work. The second one that confirms if the user wants to delete runs twice, i.e. when you click the OK button it shows again and you must click again. Then, it seems to skip to the bottom where I reload the page. When it reloads the page I can see that the appointment was successfully deleted and it also shows as deleted in the mysql work bench. So it's only the middle alert that doesn't seem to run at all. I have scoured the internet to find out why one is showing twice and the other not at all and although I have found similar questions and problems I tried using their solutions and I did not see any difference. I appreciate any help in the right direction be it code correction or resources! Thank you very much in advance.
// delete selected appointment
#FXML
void handleDelete(MouseEvent event) throws IOException, SQLException {
Appointment ifSelected = appointmentTable.getSelectionModel().getSelectedItem();
if (ifSelected == null){
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Deletion Error");
alert.setHeaderText("You didn't choose an appointment to delete.");
alert.setContentText("Please click ok in order to choose an appointment for deletion.");
alert.showAndWait();
}
else{
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Appointment Deletion");
alert.setHeaderText("You are about to delete an appointment record permanantly.");
alert.setContentText("If you want to proceed, click ok.");
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && result.get() == ButtonType.OK){
Alert alert2 = new Alert(Alert.AlertType.INFORMATION);
alert2.setTitle("Deletion Successful");
alert2.setHeaderText("You successfully deleted the appointment with " + ifSelected.getCustomerName()+ " at " + ifSelected.getStartTime() + ".");
alert.setContentText("If you want to proceed, click ok.");
alert.show();
Statement stmt = conn.createStatement();
apptID = ifSelected.getAppointmentID();
String sqlDeleteAppointment = "DELETE FROM appointment WHERE appointmentId = " + apptID;
Query.makeQuery(sqlDeleteAppointment);
Parent root = FXMLLoader.load(getClass().getResource("appointmentScreen.fxml"));
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}}
'''
You have created alert2 object from Alert class for your nested Alerts. But you have used alert object instead of alert2.
Alert alert2 = new Alert(Alert.AlertType.INFORMATION);
alert2.setTitle("Deletion Successful");
alert2.setHeaderText("You successfully deleted the appointment with " + ifSelected.getCustomerName()+ " at " + ifSelected.getStartTime() + ".");
alert2.setContentText("If you want to proceed, click ok.");
alert2.show();

JavaFx conversion and printing

Ok. I am attempting to make a simple little text editor for java practice. I have a TextArea in JavaFX 8 that I type text into. I would like to be able to create and fill a Text object and then send that text object to the printer. So far, I have failed miserably. The printer just spits out a blank sheet of paper. It's acting as if there is no content to be printed.
I found an example where the text object is wrapped in java's TextFlow like this..
TextFlow printArea = new TextFlow(new Text(textDocument.getText()));
that at least prints SOMETHING, but it's only the first line of text entered.
Here is my print code:
static void printOperation(TextArea textDocument) {
Text extractedText = new Text(textDocument.getText());
PrinterJob printerJob = PrinterJob.createPrinterJob();
if (printerJob != null && printerJob.showPageSetupDialog(textDocument.getScene().getWindow())
&& printerJob.showPrintDialog(textDocument.getScene().getWindow())) {
if (printerJob.printPage(extractedText)) {
printerJob.endJob();
} else {
System.out.println("Failed to print");
}
} else {
System.out.println("Canceled");
}
}
//There is a print menu option that calls the print method
print.setOnAction((ActionEvent e) -> {
printOperation(textDocument);
});
Text by seems to have it's origin at the bottom left corner of the node not at the top left one. The text simply is not inside the printed area.
The second attempt probably fails to achieve the desired output, since you do not set any limit for the width.
You could ensure the node is on screen by using a StackPane as parent of the text. Furthermore I recommend setting the wrappingWidth property:
static void printOperation(TextArea textDocument) {
Text extractedText = new Text(textDocument.getText());
extractedText.setWrappingWidth(450);
// use pane to place the text
StackPane container = new StackPane(extractedText);
container.setAlignment(Pos.TOP_LEFT);
PrinterJob printerJob = PrinterJob.createPrinterJob();
if (printerJob != null && printerJob.showPageSetupDialog(textDocument.getScene().getWindow())
&& printerJob.showPrintDialog(textDocument.getScene().getWindow())) {
if (printerJob.printPage(container)) {
printerJob.endJob();
} else {
System.out.println("Failed to print");
}
} else {
System.out.println("Canceled");
}
}
You should probably set the wrappingWidth according to the page size/margin chosen by the user instead of hardcoding the value though...

Load multiple bitmaps in Android Studio one at time with threads

I'm currently working on a project which takes pictures from camera and saves the photoPath in a Database, this is working fine and actually I'm handling the memory correctly generating thumbnails when I load all images.
The thing I want is that I'm trying to dedicate threads to go loading images one per one in the layout, because for example, if I have 50, with normal load it shows the layout until all 50 are loaded, meanwhile it doesn't show anything.
I've already tried to implement this threads to load one, and then another one, but it's the same, until it loads all, it shows all, here my code:
String query = "Select id_reg_mem, information from Memory_REG where type = 'PHOTO' and id_memory =" + id_memory;
final Cursor resultado = memoryDB.rawQuery(query, null);
if(resultado.moveToFirst())
noPhotos = resultado.getCount();
for(int i=0; i<noPhotos; i++)
{
new Thread()
{
public void run()
{
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
updateNewPhoto(resultado.getString(1)); // I send the path from the DB to a method I made to add a tablerow with the image (inside an imageview)
}
});
}
}.start();
if(i + 1 == noPhotos)
break;
resultado.moveToNext();
}
Here this method, where I'm loading a single image to an ImageView inside a TableRow. This method is actually working to load all images from DB.
protected void updateNewPhoto(String path)
{
ImageView iv;
if(rows == null) {
rows = new ArrayList<TableRow>();
rows.add(new TableRow(TL.getContext()));
iv = new ImageView(TL.getContext());
iv.setLayoutParams(new TableRow.LayoutParams(250,250));
iv.setTag(DB_Utils.maxIDRegMem(memoryDB) - 1);
iv.setImageBitmap(getBitmapThumbnail(path));
rows.get(0).addView(iv);
TL.addView(rows.get(0));
count = 2;
}
else
{
iv = new ImageView(TL.getContext());
iv.setLayoutParams(new TableRow.LayoutParams(250,250));
iv.setTag(DB_Utils.maxIDRegMem(memoryDB) - 1);
iv.setImageBitmap(getBitmapThumbnail(path));
if(count == 2)
{
rows.get(rows.size() - 1).addView(iv);
count = 1;
}
else
{
rows.add(new TableRow(TL.getContext()));
rows.get(rows.size() - 1).addView(iv);
TL.addView(rows.get(rows.size() - 1));
count = 2;
}
}
Unfortunately for me, all images aren't shown until all of them are loaded (kind of 3 seconds it takes). I'm thinking in no limit of images, that's why I want a way where images be loaded one per one, not all together.
Any ideas you have? I appreciate your help.
Thanks.

How to get text from JTextField? [duplicate]

This question already has answers here:
Retrieving JTextField Contents Like Scanner
(2 answers)
Closed 8 years ago.
I'm trying to understand the Scanner function, but I can't seem to understand it.
I'm making a program to calculate the BMI (body mass index) and it's practically done, except that I can't make the calculation! Everything works fine except for when I click the "ok" button.
Had to take away my code so my collegues won't copy my code, like they've made in the past, will be posting again after friday.
first thing there is no poblem with Scanner things and its not required when we use GUI.
its useful only for console input/output.
so when you get text it will be in string format so parse it to double like
String val = txt1.getText();
double valueDouble = Double.parseDouble(val);
and handle the parse exception using try/catch
so replace the piece of code below
Scanner dado1 = new Scanner(txt1.getText());
System.out.println(dado1);
if(dado1.hasNextDouble()){
tamanho = dado1.nextDouble();
}
Scanner dado2 = new Scanner(txt2.getText());
if(dado2.hasNextDouble()){
peso = dado2.nextDouble();
}
to
String t1 = txt1.getText();
if(!"".equals(t1))
tamanho = Double.parseDouble(t1);
String t2 = txt2.getText();
if(!"".equals(t2))
peso = Double.parseDouble(t2);
i tried to run your program but i got the exception saying -> container does not have parent attribute.
so what i did is i have added a parent container inside your ok button action listener
and it works well.
container to be added is
final JDesktopPane desk = new JDesktopPane();
setContentPane(desk);
to your
JOptionPane.showInternalMessageDialog(desk,"Seu IMC é:"+ (result/ peso));
but you have passed null as the first argement.
so it should become like below
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
String t1 = txt1.getText();
if(!"".equals(t1))
tamanho = Double.parseDouble(t1);
String t2 = txt2.getText();
if(!"".equals(t2))
peso = Double.parseDouble(t2);
result = tamanho*tamanho;
if (ok != null){
System.out.println(result);
System.out.println(peso);
final JDesktopPane desk = new JDesktopPane();
setContentPane(desk);
JOptionPane.showInternalMessageDialog(desk,"Seu IMC é:"+ (result/ peso));
}
}
});
you may simply parse instead of Scanner:
tamanho = Double.parseDouble(txt1.getText());

Java screen resolution change

I am following a series of tutorials on game development in Java by thenewboston on Youtube. I am at the point where I can make a fullscreen window, but the resolution refuses to resize to 800x600. I have tested vc, a GraphicsEnvironment.getDefaultScreenDevice object, and dm, a DisplayMode, and they don't seem to be the problem. I am running Snow Leopard. Any ideas?
if(dm != null && vc.isDisplayChangeSupported()){
try{
vc.setDisplayMode(dm);
System.out.println("Display mode set");
}catch(Exception ex){System.out.println("Despite the vc saying it is display change supported and the DM is not null, something went wrong");}
}
}
Add this code to your Core.java (or GameClient.java) class. The issue may be that you are not passing the required DM[] args to your ScreenManager.java class.
private static final DisplayMode modes[] = { //common monitor DMs
new DisplayMode(1366,768,32, DisplayMode.REFRESH_RATE_UNKNOWN), //1366x768px w/32-bit depth
new DisplayMode(1366,768,24, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/24-bit depth
new DisplayMode(1366,768,16, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/16-bit depth
new DisplayMode(800,600,32, DisplayMode.REFRESH_RATE_UNKNOWN), //800x600px w/32-bit depth
new DisplayMode(800,600,24, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/24-bit depth
new DisplayMode(800,600,16, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/16-bit depth
new DisplayMode(640,480,32, DisplayMode.REFRESH_RATE_UNKNOWN), //640x480px w/32-bit depth
new DisplayMode(640,480,24, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/24-bit depth
new DisplayMode(640,480,16, DisplayMode.REFRESH_RATE_UNKNOWN), // ' w/16-bit depth
};
I'm assuming that the error is with your public void setFullScreen(DisplayMode dm) method. In that case, the full syntax for this method is:
/*****************************************************************************
* #description: Creates window for program to run in, using appropriate DM
* #param DisplayMode dm
*/
public void setFullScreen(DisplayMode dm){
JFrame f = new JFrame();
f.setUndecorated(true); //no titlebars/scroll bars etc.
f.setIgnoreRepaint(true);
f.setResizable(false); //user cannot resize window
vc.setFullScreenWindow(f);
if(dm!=null && vc.isDisplayChangeSupported()){ //if DM is changeable
try {
vc.setDisplayMode(dm);
} catch (Exception e){/*Catch 'em all*/}
}
f.createBufferStrategy(2); //set # of screen buffers to 2
}//setFullScreen()
Noticed this was a mild necro-post after posting. Aaahh...

Categories