How come JLabel doesn't show underscore character? - java

For some reason JLabel doesn't show underscore symbol. Is there anything in particular I have to do for enabling such behavior?
Doesn't work in Windows, Linux, MacOS with Java 1.6.x

This is the code I used to see if this worked. Try running this on your machine.
import java.awt.*;
import javax.swing.*;
public class TestUnderscore
{
// Test routine.
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.getContentPane().setBackground(Color.yellow);
frame.getContentPane().add(new JLabel("Test_Underscore$$"));
frame.getContentPane().setLayout(new FlowLayout());
frame.setSize(450, 450);
frame.setVisible(true);
}
}

Does not work for me on Linux. Same issue for highlighted text in JTextArea. If line1 and line 2 contain underscores and both are highlighted, underscores in line 1 are not visible but underscores in line2 are. Changing alpha values of highlight color did not fix problem.
Found a fix - change the font. Both worked when I used Verdana 12pt.

Related

JFrame in full screen without undecorated

I am using Java8 on Windows machine developing with latest community edition of IntelliJ. To make JFrame full screen I find below solution where I faced one different behavior which I want to get verified.
Solution I took from JFrame full screen
As per the solution I need to put three below lines to make JFrame full screen:
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setVisible(true);
But in my project I have created a class AppFrame.java that extends JFrame. And in default constructor I set some basic properties like font etc and importantly visibility to true.
import javax.swing.*;
import java.awt.*;
public class AppFrame extends JFrame {
AppFrame() {
Font baseFont = new Font("Dialog", Font.PLAIN, 12);
setFont(baseFont);
setLocationRelativeTo(null);
setBackground(Color.WHITE);
setForeground(Color.black);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
And in class that extends AppFrame when I try to put above three lines (with or without setVisible, which is already coming from AppFrame) to maximize it get below error:
Exception in thread "main" java.awt.IllegalComponentStateException: The frame is displayable. at java.awt.Frame.setUndecorated(Frame.java:923)
As a part of solution (which I want to verify) - Experimentally I removed setVisible (true) from AppFrame.java and it worked, but this would be gonna impact all classes extending AppFrame, so I removed frame.setUndecorated(true); as well from my class and put back setVisible in AppFrame. And exception is gone. Also frame.setUndecorated(true); I believe removes title bar of JFrame.
Also, below is excerpt from javadoc of JFrame:
A frame may have its native decorations (i.e. Frame and Titlebar)
turned off with setUndecorated. This can only be done while the frame
is not displayable.
It would be great if someone can verify this behavior.
By design you have to invoke setUndecorated before and only before setVisible. So you have no other choice but to remove from base class invocation of setVisible and invoke it every time in children classes.
Modify the initializer to use parameters.
AppFrame() { should be changed to AppFrame(boolean undecorated, boolean visible) { then in the initializer add setUndecorated(undecorated); and setVisible(visible);
Completed Solution:
import javax.swing.*;
import java.awt.*;
public class AppFrame extends JFrame {
AppFrame(boolean undecorated, boolean visible) {
Font baseFont = new Font("Dialog", Font.PLAIN, 12);
setFont(baseFont);
setLocationRelativeTo(null);
setBackground(Color.WHITE);
setForeground(Color.black);
setLayout(new FlowLayout());
setExtendedState(JFrame.MAXIMIZED_BOTH);
setUndecorated(undecorated);
setVisible(visible);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
In regards to:
A frame may have its native decorations (i.e. Frame and Titlebar) turned off with setUndecorated. This can only be done while the frame is not displayable.
This is just stating that you have to do this before calling setVisible(true);. To determine if you can call setUndecorated safely, you can use if (!isDisplayable()) { ... }

Charset in JTextPane which using AdvancedRTFEditorKit

I'm having some problems with charset encodings. I'm using AdvancedRTFEditorKit (free closed source library: http://java-sl.com/advanced_rtf_editor_kit.html).
If I copy some special characters (ěščřžýáíé) from MS Word and paste them into sample delivered with AdvancedRtfEditorKit library, everything works fine. But if I do the same with my really simple SSCCE which uses AdvancedRTFEditorKit, then they appear as just rectangles. Do you know what I'm doing wrong?
This problem only occurs with MS Office products. LibreOffice works fine.
My SSCCE:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(350, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane pane = new JTextPane();
pane.setEditorKit(new AdvancedRTFEditorKit());
frame.add(pane);
frame.setVisible(true);
}
After many changes in my code I figured out there isn't any problem with my app. My problem was just running app directly from NetBeans IDE. I don't know why, but IDE somehow encode/decode interaction with OS.

How can I get my Image to be displayed using Java?

Well basically my image will not display, i'm almost certain it's my file path
(‪" C:\Users\Alex\Desktop\card.png" is what the image properties say is the file path but unless i put double slashes it confuses them for escape sequences. ) If someone has the answer it will be much appreciated. Here's my code:
import java.awt.*;
import javax.swing.*;
public class IDK extends JFrame {
public static void main(String args[]) {
new IDK();
}
public IDK(){
notsure();
}
public void notsure(){
setBounds(420,100,440,400);
setTitle("Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel label1 = new JLabel("Tell me something");
JLabel image = new JLabel();
label1.setText("New Text");
JTextField text = new JTextField("Insert text",30);
image.setIcon(new ImageIcon("C:\\Users\\Alex\\Desktop\\card.jpg"));
panel.add(label1,image);
panel.add(text);
add(panel);
validate();
panel.setBackground(Color.CYAN);
setVisible(true);
}
}
There is no problem with using "\" so long as it's escaped, as you have done, if your prefer you can use / instead and on Windows the JRE will correct for it.
How ever, you should be adding the image separately, for example...
image.setIcon(new ImageIcon("C:\\Users\\Alex\\Desktop\\card.jpg"));
panel.add(label1);
panel.add(image);
The way you are doing it now assumes that image is a layout constraint for label1, which it isn't.
You should try and avoid using absolute paths and learn to use relative paths and/or embed the resources within the application context, this makes it easier to locate these resources at runtime.
Create a folder in your project and call it i.e. 'resources' and put your image in that folder. This will ensure that given image is on your classpath and can be easily accessed.
Then you can just do :
new ImageIcon("resources/card.jgp")
Problem with accessing outside resources is that special characters needs to be escaped and also if you export the project and give it to someone else, he/she will not have the image required by software ;)

Applying a font to JTextArea crashes the gui?

The following code works when the font line is commented out, and no GUI appears at all when the line is included. From what I can tell its formatted properly but its crashing the GUI. What could cause this?
public class TestCode extends JFrame{
JTextArea jta;
public TestCode(){
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel();
jta = new JTextArea(20, 30);
jta.setFont(new Font("Courier New", Font.PLAIN, 12)); // This line crashes
content.add(jta);
add(content);
pack();
setVisible(true);
}
public static void main (String [] args){
TestCode run = new TestCode();
}
}
I'm beginning to suspect that it has something to do with my system fonts? I have installed extra fonts, perhaps that affects Java's ability to retrieve them?
EDIT:
Just to clarify, there are no errors when I run this program. The GUI never opens and the IDE gets slow and buggy as if I were running an infinite loop. The program must be terminated via the IDE (because no GUI shows to close).
It works fine for me using 1.6 and 1.7.
Some suggestions:
1) Force the EDT for your Swing app as follows:
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
TestCode run = new TestCode();
}
});
}
Further reading:Concurreny in Swing
2) Place your JTextArea in a JScrollPane, and add the scroll pane to the panel, not the text area itself:
content.add(new JScrollPane(jta));
The problem was caused by an excessive number of downloaded fonts on my system. I had previously downloaded a Font package which contained a few thousand additional fonts which caused the IDE to spend an unnecessarily long amount of time trying to find the right font I presume.
Deleting the unused additional fonts solved the problem and now this code works fine.

How to wrap text around components in a JTextPane?

I don't understand the wrapping behavior in a JTextPane. If I insert a short text, then a JComponent and then again the short text I can see the inserted stuff in one line if the frame is large enough of course. But if the text is much longer so that it takes several lines the component is always placed in a new line.
I have recognized that after a component has been inserted into a JTextPane its text gets longer by one character. So if a component is considered by a JTextPane as a character why doesn't it behave like a character? May it depend on the java version? I use Java(TM) SE Runtime Environment (build 1.7.0-b147)
Below is my code (instantiate the variable currentText with shortText/longText to reproduce the mentioned behavior):
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
String shortText = "one two three four five six seven";
String longText = "A text component that can be marked up with attributes that are represented graphically. You can find how-to information and examples of using text panes in Using Text Components, a section in The Java Tutorial. This component models paragraphs that are composed of runs of character level attributes. Each paragraph may have a logical style attached to it which contains the default attributes to use if not overridden by attributes set on the paragraph or character run. Components and images may be embedded in the flow of text.";
String currentText = shortText;
try {
// insert text before the component
textPane.getDocument().insertString(textPane.getDocument().getLength(), currentText,
new SimpleAttributeSet());
textPane.setSelectionStart(textPane.getDocument().getLength());
textPane.setSelectionEnd(textPane.getDocument().getLength());
JComboBox component = new JComboBox();
component.setMaximumSize(component.getPreferredSize());
textPane.insertComponent(component);
// insert text after the component
textPane.getDocument().insertString(textPane.getDocument().getLength(), currentText,
new SimpleAttributeSet());
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
textPane.setEditable(false);
frame.add(new JScrollPane(textPane));
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
That strange behavior seems to happen due to the content type you set. Try removing this line:
textPane.setContentType ( "text/html" );
and you will see that everything works fine after that. I am not sure why it happens - might be either some rendering bug or just an intended behavior.
P.S. I don't think that using Swing components inside text pane (whatever the reason is) is a good option. But that is just my opinion...

Categories

Resources