Java Applet In Web Page Does Not Respect Set Look And Feel - java

I am trying to set the look and feel (LAF) of a Java applet that is used via a web browser. I wish to set the system default LAF, but when loaded in a browser, the applet returns to the Metal LAF. When I run it as a stand-alone applet, the LAF is applied correctly. The only item I am showing the user is a JFileChooser. I have tried a number of methods to overcome this including:
1) Override the applet's start() method:
#Override
public void start() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
System.out.println("LOOK AND FEEL SET!");
}
catch (Exception ex) {
System.out.println(ex);
}
}
2) Set it in the static initializer of the applet class:
static {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
System.out.println("LOOK AND FEEL SET!");
}
catch (Exception ex) {
System.out.println(ex);
}
}
3) Set it in the constructor of the applet:
public MyApplet() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
System.out.println("LOOK AND FEEL SET!");
}
catch (Exception ex) {
System.out.println(ex);
}
}
I am using Java 6, but targeting Java 5 on Windows. In every case, LOOK AND FEEL SET! gets printed to the console, so I know that it set it without throwing an exception. This happens irrespective of browser (using Firefox 3.6 and IE7). Why is it doing this and how can I get it to respect the LAF I designate?

I used this code in an applet I developed recently:
public void init() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
// Just accept the default L&F
}
SwingUtilities.updateComponentTreeUI(this);
super.init();
// Now add components...
}
See also Look-and-feel of an applet window changes on subsequent displays (I have not solved this problem because my applet did not need to open pop-up windows.)

So I tried finnw's answer and marked it accepted without realizing that I had also made some other modifications to my code. When I was cleaning out code I removed my mods and left finnw's, but then it was broken again.
These were the changes that had made that worked:
JFileChooser chooser = new JFileChooser();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(chooser);
}
catch (Exception ex) {
System.out.println(ex);
}
So what I ended up doing here is setting the look and feel for the file chooser outright, instead of trying to force the LAF for the whole applet. It's kind of a hack, but the file chooser is the only part of the UI that the user even sees anyway.

There does appear to be one obscure mistake that virtually every applet ever makes. Swing (also AWT components) is being used off the AWT Event Dispatch Thread (EDT). The applet threading model is a little eccentric.
This is the one time when invokeAndWait should be used with this extreme boilerplate:
#Override public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() {
initEDT();
}});
} catch (java.lang.InterruptedException exc) {
Thread.currentThread().interrupt();
} catch (java.lang.reflect.InvocationTargetException exc) {
throw new Error(exc.getCause());
}
}

Related

How to implement your own efficient OS listener?

How to create your own listener that listens to the OS efficiently in Java? For example like the ActionListener in Swing, that reacts to button clicks.
I want to make a program that logs the users clipboard, but I don't want to use a loop like this:
while (flag)
{
Transferable t = Toolkit.getDefaultToolkit()
.getSystemClipboard()
.getContents(null);
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor))
{
try
{
String text = (String) t
.getTransferData(DataFlavor.stringFlavor);
System.out.println(text);
}
catch (UnsupportedFlavorException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
Thread.sleep(1000);
}
I want the processor only to work when the clipboard changed and not check every second if that is the case.
Secondly I found a Method that might work
this.clipboard = Toolkit.getDefaultToolkit()
.getSystemClipboard();
this.clipboard.addFlavorListener(new FlavorListener()
{
#Override
public void flavorsChanged(FlavorEvent e)
{
// work with the clipboard contents
}
});
But still I need a strange while loop that consumes processor time to keep the program active.
I think that I should use wait and notfiy, but I'm not sure how.

Create shortcut with minimized window

Good morning, I have a Java code using JShortcut, the problem is I can not create the shortcut with the minimized window, try looking for properties as windowstyle, but find nothing.
Code.
public void createDesktopShortcut() {
try {
link.setFolder(JShellLink.getDirectory("desktop"));
link.setName("ie");
link.setPath(filePath);
//windowstyle = 7
link.save();
} catch (Exception ex) {
ex.printStackTrace();
}
}
How can I add this option?

using java awt robots on browser

Trying to use java awt robots in the deployed application, initially got headless exception
thought changing headless property will do, but still the issue exists
try {
Field defaultHeadlessField = java.awt.GraphicsEnvironment.class.getDeclaredField("defaultHeadless");
defaultHeadlessField.setAccessible(true);
defaultHeadlessField.set(null,Boolean.FALSE);
Field headlessField = java.awt.GraphicsEnvironment.class.getDeclaredField("headless");
headlessField.setAccessible(true);
headlessField.set(null,Boolean.FALSE);
System.out.print(GraphicsEnvironment.isHeadless());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
try {
Robot robot = new Robot();
but now it says
java.awt.HeadlessException
at sun.java2d.HeadlessGraphicsEnvironment.getDefaultScreenDevice(HeadlessGraphicsEnvironment.java:64)
basic use case is to simulate keypress(0) on browser window, need some help in solving this issue.

JTextPane Insert Icon Troubleshooting

public void valueChanged(TreeSelectionEvent event) {
//Add images depending on selection.
String selection = navigation.getLastSelectedPathComponent().toString();
if (selection == "Sigma") {
try {
Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon("sigma.png"));
document.insertString(document.getLength(), "ignored text", style);
} catch (BadLocationException e){
}
}
}
Hey all, so I've debugged everything and everything is working correctly except for the ACTUAL INSERTION of the icon.
Can anyone explain to me why this isn't working? I have a try and catch statement, yet it still seems to fail on me.
PS: Don't ask for more code, my code compiles perfectly without this code. document is a global variable, and, I used styling to insert the icon (correct me if I'm wrong).
You have one problem:
selection == "Sigma"
that's not how you compare strings, change it to:
"Sigma".equals(selection)
Also don't swallow the exception:
} catch (BadLocationException e) {
//do something here
e.printStackTrace();
}

Changing Swing progress bar look and feel

I keep trying to chang the UIManager to make these stupid looking green squares go away. how do i change the look and feel of this to the user? Is it system dependent? Someone else who was compiling my code had a constant gradient. Ideally, it would just be a solid square, as opposed to smaller blocks.
Thanks
Have you tried setting it to the system's (user's) look and feel?
The easiest way to set the look and feel is by launching the GUI after calling:
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
// ...
}
With that said, the above appears to be the Windows XP theme and may indeed be the system (user) theme. I generally stay away from custom themes in GUIs unless there is a very good reason (e.g., customer/user requirement).
That is to say, the above code makes it system dependent, which is good because it matches the user's expecations.
"These stupid looking green squares" are element of Windows XP's Look nad Feel. If you want them to look different, you can change Look and Feel for this particular component.
Just use below workaround:
try {
javax.swing.UIManager.setLookAndFeel(/* Look and Feel for your JProgressBar*/);
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
MyProgressBar = new javax.swing.JProgressBar();
try {
javax.swing.UIManager.setLookAndFeel(/* Previous, main Look and Feel */);
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
I'm using this code for giving JFileChooser another look and it works perfectly.
You just change Look and Feel before creating component, and restoring previous one, just after that creation.
Edit
Code below change the L&F of entire JFrame.
static Main m;//Reference to JFrame to be updated
static String maxOSLookAndFeel = "ch.randelshofer.quaqua.QuaquaLookAndFeel";//Package of particular L&F
private void MacOSLFjMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MacOSLFjMenuItemActionPerformed
// TODO add your handling code here:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(maxOSLookAndFeel);
SwingUtilities.updateComponentTreeUI(m);
m.validate();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}//GEN-LAST:event_MacOSLFjMenuItemActionPerformed
Secundo:
In my opinion (googled a lot and by expirience) it's impossible to affect only one JComponent while you attach a new L&F. You change your L&F in entire JFrame or you can Write your own Swing Component.
Another way to achive your goal is studying java source code and find place where JProgressBar image is beeing added to component and override this method by extending JProgressBar.
A comprehensive description of Java look and feel could be found by Sun Java document, here: Java, Look and Feel Design Guidelines in pdf.

Categories