Mittwoch, 24. Oktober 2007

java.net.MalformedURLException: unknown protocol: c

This error message is quite hard to understand.
It often happens, when a File or it's path contains whitespaces. A quick solution is, to add "file:/" to the Filename.

For example:

String f = new String("test.xml");
// this can cause the error:
readFile(f); 
// this will work fine:
readFile("file:///"+f);

Mittwoch, 17. Oktober 2007

Comparing a Float to another Float is not working

Recently I changed my code, so now I am not anymore working with floats, but with Floats.

Somewhere in my code, I used to compare the float values with the "==" Operator. But now this won't work anymore.

Float is not the same as a float. Float is a Wrapper for floats. Because of this, you should compare two Float values with the compareTo method. Using the "==" Operator, you are comparing the Float Object and not the value.

Check out this code:

 

public class CompareFloatsExample {

Float f = new Float(20);

Float f1 = new Float(20);

public CompareFloatsExample(){
System.out.println(new Float(20) == new Float(20));
if (f == f1){
printEqual();
}
else {
printNotEqual();
}
if (f.compareTo(f1) == 0){
printEqual();
}
else {
printNotEqual();
}
}
public void printEqual(){
System.out.println("the value of f ("+f+") is equal to the value of f1("+f1+")");
}
public void printNotEqual(){
System.out.println("the value of f ("+f+") is not equal to the value of f1("+f1+")");
}
/**
* @param args
*/
public static void main(String[] args) {
new CompareFloatsExample();

}

}







Montag, 8. Oktober 2007

How to make a JPanel transparent?

The easy way is to change the alpha of the background Color:


public class TransparentPanel extends JPanel {


public TransparentPanel(){
}
/**
* Set the Transparency of the background color in %
*/
public void setTransparency(int d){
int newValue = (int) (d*2.55);
if (getBackground() != null ){
setBackground(new Color(getBackground().getRed(),getBackground().getGreen(),getBackground().getBlue(),newValue));
}
if (getParent() != null){
getParent().repaint();
}
}
public void setTransParent(){
setTransparency(100);
}
/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
final TransparentPanel p = new TransparentPanel();
p.setBackground(Color.RED);
p.setPreferredSize(new Dimension(200, 100));
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(p,BorderLayout.NORTH);
final JSlider slider = new JSlider(0,100,1);
frame.getContentPane().add(slider,BorderLayout.SOUTH);
slider.addChangeListener(new ChangeListener(){

@Override
public void stateChanged(ChangeEvent e) {
p.setTransparency(slider.getValue());
}
});
slider.setValue(100);
frame.setSize(200,200);
frame.setVisible(true);

}

}