I've managed to add an image into a JPanel in netbeans and display it.I wonder how to get to the next one,by pressing a button.
I've added the image using this code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
// TODO add your handling code here:
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(null);
if ( result == JFileChooser.APPROVE_OPTION ){
String Ruta = fileChooser.getSelectedFile().getAbsolutePath();
jTextField1.setText(Ruta);
Icon icon = new ImageIcon(Ruta);
jLabel2.setIcon(icon);
JOptionPane.showMessageDialog(this,"You chose to open this file: " +
fileChooser.getSelectedFile().getName());
}
}
And when i press a button called "jButton2" to get the next image,without manually selecting it again from folder.
For example:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
// TODO add your handling code here:
}
Thank You very much.
You have to enumerate images in the directory you are browsing in. When the user selects the file, you should keep a list of all images from that directory in order to retrieve them when user click the next button. As well you can get the file list whenever the user clicks the next button.
maybe something like this:
private File allFiles;
private int currentIndex;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(null);
if ( result == JFileChooser.APPROVE_OPTION ){
currentFile = fileChooser.getSelectedFile();
String Ruta = currentFile.getAbsolutePath();
jTextField1.setText(Ruta);
allFiles = currentFile.getParent().listFiles(); // maybe you need a filter to include image files only....
currentIndex = indexOf(allFiles, currentFile);
Icon icon = new ImageIcon(Ruta);
jLabel2.setIcon(icon);
JOptionPane.showMessageDialog(this,"You chose to open this file: " + fileChooser.getSelectedFile().getName());
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
if (currentIndex+1 < allFiles.length) {
jtextField1.setText(allFiles[++currentIndex]);
}
}
private int indexOf(File[] files, File f) {
for (int i=0; i+1 < files.length; i++) {
if (files[i].equals(f)) {
return i;
}
}
return -1;
}
Get the parent file if the current image (File.getParent()).
Use one of the File.list..() methods to get the image files.
Sort them into some order that means 'next' to the user.
Iterate that connection until you find the current File then display the next one after that.
I am assuming that you want the next image, if possible in the same directory you chose in your first code excerpt. What you could do is that once the user has chosen the image, you could use Apache's FileUtils to get the extension of files. If the file is a JPG, JPEG, PNG, etc you could load it's location in a List of strings.
This will give you a list of picture paths. You could then use the buttons to traverse the list. Once the button is pressed, you move to the next item, load the image and render it.
EDIT: This is how I would go about it step by step:
Create a global variable of type List.
Create a global variable which will act as a counter;
In your jButton1ActionPerformed method:
Get the parent directory of the file that the user has chosen;
Use Apache's FileUtil class to get the extension of the file names. If the file name is an image, such as PNG, JPG, etc, add it (the path of that file) to your list.
In you jButton2ActionPerformed, increment the counter (if the counter is not smaller than the size of your list, re-initialize it to 0, so as to avoid OutOfBoundsExceptions) and load the the file denoted by the counter using similar logic to your jButton1ActionPerformed method.
Related
I am using JFileChooser as a component for selecting files in this code.
I need one additional input from the user to trigger the way how the file shall be opened. In my use case if it shall be read to the RAM entirely or not.
I know I can ask user elsewhere but the best would be if I can add JCheckBox to the JFileChooser dialog. I want to achieve something as on the picture.
How I can do that and how I read the status of user input?
I figured out the simplest is to utilize the mechanism that is intended for image thumbnails of selected files. By providing so called Accessory Component, which must be a child class of JComponent, through calling JFileChooser.setAccessory you can obtain a space to the right of file selecting rectangle.
Including minimal example:
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Open DEN file...");
fc.setAccessory(new CheckBoxAccessory());
int returnVal = fc.showOpenDialog(frame);
CheckBoxAccessory cba = (CheckBoxAccessory)fc.getAccessory();
boolean useVirtualStack = cba.isBoxSelected();
JOptionPane.showMessageDialog(null, String.format("selected=%b", useVirtualStack));
where the class CheckBoxAccessory looks as follows
public class CheckBoxAccessory extends JComponent {
JCheckBox virtualCheckBox;
boolean checkBoxInit = false;
int preferredWidth = 150;
int preferredHeight = 100;//Mostly ignored as it is
int checkBoxPosX = 5;
int checkBoxPosY = 20;
int checkBoxWidth = preferredWidth;
int checkBoxHeight = 20;
public CheckBoxAccessory()
{
setPreferredSize(new Dimension(preferredWidth, preferredHeight));
virtualCheckBox = new JCheckBox("Virtual stack", checkBoxInit);
virtualCheckBox.setBounds(checkBoxPosX, checkBoxPosY, checkBoxWidth, checkBoxHeight);
this.add(virtualCheckBox);
}
public boolean isBoxSelected()
{
return virtualCheckBox.isSelected();
}
}
The result looks as follows
Disadvantage is that you will not get the whole component to play with but just a relatively small box. Thus the visual look is not what I initially wanted, but when you are no Picasso, you won't care. Advantage of this solution is that you can even react on change of selected file, which is in more details described in https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html#accessory
I have a page that has a button to download information in the format of a CSV file. The button opens a confirm dialog to download the file. I need to store that file to a temporary location (whether that be memory or saving to an actual file and then deleting it after) and then read the data in the CSV to an array.
I've tried the code in these questions (question 1, question 2, question 3, and question 4), and it's not quite what I need - mostly because they weren't downloading a CSV and using the data in it.
I'm not sure that the ConfirmDialog is being opened, but I did add a ConfirmHandler returning true to attempt to download the file. However, I don't know where the file is downloading if it is at all.
Here's what I have happening and where I get stuck:
I log in just fine. I go to a report generator. I generate a report that opens in a new window. The new window opens fine and I catch it with a WebWindowListener. I then search for the "save as CSV" button on the new window. I can find that, and I can click on it, but a System.out.print call shows that the ConfirmHandler isn't firing.
for (DomElement e : newPage.getElementsByTagName("button")) {
int i = 0;
webClient.setConfirmHandler(new ConfirmHandler() {
private static final long serialVersionUID = 1L;
#Override
public boolean handleConfirm(Page arg0, String arg1) {
System.out.println("Test"); //isn't firing
return false;
}
});
if (((HtmlButton) e).getAttribute("onclick").contains("CSV")) {
((HtmlButton) e).click();
}else {
if (i++ == (newPage.getElementsByTagName("button").size() - 1)) throw new AssertionError("CSV button not found");
}
}
The inspiration for this answer came from this answer.
I really wanted to get the CSV information without downloading the file, and so I, inside of the webWindowContentChanged(arg0) method of my webWindowListener, just used arg0.getWebWindow().getEnclosingPage().getWebResponse().getContentAsString() and then used String.split() a couple times to get the information I wanted.
Here's what the code looks like so it's a little clearer:
webClient.addWebWindowListener(new WebWindowListener() {
#Override
public void webWindowContentChanged(WebWindowEvent arg0) {
if (CSVclicked) { //boolean that is set true when I click the download button...
String CSV = arg0.getWebWindow().getEnclosedPage().getWebResponse().getContentAsString();
//do things...
CSVclicked = false; //don't use the same behavior next time the method is called...
}
}
});
I have a problem with my JComboBox.
description:
I create a new file by writing the name of my file in a Textfield. By clicking on a button I create a file with this value and add this into my JComboBox, but I only see the Object value, for example "[Ljava.io.FIle;#1b1428d" and that's the problem. The user doesn't even know what this value means so I need my filename. I searched for a long time and Yes the toString() doesn't work :D
My Code looks like this: JComboBox TxtDoc = new JComboBox(create());
public File[] create(){
FileSystemView SYSTEM = FileSystemView.getFileSystemView();
String user = System.getProperty("user.home")+"\\notes";
File userdir = new File(user);
File[] fileList = SYSTEM.getFiles(userdir, true);
return fileList;
}
newTxt.addMouseListener(new MouseAdapter() {
#SuppressWarnings("unchecked")
public void mouseClicked(MouseEvent event){
new Documents().createTxtDoc(); // <-- this just open a new frame with my textfield and a button.
TxtDoc.addItem(create());
}
});
thank you for your help
regards Blank
iterate over it:
for (File f : fileList) {
TxtDoc.addItem(f);
}
You're add an array Files as a single element of the combobox (that's what addItem does, adds A (single) item)
There's a few ways you might be able to do this, one might be to simply reset the combo box's model...
TxtDoc.setModel(new DefaultComboBoxModel(create());
This has the the nice side effect of removing all the previous elements first
Having said that, you might not like the results...
You may want to consider providing a custom cell render to render just the name of the file. See How to Use Combo Boxes and Concepts: Editors and Renderers for more details
I'm making a small Java application that have to show some images in a JLabel named picLabel.
I have a JList of Photo objects (that contains an InputStream of an image, read from a database).
Here is the code of the JList ValueChanged event listener:
private void photoListValueChanged(javax.swing.event.ListSelectionEvent evt) {
if (evt.getValueIsAdjusting() == false && photoList.getSelectedIndex() != -1) {
photo = (Photo) photoList.getSelectedValue();
BufferedImage image = ImageIO.read(photo.getContent()) ;
if(image != null) {
picLabel.setIcon(new ImageIcon(image));
}
}
It works perfectly for the first time I select each element from the list. But if I choose again an element that was already selected (and the image was already shown), it simply don't show the image, leaving the JLabel as it was before.
Am I missing something?
Once you have read the image once from the input stream, the stream is at its end, and reading a second time won't read anything. The Photo class should read from the stream and store everything read as a byte array, or as a BufferedImage or ImageIcon directly.
What I'm having problems with is that I have a list of 10 files in a JList. On a JButton, I have "attached file(s) 0." What I'm trying to achieve is when a user clicks on a file in the JList, the variable fileCount (represents the '0') will increment. Here is the code:
#Override
public void mouseClicked(MouseEvent arg0) {
int idx = list_fileListing.getSelectedIndex();
String eFiles[] = ig.getListOfFiles();
if(idx == list_fileListing.getSelectedIndex()){
fileCount++;
}
}
Basically, if a file is selected, increment fileCount. Any suggestions as to how to accomplish this?
The JButton class has a setText() method like many of the other Swing component classes. You can use this method to overwrite the text that is currently on the JButton.
ex:
if(idx == list_fileListing.getSelectedIndex())
{
fileCount++;
yourButtonName.setText("attached file(s) " + fileCount);
}
hope this helps.