java JFileChooser how to temporarily disable file selection window - java

Is there a way how to temporarily disable file chooser in the JFileChooser window?
I created custom preview JPanel and I need the next file selection to be made only after the file preview is done/created (it created image from Wavefront OBJ files when such obj file is selected in the file chooser window).
Maybe some sort of disabling the whole file selection window part?
EDIT:
I was searching around here a bit more and found post Start a JFileChooser with files ordered by date. Now if I understood it right, then according to it, this piece of code should in fact enabling access to FilePane inside the JFileCHooser (of course, I downloaded the SwingUtils.java class first):
JTable table = SwingUtils.getDescendantsOfType(JTable.class, fileChooser).get(0);
But when I do that, I got error in NetBeansIDE saying: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Does anyone know why?
I also found post How to disable file input field in JFileChooser?, according to which this piece of code accessing the JFileChooser's textfield showing the selected file name:
import java.awt.Frame;
import java.lang.reflect.Field;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.plaf.metal.MetalFileChooserUI;
public class FileChooser {
public static void main(String[] args) throws Exception{
Frame f = new JFrame();
JFileChooser jFileChooser = new JFileChooser();
MetalFileChooserUI ui = (MetalFileChooserUI)jFileChooser.getUI();
Field field = MetalFileChooserUI.class.getDeclaredField("fileNameTextField");
field.setAccessible(true);
JTextField tf = (JTextField) field.get(ui);
tf.setEditable(false);
tf.setEnabled(false);
jFileChooser.showDialog(f, "Select");
f.dispose();
}
}
So, by inspecting all available fields I found out there is one called "filePane". So I took a risk and try to imitate the above code just with a few changes so that the FilePane would be targeted instead like this:
Field fieldB = MetalFileChooserUI.class.getDeclaredField("filePane");
fieldB.setAccessible(true);
FilePane filePane = (FilePane) fieldB.get(ui);
filePane.setEnabled(false);
I thought the code above would disable the file selection part of the JFileChooser window, but it did absolutely nothing, unfortunately.

So after a while I've solved it myself by playing further with the above code ending up with this functioning piece below:
FilePane filePane = SwingUtils.getDescendantsOfType(FilePane.class, fileChooser).get(0);
filePane.setEnabled(false);//<- this line doesn't work, but I'll leave it here so others know
filePane.setVisible(false);

Related

How do I add a java program to a weebly site?

I'm experimenting with Weebly, and I'm currently trying to add an arbitrary swing program to the Weebly editor. I have tried two approaches thus far, as shown here:
1: (Note: - replaces < and >)
-embed height=400 width=400 src="siteName/uploads/someNumbers/testapplet.class"--/embed-
2: (Same substitution as above)
-applet codebase="siteName/uploads/someNumbers" code="testapplet.ckass" width=400 height=400--/applet-
Upon publishing and viewing the page, the first one says I need a plugin to display the content, and the second one says my security preferences won't let me run java on the site, whereas I can run java pretty much everywhere else just fine.
What should I do to make this work? This could include some of the following:
Modifying my program (i.e. the java code itself)
Modifying how I upload the program (i.e. .class vs .jar)
Modifying how I display the program (i.e. the actual -applet- or -embed-)
For reference, here is the java code- just a basic JButton and JLabel, with the JLabel's value increasing upon each click of the button:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TestApplet extends JApplet
{
static int x = 0;
static JLabel l = new JLabel(x+"");
public void init()
{
setLayout(new FlowLayout());
JButton b = new JButton("Button");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
x++;
l.setText(x+"");
}
});
add(b);
add(l);
}
}
Sign in to weebly and click on the edit button next to your site name
On the "Elements" tab on the top, go to "Multimedia" and drag a file element onto your page.
Follow directions to upload your .class file. Name should be lowercase.
Hit the publish button and go to your published page.
Remember your .class file? Right-click on it and copy the link address or link location.
Go back to editing your weebly page.
On the "Elements" tab, go down to "More" and drag in the "Custom HTML" element.
Click to edit the custom HTML element- this is where we are going to put our applet code.
If my link location to my .class file was http://www.johndoe.com/uploads/3/3/2/6/3326331/countme.class, my applet code would read:
<applet codebase="http://www.johndoe.com/uploads/3/3/2/6/3326331" code="countme.class" width=something height=something></applet>
The idea is that the codebase tells the browser where to look for a .class file and the code itself tells it whick .class it is.
10. Publish again, and your applet should appear.
I haven't tried it personally, but I had a chat with a support support staff and they affirmed this method.
All the best!

JFrame and JOptionPane are not clear

Whenever I execute JFrame of JOptionPane this is how its displayed. I have the latest version of eclipse and JDK. I use Windows 8. What might be the issue?!
public static void main(String args[]){
String disp="2.40894673";
JOptionPane.showMessageDialog(null, disp);
}
the problem occurs in all the codes. This is a sample code I wrote th problem occurs in this too.
Update your graphics and card drives.
If you're using Mac then as I found in this
page
look at:
Preferences > Fonts > Text antialiasing
If you're using Windows then from this
answer be sure it's checked:
Control Panel → Appearance and Personalization → Display → Adjust ClearType text
Then check your font settings for windows, menu items and dialog
boxes:
Control Panel → Appearance and Personalization → Personalization → Window Color → Advanced appearance settings
Most of times just step 1 solves the issue.
Try them and if worked let me know.
UPDATE
Try turning off ClearType from Control Panel as indicated in step 3,
as said in this answer
Also try deleting FNTCACHE.DAT from System32 as mentioned in
this other answer.
Also as said in this
forum
try to change your screen resolution, and also reducing Hardware acceleration.
Let me know if any of them solved the issue.
I've written a code for the same, and it works fine.
Program:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SDialog
{
public static void main(String[] args)
{
String disp="2.40894673";
// create a jframe
JFrame frame = new JFrame();
// show a joptionpane dialog using showMessageDialog
JOptionPane.showMessageDialog(frame,disp);
System.exit(0);
}
}

Simple Java GUI, cards not appearing

import javax.swing.*;
public class SlideShow {
JFrame slide = new JFrame("Slide Show");
public SlideShow(){
slide.setSize(300,400);
slide.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
slide.setVisible(true);
slide.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel label = new JLabel(new ImageIcon("Images/picture1"));
panel.add(label);
slide.add(panel);
}
public static void main(String[] args){
SlideShow slide = new SlideShow();
}
}
I have to create a simple Java GUI that displays some cards. First, I just wanted to test it by displaying one card. For some reason I can't seem to figure out why nothing is being displayed.
You haven't actually used a proper file name "Images/picture1". Should be something like "Images/picture1.png" with the file format
Also image files, generally should be read from the class path, if you plan on having them embedded to the program. To do so, you will first need to put the file in the class path. With most IDE build configurations it's as simple as placing the image in the src. So
ProjectRoot
src
images
picture1.png
Then you would read it like
new ImageIcon(getClass().getResource("/images/picture1.png"));
A better approach would be to use ImageIO.read(). If the file path is incorrect, it will throw an exception, so you know where you're going wrong
Image image = ImageIO.read(getClass().getResource("/images/picture1.png"));
ImageIcon icon = new ImageIcon(image);
You will need to put it in the try/catch block
Also do what codeNinja said about the setVisible() after adding component. Also preferably pack() the frame, instead of setSize()
You need to set the Frame visible after you add all necessary components to it. Move slide.setVisible(true); Down to the bottom of the constructor like this:
...
slide.add(panel);
slide.setVisible(true);
Alternatively you can add slide.revalidate(); at the bottom of your constructor.

JFileChooser.showSaveDialog: All files greyed out

I'm trying to use the JFileChooser to get files for loading and saving. The dialog that comes up with openFileDialog() works fine, but when I use the saveFileDialog() method, the dialog window has all the file names greyed out. This happens with or without a FileFilter (my example includes one to better show what I'm seeing).
Here's a minimal program to illustrate:
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Temp extends JFrame {
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
chooser.setFileFilter(filter);
frame.setVisible(true);
chooser.showOpenDialog(null);
chooser.showSaveDialog(null);
}
}
Here's what I see in the Open dialog:
Open Dialog
Here's what I see in the Save dialog:
Save Dialog
Despite being greyed out, all the files in the save dialog are selectable.
I'm on Mac/Mountain Lion and Java 7 if it matters.
Is this expected behavior? Is there a way to change this?
(Edit: per comments by MadProgrammer + trashgod below, this appears to be consistent with the look + feel of other (native) Mac apps)
I'm looking for the .txt files to be displayed in the "normal" color while in the save dialog.
That's controlled by the FileChooserUI delegate specific to a particular Look & Feel, e.g. AquaFileChooserUI on Mac OS X. You can use a different L&F, (laboriously) write your own FileChooserUI, or develop a custom File Browser GUI.
What I ended up doing was to use:
JFileChooser chooser = new JFileChooser(...);
chooser.showDialog(myFrame, "Save");
My save dialog looks like a save dialog, and the FileFilter greys out only files that fail its test.
Mmm... I think, that show dialogs the way you do is not the best way
chooser.showOpenDialog(null);
chooser.showSaveDialog(null);
I think that could be generating a conflict. Why don't you try to use a JFrame to help you? Try with this piece of code, just to know if the problem is the saveDialog. Myabe then you can adapt it to your programming requirements.
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
As a matter of fact, you could try using the setLookAndFeel, I remember I had this issue working with my Macbook Pro.

Malformed Farsi characters on AWT

When I started programming with the JDK6, I had no problem with text components, neither in AWT nor in Swing.
But for labels or titles of AWT components I do have a problem. I can't display Farsi characters on AWTs components (in Swing I type them into the source code).
Here's my sample code:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Properties;
public class EmptyFarsiCharsOnAWT extends JFrame{
public EmptyFarsiCharsOnAWT() {
super("مثال");
setDefaultCloseOperation(3);
setVisible(rootPaneCheckingEnabled);
}
public static void main(String[] args) throws AWTException, IOException {
JFrame jFrame = new EmptyFarsiCharsOnAWT();
MenuItem show ;
// approach 1 = HardCoding :
/*
show = new MenuItem("\u0646\u0645\u0627\u06cc\u0634");
*
*/
// approach 2 = using simple utf-8 saved text file :
/*
BufferedReader in = new BufferedReader(new FileReader("farsiLabels.txt"));
String showLabel = in.readLine();
in.close();
show = new MenuItem(showLabel);
*
*/
// approach 3 = using properties file :
FileReader in = new FileReader("farsiLabels.properties");
Properties farsiLabels = new Properties();
farsiLabels.load(in);
show = new MenuItem(farsiLabels.getProperty("tray.show"));
PopupMenu popUp = new PopupMenu();
popUp.add(show);
// creating Tray object
Image iconIamge = Toolkit.getDefaultToolkit().getImage("greenIcon.png");
TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp);
SystemTray tray = SystemTray.getSystemTray();
tray.add(trayIcon);
jFrame.setIconImage(iconIamge);
}
}
These three approaches all work when run with an IDE, but when I make a JAR containing this class (by means of NetBeans > project > clean & build), I don't see the expected characters (it shows EMPTY/BLANK SQUARES)!
Note:
It seems I can not attach anything, so the contents of the text file would be this: نمایش and the contents of properties file:
#Sun May 02 09:45:10 IRDT 2010
tray.show=نمایش
And I think I have to let you know that I posted this question a while ago on SDN and "the Java Ranch" forums and other native forums and still I'm waiting...
By the way I am using latest version of Netbeans IDE...
I will be grateful if anybody has a solution to these damn AWT components never rendering any Farsi character for me...
I suspect that this is platform related. Your example appears to work on my platform using approach 1 in either Netbeans or the command line; I didn't try the other approaches.
There might be a disparity between the IDE and the command line with regard to the default character encoding. I've noticed that NetBeans, Eclipse and many consoles can be set to something other than the platform default. Here's code to check:
System.out.println(System.getProperty("file.encoding"));
System.out.println(Charset.defaultCharset().name());
You might look at this related question, too.
Addendum: Note show string changed to match the JFrame title for comparison. The title and menu look the same from NetBeans' Run > Run Project as well as via these command lines:
$ java -cp build/classes EmptyFarsiCharsOnAWT
$ java -jar dist/test6.jar
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class EmptyFarsiCharsOnAWT extends JFrame{
public EmptyFarsiCharsOnAWT() {
super("مثال");
setDefaultCloseOperation(3);
setVisible(rootPaneCheckingEnabled);
}
public static void main(String[] args) throws AWTException, IOException {
JFrame jFrame = new EmptyFarsiCharsOnAWT();
MenuItem show ;
// approach 1 = HardCoding :
show = new MenuItem("\u0645\u062b\u0627\u0644");
PopupMenu popUp = new PopupMenu();
popUp.add(show);
// creating Tray object
Image iconIamge = Toolkit.getDefaultToolkit().getImage("image.jpg");
TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp);
SystemTray tray = SystemTray.getSystemTray();
tray.add(trayIcon);
jFrame.setIconImage(iconIamge);
}
}
The most exciting part of your reply was:
"$ java -jar dist/test6.jar" !
Does it really shows the real characters (just like the frame title)?!
and not boxes or garbage ?
I'm sorry if I believe it hard, because the only problem in my developing work with Java took such long without any answer nor from searching, nor asking in forums is this!
So, what can I do? what font should I use? Unfortunately I'm not so familiar with fonts, until now I've just used global fonts in Java (Serif,SansSerif,etc.) and only modified their size or style, but after you suggest I examined several Persian ttf fonts through these codes:
File fontFile = new File("F_JADID.TTF");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
show.setFont(font.deriveFont(15f));
but just boxes was the result! (just using HardCoding)
I think i should mention that my envirounment is win xp and i have this problem not only in my machine, but another running xp os too. And I'm using jdk6u17.
I can be agree with you in suspecting the fonts, because encoding problem (in my experience) appears with question mark, but garbage or empty boxes related to rendering characters.
But still i have the problem, just like the first day :(
What font you use and another question i encountered is:
Why swing doesn't have any problem without specifying the font, but AWT.
Addendum: Thanks to Oscar Reyes in this page for giving this link and thanks to StackOverflow :)
They saved me! from this section i should quote:
An application using peered AWT components can only use logical font names.
and from this section should quote:
For applications using AWT peered components, Sun's JREs select fonts for Chinese, Japanese, or Korean only when running on host operating systems localized for these specific languages
Yes, you guess right! by setting the OS locale to Farsi, i got the right result.
but i still should research and see how is it possible to have the right result by not setting the right locale, from that article.
I will explain how, when i got the result, but still will listen to here. wish me luck.

Categories