so Basically I an working on this project car registration and I find difficulties in changing part of the page so I used the boarder pane to and I reached a point that I can change the middle pane but to null I believe that the problem comes from here
This is my code:
private Pane view;
#FXML
public Pane getPage(String fileName) {
try {
URL fileUrl = App.class.getResource("/org.example/" + fileName + ".fxml");
if (fileUrl == null) {
throw new java.io.FileNotFoundException("FXML file can't be found");
}
view = new FXMLLoader().load(fileUrl);
} catch (Exception e){
System.out.println("No page " + fileName + " please check FxmlLoader.");
}
return view;
}
This is where I believe the problem comes from:
URL fileUrl = App.class.getResource("/org.example/" + fileName + ".fxml");
because I get (No page addingACar.fxml please check FxmlLoader.
)
my question is I am not sure how to reach the file I assigned as a URL
Related
I have problems trying to create an ImageIcon for my project. My createImageIcon method goes as follows ::
protected ImageIcon createImageIcon(String path, String description)
{
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null)
{
return new ImageIcon(imgURL, description);
}
else
{
System.err.println("Couldn't find file: " + path);
return null;
}
}
And the line that creates the Icon ::
ImageIcon icon = createImageIcon("**ICON URL***","Java");
Unfortunately, I cannot create any Icon because all the URLs I enter are not found (the file is not found). Could someone please tell me how to get the URL of an image found online that will work and will fit for this method? Thanks.
I am trying to get all frames from an mp4 file using the ExtractMpegFrames.java class found here http://bigflake.com/mediacodec/ExtractMpegFramesTest.java.txt
What I currently do is create a temp file (File.createTempFile) in a directory that stores all the frames, create a FileOutputStream and do
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut)
where fOut is the OutputStream with the file.
Currently, the saved images look like this: https://imgur.com/a/XpsV2
Using the Camera2 Api, I record a video and save it as an mp4. According to VLC, the color space for the video is Planar 4:2:0 YUV Full Scale.
Looking around, it seems that each vendor uses different color spaces
https://stackoverflow.com/a/21266510/7351748. I know ffmpeg can conversions with color spaces, but I cannot use it.
I am not sure where to start to solve this issue of the strange output pngs. I am assuming that this is a color space issue, but I can be completely wrong here.
You can get all Frames of Video Using ffmpeg library here is working code.
add dependancy
compile 'com.writingminds:FFmpegAndroid:0.3.2'
to your gradle
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
// #Override
// public void onFailure() {
// showUnsupportedExceptionDialog();
// }
#Override
public void onSuccess() {
Log.d(TAG, "ffmpeg : correct Loaded");
}
});
} catch (FFmpegNotSupportedException e) {
} catch (Exception e) {
Log.d(TAG, "EXception : " + e);
}
}
here is image extratct method
public void extractImagesVideo() {
File moviesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
);
String filePrefix = "extract_picture";
String fileExtn = ".jpg";
String yourRealPath = getPath(Pick_Video.this, DataModel.selectedVideoUri);
Log.d("selected url", "" + DataModel.selectedVideoUri);
File src = new File(yourRealPath).getAbsoluteFile();
File appDir=new File(moviesDir,"/"+app_name+"/");
if(!appDir.exists())
appDir.mkdir();
DataModel.appDir=appDir;
File dir = new File(appDir, "testVideo");
int fileNo = 0;
while (dir.exists()) {
fileNo++;
dir = new File(moviesDir+"/"+app_name+"/", "testVideo" + fileNo);
}
dir.mkdir();
DataModel.dir = dir;
resultList = new ArrayList<String>(256);
filePath = dir.getAbsolutePath();
File dest = new File(dir, filePrefix + "%03d" + fileExtn);
Log.d(TAG, "startTrim: src: " + src.toString());
Log.d(TAG, "startTrim: dest: " + dest.getAbsolutePath());
String[] complexCommand = { "-i",""+src.toString(),"-qscale:v", "2","-vf", "fps=fps=20/1",dest.getAbsolutePath()};
//"-qscale:v", "2","-vf", "fps=fps=20/1",//
//works fine with speed and
execFFmpegBinary(complexCommand);
}
call this two method on button click event
Comment If Any query.
Edit: For any future person reading this, you need to add parameters to the method I have shown in the post.
Instead of doing + textview +, you do +with parameter+ and then in the controller, you make integers/strings for the parameters and set them = to textview.getText(), then you put those integers/strings inside the method parameters of the method you are getting from the instance in the controller class.
Original Post
How do I get the value from a TextView in a method in another class outside the Controller class?
I cannot use textview.getText(); outside the Controller class or it will just give me NullPointerException.
Here is my method from my other class:
Controller c;
public void createRecipes() throws SQLException {
openDB();
if (connectionDB != null) {
Statement st = this.connectionDB.createStatement();
String insert = "INSERT INTO recipes "
+ " (ID, name, temperature, fan, redlight, bluelight, addwater) " + " VALUES "
+ " ( " + c.createID.getText() + ", " + c.createName.getText() + ", " +c. createTemperature.getText() + ", " + c.createFan.getText() + ", " + c.createRedLight.getText() + ", " + c.createBlueLight.getText() + ", " + c.createWaterLevel.getText() + " ) ;";
st.executeUpdate(insert);
} else {
System.out.println("No connection established to the database.");
}
closeDB();
}
This is the textfield I am getting from my controller class:
c.createBlueLight.getText()
You shouldn't use fx components outside of you controller! You should always separate logic and ui. So just pass the text content to the method.
This is an example of the right way to access controllers that are generated by parsing FXML files from FXMLLoader
public class Controller {
#FXML
private TextField textField;
public TextField getTextField() {
return textField;
}
public String getTextFieldValue() {
return textField.getText();
}
}
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
So the controller is initialized correctly (the textField field is not null) and we can use it without problem, for example
TextField textField = controller.getTextField();
or
String value = controller.getTextFieldValue();
I try to use a Wicket Modal Window to set the PropertyModel of an Entity. The problem is this Entity has a FIleUploadFields that i read non work nice with Ajax. I need to use AjaxSubmitLink inside the modal and i don't be able to get this work fine.
setMultiPart(true);
setMaxSize(Bytes.megabytes(100));
fileUpload = new FileUploadField("fileUpload");
fileUpload.setOutputMarkupId(true);
fileUpload.setOutputMarkupPlaceholderTag(true);
add(fileUpload);
save_btn = new AjaxLink("save_btn") {
#Override
public void onClick(AjaxRequestTarget art) {
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null && uploadedFile.getSize() > 0) {
try {
if (GestioneDocumentiDcs.isTextDocument(uploadedFile)) {
String ext = GestioneDocumentiDcs.getTextExtension(uploadedFile.getContentType());
String nomeFile = "c_" + _corso.getId() + "_m_" + materialeCorso.getId() + ext;
byte[] b = ByteStreams.toByteArray(uploadedFile.getInputStream());
gd.salvaFile(b, gd.getPathCorso(_corso) + "/" + nomeFile);
materialeCorso.setPercorso(nomeFile);
materialeCorso.setDimensione(uploadedFile.getSize());
materialeCorso.setDataUpload(LocalDate.now());
}
} catch (Exception e) {
System.out.println("ERRORE: " + Utils.StampaStackError(e));
}
}
this is my code inside the Modal
AjaxLink does not submit the form, so nothing will be transferred to the server. You need either AjaxButton or AjaxSubmitLink.
I have a JSF2 commandlink with an image. When the image is clicked, the server will download a PDF file. While the file is downloaded after the image link is clicked, it also causes the entire page to scroll to the top of the page. the code snippet for the link is as follows:
<p:commandLink ajax="false"
action="#{refereeAssessmentSummaryBean.stateLatestFormInPAVer(project.appId)}">
<p:graphicImage name="images/pdf.png"
title="#{msg['label.downloadpdf']}" />
</p:commandLink>
How can I use the commandlink to download the PDF file, without the webpage scrolling to the top of the page every time I click on it?
Edit: FWIW, added PDF download code. This code is called as a shared method from the backing bean. As you can see, the code will set the content type before streaming the PDF data to the client.
public void downloadEformPdf(Integer appId, Integer revNo, Integer meetingId,
String password, boolean showSaveDialog, boolean getEditedIfAvailable, boolean showVersionInfo) {
User user = WebUtils.getCurrentUser();
PermissionResult permissionResult = ServiceProxy.getPermissionService().checkViewOnlineProposalPermission(user, appId, meetingId);
if (permissionResult != PermissionResult.GRANTED) {
if (!(permissionResult == PermissionResult.REJECTED_GRBE_COI_NOT_APPROVED
|| permissionResult == PermissionResult.REJECTED_GRBE_COI_NOT_DECLARED)) {
throw new PermissionDeniedException("Permission Denied");
}
}
Application appl = ServiceProxy.getAppService().getApplication(appId);
String scheme = appl.getScheme();
boolean withNomination = false;
boolean isEditedVersion = false;
byte[] pdfData;
if (getEditedIfAvailable) {
if (revNo == null) {
Appmatching appMatching = ServiceProxy.getAppFormService().getLatestAppMatching(appId,false);
revNo = appMatching.getMainRevno();
}
Appattacheditedeform editedEntry = ServiceProxy.getAppService().getEditedProposalForApplication(appId, revNo, true);
// give GRB, ER the edited version if it exists
if (editedEntry != null) {
Filestorage storage = editedEntry.getFilestorage();
pdfData = storage.getContent();
isEditedVersion = true;
} else {
pdfData = ServiceProxy.getReportService().getHMRFReportContentByRevNo(
appId.intValue(), revNo, withNomination);
}
} else { //Get the unedited version
//Get latest rev no.
if (revNo == null) {
Appmatching appMatching = ServiceProxy.getAppFormService().getLatestAppMatching(appId,false);
revNo = appMatching.getMainRevno();
}
pdfData = ServiceProxy.getReportService().getHMRFReportContentByRevNo(
appId.intValue(), revNo, withNomination);
}
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
extContext.responseReset();
PDDocument doc = null;
try {
if (pdfData != null) {
PDFParser parser = new PDFParser(new ByteArrayInputStream(pdfData));
parser.parse();
doc = parser.getPDDocument();
AccessPermission ap = new AccessPermission();
ap.setReadOnly();
if (password != null) {
StandardProtectionPolicy spp = new StandardProtectionPolicy(password, password, ap);
spp.setEncryptionKeyLength(128);
doc.protect(spp);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
doc.save(bos);
doc.close();
byte[] docbuff = bos.toByteArray();
String refNo = appl.getRefNo();
String filename = null;
if (showVersionInfo) {
if (isEditedVersion) {
filename = scheme.toLowerCase() + "_eform_" + refNo + "_(v" + revNo + ")_(Edited).pdf";
} else {
filename = scheme.toLowerCase() + "_eform_" + refNo + "_(v" + revNo + ")_(PA).pdf";
}
} else {
filename = scheme.toLowerCase() + "_eform_" + refNo + ".pdf";
}
extContext.setResponseContentType("application/pdf");
extContext.setResponseContentLength(docbuff.length);
extContext.setResponseHeader("Content-Disposition", (!showSaveDialog) ? "inline"
: "attachment" + "; filename=\"" + filename + "\"");
OutputStream os = extContext.getResponseOutputStream();
os.write(docbuff);
os.close();
context.responseComplete();
} else {
extContext.setResponseContentType("text/html");
Writer writer = extContext.getResponseOutputWriter();
writer.write("Cannot retrieve PDF form for this proposal.");
writer.close();
context.responseComplete();
}
} catch (IOException e) {
logger.log(Level.ERROR, e.getMessage(), e);
} catch (COSVisitorException e) {
logger.log(Level.ERROR, e.getMessage(), e);
} catch (BadSecurityHandlerException e) {
logger.log(Level.ERROR, e.getMessage(), e);
} finally {
}
}
How do you generate the PDF?
Did you set a mimetype so that the brower will recognize that you respond with a pdf?
Did you also prevent primefaces from continuing the response after you have written your PDF file to it? (use facesContext.responseComplete(); for that)
When you use the default HTML link tag <a />, you have to set href='javascript:void(0)' to avoid the current page to scroll to the top.
Maybe there is a way with a p:commandLink to do the same thing
<p:commandLink url="javascript:void(0)" ... /> ??
Hope this will help you to resolve your problem
I think it's because you are using ajax=false.
If you are not using ajax the whole page will be reloaded.
Either remove it or change to ajax=true and give it a try.
Edit:
I was wrong. ajax=false is required when downloading files.