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...
Related
I have an assignment to show JFileChooser as part of a JFrame. So showing it as a dialog box is out.
I'm doing the most basic approach to adding it as a component to a yet invisible frame, and then the setVisible() call freezes instead of showing the frame.
What irks me the most is that one time out of ten the frame appears with the FileChooser just fine. This makes me think this is a concurrency issue.
Here's the minimal source code that still has the issue.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
class ApplicationFrame extends JFrame {
JFileChooser fileChooser;
public ApplicationFrame(String frameName) {
super(frameName);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
fileChooser = new JFileChooser();
fileChooser.setControlButtonsAreShown(false);
panel.add(fileChooser, BorderLayout.CENTER);
getContentPane().add(panel);
}
}
public class lab7{
public static void main(String args[])
{
ApplicationFrame windowForApplication = new ApplicationFrame("lab7");
windowForApplication.setSize(600,600);
windowForApplication.setVisible(true);
}
}
If you put a println after the final setVisible, it doesn't get called.
If you comment out panel.add(), the frame displays just fine.
What else should I do to display the file chooser?
What irks me the most is that one time out of ten the frame appears with the FileChooser just fine.
All Swing component should be created on the Event Dispatch Thread. So the GUI creating code should be wrapped in a SwingUtilities.invokeLater(...).
Read the section from the Swing tutorial on Concurrency for more information and an example of how this is done.
Your code (as is) actually works for me without problem. I'm using JDK7 on Windows 7, so it could be a version/platform issue. Again make sure the code executes on the EDT.
Also, class names ("lab7") should start with an upper case character. Doesn't matter if this is a SSCCE or not, be consistent.
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 ;)
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.
Using Swing on Java 6u16, WinXP SP3
Hello to all. I need some help, please, with the following case.
Basically I use a JTable inside a JScrollPane, that on the scrollPane I apply component orientation of right-to-left. The final result that I get is such that the table is indeed is attached to the right, but the header is placed to the left, when the scroll pane is bigger than the table width. This is happens only with custom table headers and AUTO_RESIZE_OFF on table columns (to get horizontal scrolling). Second (related) problem is with dragging the vertical grid lines to resize the columns - the header line moves to the left, when the table column's line moves to the right.
I have 2 test cases. The first uses the code from http://www.swebb99.f2s.com/GroupableHeader/. This is open source implementation of the table header that is used to group some sub-column headers.
Please add to main() in GroupableColumnExample.java:
frame.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
Second test case uses JIDE (www.jidesoft.com) implementation of nested table header for the same purpose and with the same results.
import java.awt.ComponentOrientation;
import javax.swing.*;
import com.jidesoft.grid.JideTable;
public class TestCase {
public static void main(String[] args) {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JideTable table = new JideTable(
new Object[][]{{"1", "2"}}, new String[]{"3", "4"});
//this line adds the custom header and the problem begins
table.setNestedTableHeader(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
frame.add(new JScrollPane(table));
//make frame bigger than needed to display the table
frame.setSize(200, 200);
frame.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
frame.setVisible(true);
}
}
Please help me to resolve this, as I did not find anything via Google and cannot resolve the issue myself.
I think I need to restate my question ...
I want to create a SIMPLE form application that edits certain areas of one very specific text file. Though I have some web development experience, I do not want to create a browser based application. Basically I want to give a Desktop application a try and I am looking for some help to get started including suggestions for the language of choice. The application should run on Mac OS X. Besides there's no restriction: Java, Cocoa, Python, even a some interactive shell script would be ok.
If you are interested in the details, continue to read here, but not that my question is not LaTex specific...:
I have an automatically generated report file that contains LaTex Code. Now I want to build a little application that creates a form field for every section and it's header. The document contains only a few hundred lines and the should work the following:
\section{ This is were the header text should go inside the document }
\normalsize{ This is where the normal text should go}
The header / normalsize pairs occur 5-6 times within the document. All I want is a little GUI that allows user to edit between the curly braces without seeing any TeX code. I know that there's LyX and other WYSIWYG approaches to LaTeX – I do not want to reinvent the wheel. I just want to protect the auto-generated code a litte from users and make it a little more comfortable to them.
EDIT:
here's my very first try. I guess I should use PlainDocument instead of directly sending it, but I´ll figure that out, since I got plenty of help from trashgod with the editor / Text Component links. The major problem is to single out the content from \section{} and \normalsize{} stuff. Probably I will some regexp here. I need to get a new text area for every appearance.
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileReader;
import javax.swing.*;
public class basicFrame extends JFrame {
// Declare Variables
JScrollPane bildlauf = new JScrollPane();
JTextArea txtfeld = new JTextArea();
public basicFrame() {
super();
// Main window
setTitle("ReportEditor");
setBackground(Color.LIGHT_GRAY);
// components
try {
File datei = new File("report.Rnw");
FileReader in = new FileReader(datei);
txtfeld.read(in, datei);
in.close();
} catch (Exception e) {
System.out.println("Error !");
}
// setLayout(new GridLayout(2,2));
// Scroll Shizzle
bildlauf.getViewport().add(txtfeld, null);
getContentPane().add(bildlauf, BorderLayout.CENTER);
//txtfeld.setSize(500,680);
//add(txtfeld);
//this.getContentPane().add(txtfeld);
// close
addWindowListener(new WindowLauscher());
}
// event handlers...
protected static final class WindowLauscher extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
//Fesnter erzeugen und anzeigen, die main Sache halt
basicFrame hf = new basicFrame();
hf.setSize(500, 700);
hf.setLocation(100, 100);
hf.setVisible(true);
}
}
Thx in advance for any suggestions!
The TeX on Mac OS X wiki recommends jEdit, which supports plugins. LaTeXTools might be a good start.
Addendum:
I do not want to reinvent the wheel.
All I want to do is create a form application.
Although these goals are somewhat contradictory, you can always parse the file and use a suitable JTextComponent for each editable section. Here's an overview of Using Text Components; see Text Component Features if you want to create your own editor kit, as discussed in Customizing a Text Editor.
Addendum: In addition to the tutorial, you might look at this text field layout example. Also, consider a two-column JTable, which would allow you to cleanly separate your document model from your form view.
Addendum: A few notes on your code.
Class names are usually capitalized, e.g. BasicFrame.
Don't extend JFrame if you're not changing it's behavior; JPanel is a good container for other components, and it can be displayed in a JFrame.
Always buid your GUI on the EDT.
Keep you view and model separate.