How to update Jlabel Text in Swing - java

I've a simple GUI file which is here:
I want to update the Label text each time when new file is selected
But when I am selecting any file, it is overlapping on the existing Jlabel text, so, please help me how do I update my JLabel text.
Here is my code:
protected static void excelButtonAction(){
excelReturnVal = fc.showOpenDialog(excelButton);
if(excelReturnVal==JFileChooser.APPROVE_OPTION){
FileValidation.excelFileValidation(fc);
System.out.println(FileValidation.getName() );
if(status==JFileChooser.CANCEL_OPTION){
}else{
fileName=FileValidation.getName();
FileValidation.updatemylabel(fileName);
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
}
} else{
System.out.println("Open command cancelled by user." + newline);
}
}
public static void updatemylabel(String exfileName){
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser) evt.getSource();
File oldFile = (File) evt.getOldValue();
File newFile = (File) evt.getNewValue();
File curFile = chooser.getSelectedFile();
}else if(JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser)evt.getSource();
File[] oldFiles = (File[])evt.getOldValue();
File[] newFiles = (File[])evt.getNewValue();
File[] files = chooser.getSelectedFiles();
}
}
});
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
existingText=exfileName;
}
Let me know if any further information is required to resolve my issue.
Thanks in advance for your co-operateion.

Your code creates a new JLabel instance every time. You need to create an instance once, store it in a field of your class, and call setText() whenever you need to update it.

You can have a look at the following for better understanding of labels in java :
How to Use Labels
setText
public void setText(String text)
Defines the single line of text this component will display. If the value of text is null or empty string, nothing is displayed.
The default value of this property is null.
This is a JavaBeans bound property.

Related

Upload image to server from Java

Follow a small Java code to select an image from a folder. What I would like is to know how to upload it to a server, I have always uploaded images from javascript or jquery or php too. Use a AngularJS frameworks and also to upload images Ionic from mobile devices to my server, I am now working directly in Java and have some doubts. On issues of time, I would like to know how is the best way to upload an image, bits or base64? And if they could help me with this conversion would appreciate. I'm new to Java and I'm just practicing. Regards!
My code :
public class UI extends JFrame {
JButton buttonBrowse;
JButton buttonUpload;
JLabel label;
public UI(){
super("Set Picture Into A JLabel Using JFileChooser In Java");
buttonBrowse = new JButton("Browse");
buttonUpload = new JButton("Upload");
buttonBrowse.setBounds(300,300,100,40);
buttonUpload.setBounds(400, 300, 100, 40);
label = new JLabel();
label.setBounds(10,10,670,250);
add(buttonBrowse);
add(buttonUpload);
add(label);
buttonBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
//filter the files
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
//if the user click on save in Jfilechooser
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
System.out.println(path);
label.setIcon(ResizeImage(path));
}
//if the user click on save in Jfilechooser
else if(result == JFileChooser.CANCEL_OPTION){
System.out.println("No File Select");
}
}
});
buttonUpload.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(700,400);
setVisible(true);
}
// Methode to resize imageIcon with the same size of a Jlabel
public ImageIcon ResizeImage(String ImagePath)
{
ImageIcon MyImage = new ImageIcon(ImagePath);
Image img = MyImage.getImage();
Image newImg = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(newImg);
return image;
}
public static void main(String[] args){
new UI();
}
}

How to draw image using FileDialog in Java

Need to display selected in FileDialog image, but thats somewhy didnt work. When i try to choose image it throws exception javax.imageio.IIOException: Can't create an ImageInputStream!
I think problem is in getDirectory() , but dont know how to fix.
public ImageShow() throws IOException {
super("Pictures");
setSize(1024,768);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonOpen = new JButton("Open file");
buttonPanel.add(buttonOpen);
actions();
fileDialog();
add(buttonPanel);
image = ImageIO.read(new File(fd.getDirectory()));
imageLabel = new JLabel(new ImageIcon(image));
buttonPanel.add(imageLabel);
}
public void fileDialog() {
fd = new FileDialog(new JFrame(), "Choose file");
fd.setVisible(true);
}
public void actions() {
buttonOpen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fileDialog();
}
});
}
}
image = ImageIO.read(new File(fd.getDirectory()));
A directory is not an image! Try instead getFile() which:
Gets the selected file of this file dialog. If the user selected CANCEL, the returned file is null.
But as I said in comments..
Use the Swing based JFileChooser rather than the AWT based FileDialog.
And be sure to consult the avialable documentation when using methods.

Java Null Pointer When clicking JButton(Eclipse)

Here is my code. I am trying to make a basic text editor just to try out file writing and reading along with JPanels and such. My current issue is that users are required to input the full file path of the file and that can get quite frustrating. So I made a button that allows the user to have preset file path settings. When you click on the 'File Path Settings' button, there is a window that pops up allowing you to set the settings. (A file browsing button will be implemented later I just wanted to do this for fun first.)
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName,saveFilePath,filePathSaveDirectory,savedFilePath;
JButton save,help,savePath;
//JTextArea text;
public EventListeners(){
window();
}
public void window(){
JFrame window = new JFrame();
window.setVisible(true);
window.setSize(650,500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10,50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500,500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help",JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20,100);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory+"filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert",JOptionPane.WARNING_MESSAGE);
}
});
}
public static void main(String[] args) {
new EventListeners();
}
}
main problem is you are creating variable with same name inside the constructer, you already define as instance .then your instance variable keep uninitialized/null.
for example
you have declare instance variable
JButton save, help, savePath, saveFilePath;
inside constructor you are creating another local jbutton and initialize it so instance variable is null.
so instead of creating new one you should initialize instance field.
JButton saveFilePath = new JButton("File Path Save Settings"); // problem
saveFilePath = new JButton("File Path Save Settings"); // correct way
but there is a another problem ..you have declare saveFilePath instance field as a jtextfield and you have created a saveFilePath button inside the constructor .i think it may be a button not a textfield.
also you are initializing some variables inside saveFilePath.addActionListener(new ActionListener() { method but you are adding actionlistners to them before saveFilePath action fired .you have to add actionlistners after you initialized a component.
also you should call repaint() at last after you add all the component to a frame..
try to run this code
import javax.swing.*;
import java.awt.event.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName, filePathSaveDirectory, savedFilePath;
JButton save, help, savePath, saveFilePath;
//JTextArea text;
public EventListeners() {
window();
}
public void window() {
JFrame window = new JFrame();
window.setSize(650, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10, 50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500, 500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
System.out.println(savePath);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory + "filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert", JOptionPane.WARNING_MESSAGE);
}
});
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help", JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20, 100);
window.setVisible(true);
}
public static void main(String[] args) {
new EventListeners();
}
}
You also may want to consider dependency injection. That is becoming the standard way of doing things in the industry. Instead of the constructor doing all the work of creating all the objects your class uses, or calling another method like window() to do all the work, you pass in all the specifications to the constructor. It might look something like
public EventListeners(JButton save, JButton help, JButton saveFilePath) {
this.save = save;
this.help = help;
this.saveFilePath = saveFilePath);
}
Of course, you could also use a dependency injection framework like Spring, but that might be a bit much if your application is small.

How to load a File using JFileChooser?

In Java I want to load a file [whatever format it is] in its own format using JFileChooser. Means I don't want to read and display the contents inside my JFrame. Instead I want them to open/load like an image open in a Windows Photo Viewer/Irfan Viewer and a PDF open in Adobe Reader By clicking a Button.
I had searched a lot. But all tutorial I read tells how to print a line "opening this file/You are selected this file" by clicking a JButton. Nobody is actually opening/loading a file on a button click. May be I am not getting correctly what they said because I am new to Java. I hope my problem is clear and please help...
Here is the code that I got from a tutorial page:
public class JFileChooserTest {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComboBox Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Select File");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
}
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}
Here is what I want to do with Java. here is an example with windows:
A Browse Button Click opens this window
And when I select the XLS file and click OPEN button, an XLS file will open. I want to do the exact same with Java. Hope it is more clear now.
You may try using Desktop.open():
Desktop.getDesktop().open(selectedFile);
EDIT
You need to update here:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
java.awt.Desktop.getDesktop().open(selectedFile);//<-- here
}
}
});
Sample code from site:
If I understand you correctly, you want to select a file and pass it to the system's default application. Unfortunately, this is highly dependable on your operating system. For Windows you can pass that to the command line like this:
String systemcall = "cmd /C start \"\" \"" + absolutePath + "\"";
Runtime runTime = Runtime.getRuntime();
HomeLogger.instance().info("EXECUTE " + systemcall);
runTime.exec(systemcall);
The String absolute Path must be the exact locatin of the file, e.g. "C:\test.txt". I hope that helps!

saving setText after closing JDialog

I'm having a JDialog that works as a "Settings Window". I Choose a Save-File-Path and I click a button named Save. It Stores the Path and displays it on a JTextField. My problem is when i close the JDialog called "Settings" and open it again the JTextField doesn't display the newest Path.
I think it has something to do with the JDialog and that it doesn't store the setText variable. How can I store the new text in the JTextField?
This is a fragment of my code:
public class Settings extends JDialog {
textField = new JTextField("C\\:");
textField.setBounds(10, 36, 254, 28);
panel.add(textField);
textField.setEditable(false);
textField.setColumns(10);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
choose= new JFileChooser();
choose.setCurrentDirectory(new java.io.File("."));
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rVal = choose.showSaveDialog(Settings.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(choose.getSelectedFile().getName());
dir.setText(choose.getCurrentDirectory().toString());
File file = choose.getSelectedFile();
string myline = file.getAbsolutePath();
}});
sbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(myline);
}
});
So I wan't to set textfield to myline and even after closing the JDialog, store it and display it next time you open JDialog.
If you intend for the Settings class to store the value of the settings then make sure you are using one instance of Settings and not creating a new Settings object when opening the dialog.
declare the myline object outside of the listener like this way
private string myline = "":
public class Settings extends JDialog {
textField = new JTextField("C\\:");
textField.setBounds(10, 36, 254, 28);
panel.add(textField);
textField.setEditable(false);
textField.setColumns(10);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
choose= new JFileChooser();
choose.setCurrentDirectory(new java.io.File("."));
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rVal = choose.showSaveDialog(Settings.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(choose.getSelectedFile().getName());
dir.setText(choose.getCurrentDirectory().toString());
File file = choose.getSelectedFile();
myline = file.getAbsolutePath();
}});
sbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(myline);
}
});
You can make the JFileChooser instance variable of your main class so that it remembers the last directory location. You can also initialize your text field based on current file in the chooser.

Categories