I am trying to add a JFileChooser to JPanel. Sometimes it works properly and sometimes it shows just the JPanel without the JFileChooser dialogue box. Now i actually don't know what to do . Can anyone help me please?
Here is my code(It is a method):
public File chooseFileFromComputer(){
methodPanel = new JPanel();
methodPanel.setLayout(null);
methodFrame = new JFrame();
methodFrame.setTitle("File Chooser");
methodFrame.setVisible(true);
BufferedImage removeJavaImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
methodFrame.setIconImage(removeJavaImage);
methodLabel = new JLabel("Choose a file: ");
methodLabel.setBounds(10, 10, 80, 20);
methodPanel.add(methodLabel);
fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setBounds(10, 35, 550, 500 );
fileChooser.setVisible(true);
add(fileChooser);
/**
* Action Events #********AE*******#
**/
fileChooser.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
selectedFile = fileChooser.getSelectedFile();
methodFrame.setVisible(false);
} else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
methodFrame.setVisible(false);
}
}
});
//End of Action Events #________AE_______#
methodPanel.add(fileChooser);
methodFrame.setContentPane(methodPanel);
methodFrame.setResizable(false);
methodFrame.setSize(600, 600);
methodFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
return selectedFile;
}
You are using a null layout and calling setBounds(...) on your components. While this may seem to a newbie the better way to create complex GUI's, it's a fallacy, and more you create Swing GUI's the more you learn to respect and use the layout managers and see that these creatures help immensely in creating flexible, beautiful and if need be, complex GUI's.
add your components to the JFrame, and only then call setVisible(true) on the JFrame.
It doesn't look like you should be using a JFrame at all if you are setting it visible and invisible. Perhaps you really want to use a JDialog or even a free standing JFileChooser dialog.
Edit
You are adding the JFileChooser to more than one container:
add(fileChooser); // ******************* here *************
fileChooser.addActionListener( new ActionListener(){
private File selectedFile;
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
selectedFile = fileChooser.getSelectedFile();
methodFrame.setVisible(false);
} else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
methodFrame.setVisible(false);
}
}
});
methodPanel.add(fileChooser); // ******** here *******
You can't do this. Only add it to one container, else it may not show correctly or show at all.
Edit 2
You're returning the wrong result from your method. You return the selectedFile variable, but do so before it is ever set since it is set by the ActionListener which is called long after this method returns.
Solution: again, don't use a JFrame here where a modal JDialog would work much better. If you used a modal dialog and returned after the ActionListener is done, your code would work.
Edit 3
But again for my money, I'd just use a JFileChooser as a modal dialog. For example:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose a File");
// don't use null in the method below but rather a reference to your current GUI
int response = fileChooser.showOpenDialog(null);
if (response == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
System.out.println(file);
}
Your JPanel - methodPanel has null layout methodPanel.setLayout(null); try it with for example with FlowLayout
I don't know exactly about your class wherether extends jpanel or not , but you should add filechooser to methodPanel together with label. I tested your code is ok except actionPerform.
methodPanel.add(fielChooser);
I suggest, just try it.
Related
I am trying to display on a label (ecran) the file and path I just picked using FileDialog object.
But it is not working.
My code is returning a null value and I don't know why.
Can you please help me?
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class FerPrinc extends Frame implements ActionListener{
Label ecran;
public String path = null;
public FerPrinc(String titlu){
super(titlu);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
final Label ecran = new Label();
add(ecran, BorderLayout.SOUTH);
Button b = new Button("Choose file");
add(b, BorderLayout.NORTH);
b.addActionListener(this);
System.out.println (path);
ecran.setText(path);
pack();
}
public void actionPerformed(ActionEvent e){
FileDialog fd = new FileDialog(this, "Choose file", FileDialog.LOAD);
fd.setDirectory(".");
fd.show();
path = fd.getDirectory()+fd.getFile();
//System.out.println (path);
//ecran.setText(path);
}
}
public class TestFileDialog {
public static void main (String[] args) {
FerPrinc f = new FerPrinc("Test Dile Dialog");
f.show();
}
}
Actual result is NULL.
I am expecting to see the full path to teh file i selected.
You can't, this isn't how ActionListener or GUIs work. Swing, like most GUIs, is event driven, something happens, you react to, it's no linear. Registering a ActionListener to a button isn't going to stop the code execution, waiting for the user to press the button, what happens if they never do? Instead, you need to wait till the ActionListener is triggered and THEN perform the associated actions.
This is a basic concept of an observer pattern.
I think you need to speed some more time going through Creating a GUI With JFC/Swing, How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener as this is a basic concept of the API you should understand before embarking on writing your own applications
Im looking to change an Icon when I click a Jbutton. I have button1 rigged up to an action command that prints "On" or "Off". I would like to have the button change icons from an image of an circle meaning off, to an image of a power button meaning on. I've tried many things but haven't been able to find a solution so Im wondering if there is an easy way to do this or if there isn't an easy way, and ill have to make a more complex way for each button. Any advice is greatly appreciated because Im at a dead end. Fell free to edit large blocks or add things because Im open to all ideas. The code is included below
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
public class OnandOff{
public static void main(String[] a){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new ButtonDemo());
f.setSize(600,500);
f.setVisible(true);
}
}
class ButtonDemo extends JPanel implements ActionListener {
JTextField jtf;
public ButtonDemo() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
makeGUI();
}
});
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
setLayout(new FlowLayout());
//sets up icons
ImageIcon OnIcon = new ImageIcon(" On.jpg");
Icon OffIcon = new ImageIcon("Off.jpg");
ImageIcon BlankIcon = new ImageIcon("Blank.jpg");
//creates jbuttons with Action command
ImageIcon button1 = new ImageIcon("Off.jpg");
JButton jb = new JButton(button1);
jb.setActionCommand("On");
jb.addActionListener(this);
add(jb);
ImageIcon button2 = new ImageIcon("Off.jpg");
jb = new JButton(button2);
add(jb);
ImageIcon button3 = new ImageIcon("Off.jpg");
jb = new JButton(button3);
add(jb);
ImageIcon button4 = new ImageIcon("Off.jpg");
jb = new JButton(button4);
add(jb);
}
#Override
//prints on and off when detecting action comand from a jbutton
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
if (action.equals("On")) {
System.out.println("Yes Button pressed!");
ImageIcon button1 = new ImageIcon("On.jpg");
TicTacToe.a = 1;
}
else if (action.equals("Off")) {
System.out.println("No Button pressed!");
}
}
You're forgetting to call setIcon(...) on any button. As the AbstractButton API will tell you (this is the parent class of JButton), it is easy to change the icon of any button by simply calling its setIcon(Icon icon) method and pass in the new Icon. In the future, first go to the API as you'll learn much there, including methods that do exactly what you need.
Other suggestions: don't give your variables names that don't match what they are. For instance you're calling an ImageIcon variable "button1" as if it were a JButton, and that will confuse other coders and your future self. Instead why not call it `onIcon" or "offIcon", a name that makes the code self-commenting.
A major problem with your code, and one reason why as written, you can't make it work -- your JButton objects are assigned to local variables, variables that are only visible within the method that they were declared. If you want your JButton objects to be able to have there icons changed in different methods of the class, they must be declared at the class level, not at the method or constructor or deeper level.
I'm porting an existing application over to netbeans platform, and while I will probably change some of the existing dialogs to the new notify methods, some of the dialogs are quite complex (multiple panels etc) and I would rather not port them, at least not yet. I found out how to get the mainframe,
mainFrame = (JFrame) WindowManager.getDefault().getMainWindow();
But I have no idea what to use for the .getApplication().show()
public void configScoreboard() {
if (!in_race) {
if (CSBox == null) {
CSBox = new SBconfig(mainFrame, true);
CSBox.setLocationRelativeTo(mainFrame);
}
Sst01App.getApplication().show(CSBox);
}
}
The Sst01App of course does not exist in my new Netbeans Platform App and I can't seem to find the app (I think I tried all of the varaibles)
Found it under DialogDescriptor documentation after lots more searching...
https://ui.netbeans.org/docs/ui_apis/dide/index.html
Where I figured out how to create the custom dialog that I could decorate, The .show() method was still a problem, but I found the DialogDisplayer would work with the object I created. So done.
Dialog sb2Dlg = DialogDisplayer.getDefault().createDialog(sb2);
Still having lots of fun with borderless and full screen, but thats another topic.
class MyPanel extends javax.swing.JPanel implements java.awt.event.ActionListener {
//buttons, fields, labels, etc.
...
public void requestFocus () { //set focus for one components
myField.requestFocus ();
}
...
public void actionPerformed(final java.awt.event.ActionEvent ap) { // handling code for buttons
...
}
}
MyPanel mp = new MyPanel(); // create new MyPanel
Object [] options = { new JButton ("Choice 1"),
new JButton ("Choice 2")};
DialogDescriptor dd = new DialogDescriptor (mp,
"Text in title",
true,
options,
null,
DialogDescriptor.DEFAULT_ALIGN,
null,
mp); //create new modal DialogDescriptor with defined ActionListener
mp.requestFocus(); // set focus to component which was specified in MyPanel's requestFocus() method
TopManager.getDefault ().createDialog (dd).show (); //show dialog
I have a panel that contains a File Section button. The Button itself should load FileDialog() upon click. Upon calling FileDialog() constructor I figured out that it asks parent either Frame or Dialog while I was passing JPanel. The Panel itself is called in JOptionPane.showMessageDialog() method. How to make it possible? Code is given below:
JPanel pnlMain;
JButton btnPath;
pnlPath.add(btnPath);
//Click Event
btnPath.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("File Section Clicked..");
java.awt.FileDialog fd = new java.awt.FileDialog();
}
});
JOptionPane.showMessageDialog(null, pnlMain, "Settings", JOptionPane.PLAIN_MESSAGE);
I created a new Instance of JFrame and it worked:
FileDialog fd = new FileDialog(new Frame(),"My Settings",FileDialog.LOAD);
I want the user to be able to click a button and choose and image which'll be displayed on the screen.
This is the code I wrote. It doesn't seem to work:
uploadBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int retVal = fc.showOpenDialog(EditImage.this);
if(retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
try{
Image img = ImageIO.read(file);
if(img==null){
//TODO: THE FILE IS NOT AN IMAGE. ERROR
}
ImageIcon ic = new ImageIcon(img);
JLabel imageLabel = new JLabel(ic);
imagePreview.add(imageLabel);
}
catch(IOException ex){
//TODO: THE FILE COULD NOT BE OPENED.
}
}
}
});
imagePreview is a JPanel that I've got somewhere on the screen.
What am I doing wrong?
agree with other answers here is required to call container.revalidate() and (there is an Image, then to required) container.repaint()
but this logics is wrong, you couldn't, why to add/remove JComponent for showing another Image, there no reason for, you can to switch betweens ImageIcons in JLabel - JLabel.setIcon(file)
and there is another issue, Images can increasing used JVM memory, you have to call Icon/ImageIcon.flush() before is added to JLabel.setIcon(a few times mentioned here)
Is imagePreview already visible when you add the JLabel to it? If so, you can't just add components to a visible container; you have to revalidate it.
call imagePreview.revalidate(); imagePreview.repaint() after imagePreview.add(imageLabel);, that needed if you add components to visible container.