I'm working on a Java Swing application. I have a JTextArea inside a JScrollPane inside a JTabbedPane inside a JPanel. I can type in the JTextArea, and every key on my keyboard has the desired effect, except the enter key.
Tabs and spaces work fine. When I press the enter key, then type to the end of the line with word wrap enabled, the line is broken where I typed the enter key, leading me to believe that the issue is with how the JTextArea is displaying the text. I'm giving the JTextArea a new HTMLDocument. Note that when I do not give the JTextArea a new HTMLDocument, the enter key works perfectly well.
Simple code reproducing the problem:
import javax.swing.*;
import javax.swing.text.html.HTMLDocument;
import java.awt.*;
public class Driver extends JFrame {
public Driver() {
setLayout( new GridLayout( 1, 1 ) );
JTabbedPane tabbedPane = new JTabbedPane();
add( tabbedPane );
JTextArea textArea = new JTextArea( new HTMLDocument() );
textArea.setLineWrap( true );
JScrollPane scrollPane = new JScrollPane( textArea );
tabbedPane.addTab( "No enter key!", scrollPane );
pack();
getContentPane().setVisible( true );
setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
setSize( 640, 480 );
setVisible( true );
setFocusable( true );
}
public static void main( String[] args ) {
new Driver();
}
}
JTextArea doesn't understand HTMLDocument - it is not intended for styled documents. You will have to use JTextPane with an HTMLEditorKit so it knows it is HTML. For some reason, you can't supply your own document, but if you get the one from the component it works OK.
final HTMLEditorKit htmlKit = new HTMLEditorKit();
final JTextPane textPane = new JTextPane( );
textPane.setEditorKit(htmlKit);
textPane.setEditable(true);
JScrollPane scrollPane = new JScrollPane( textPane );
Document doc = textPane.getDocument();
System.out.println(doc.getClass().getName()); // It's an HTML Document
Related
I've run into a problem with JTextPane. The code I am working with sets a number of font attributes, such as BOLD, ITALIC, etc. But if the initial text ends with a single linefeed, and the user clicks on the last line, or is sent to the last line, the default font settings appear for any additional text the user types.
Specifically, this text works as I would expect: jTextPane.setText(String.format("Test This"));.
This text does not:
jTextPane.setText(String.format("Test This%n%n%n"));
I think that JTextPane may consider this to be a new paragraph.
If so, I would like to either
a.) Know how to set a universal font that applies across the entire JTextPane instance's paragraphs.
or
b.) tell the JTextPane instance to consider all of its editable area to be one paragraph.
Here is a toy program to show you what I mean. If you run this, and start typing at the end of the text the font will be whatever the default is for your Swing implementation.
I have also tried setting the document model of the JTextPane and using a Font instance in the JTextPane constructor. The results are the same.
Another alternative is to use a JTextArea instance instead, but this is very complex code and I hesitate to make a change that may break some other area of the application than the one I am working in.
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
public class JTextPaneExampleOne {
public static void main(String args[]) {
JFrame frame = new JFrame("JTextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
JTextPane pane = new JTextPane();
String welcomeString = String.format("Welcome%n%n%nStranger!%n%n%n");
pane.setText( welcomeString );
pane.invalidate();
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setBold(attributeSet, true);
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.red);
pane.setSelectionStart( 0 );
pane.setSelectionEnd( pane.getText().length() );
pane.setParagraphAttributes( attributeSet, true );
pane.setSelectionStart( pane.getText().length() );
pane.validate();
JScrollPane scrollPane = new JScrollPane(pane);
cp.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
a.) Know how to set a universal font that applies across the entire JTextPane instance's paragraphs.
In this case, you might be able to use JTextPane#setLogicalStyle(Style):
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JTextPaneExampleOne2 {
public Component makeUI() {
JTextPane pane = new JTextPane();
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style body = pane.getStyledDocument().addStyle("body", def);
StyleConstants.setBold(body, true);
StyleConstants.setItalic(body, true);
StyleConstants.setForeground(body, Color.RED);
pane.setLogicalStyle(body);
String welcomeString = String.format("Welcome%n%n%nStranger!%n%n%n");
pane.setText(welcomeString);
// SimpleAttributeSet attributeSet = new SimpleAttributeSet();
// StyleConstants.setBold(attributeSet, true);
// StyleConstants.setItalic(attributeSet, true);
// StyleConstants.setForeground(attributeSet, Color.RED);
//
// pane.setSelectionStart(0);
// pane.setSelectionEnd(pane.getText().length());
// pane.setParagraphAttributes(attributeSet, true);
// pane.setSelectionStart(pane.getText().length());
return new JScrollPane(pane);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame("JTextPane Example");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new JTextPaneExampleOne2().makeUI());
f.setSize(400, 400);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
I have a paint-like project, in which I recently added a JSpinner, but after researching how to add it to the JFrame, it ends up looking like this:
but I would like it to look like this:
how would I accomplish this? Thanks in advance.
P.D: The code used to create the current project is this:
public View( final String title ){
super( title );
}
public void init()
{
canvas = new Canvas();
menuManager = new MenuManager();
toolBarManager = new ToolBarManager( JToolBar.VERTICAL );
spinnerManager = new SpinnerManager();
JPanel subPanel = new JPanel( new FlowLayout() );
subPanel.add( menuManager );
subPanel.add( spinnerManager );
add( BorderLayout.CENTER, canvas );
add( BorderLayout.NORTH, menuManager);
add( BorderLayout.EAST, toolBarManager );
setDefaultCloseOperation( EXIT_ON_CLOSE );
App.getInstance().addDrawingListener( this );
canvas.init();
}
Simply give the top JPanel an appropriate FlowLayout: new FlowLayout(FlowLayout.LEADING))
// Fig. 14.6: LabelFrame.java
// Demonstrating the JLabel class.
import java.awt.FlowLayout; // specifies how components are arranged
import javax.swing.JFrame; // provides basic window features
import javax.swing.JLabel; // displays text and images
import javax.swing.SwingConstants; // common constants used with Swing
import javax.swing.Icon; // interface used to manipulate images
import javax.swing.ImageIcon; // loads images
public class LabelFrame extends JFrame
{
private JLabel label1; // JLabel with just text
private JLabel label2; // JLabel constructed with text and icon
private JLabel label3; // JLabel with added text and icon
// LabelFrame constructor adds JLabels to JFrame
public LabelFrame(){
{super( "Testing JLabel" );
setLayout( new FlowLayout() );
// JLabel constructor with a string argument
label1 = new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
add( label1 );
//JLabel constructor with string, Icon and alignment arguments
Icon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );
label2 = new JLabel( "Label with text and icon", bug,
SwingConstants.LEFT );
label2.setToolTipText( "This is label2" );
add( label2 );
label3 = new JLabel(); // JLabel constructor no arguments
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug ); // add icon to JLabel
label3.setHorizontalTextPosition( SwingConstants.CENTER );
label3.setVerticalTextPosition( SwingConstants.BOTTOM );
label3.setToolTipText( "This is label3" );
add( label3 );
}
}
That was class one.
import javax.swing.JFrame;
public class LabelTest
{
public static void main( String[] args )
{
LabelFrame labelFrame = new LabelFrame(); // create LabelFrame
labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
labelFrame.setSize( 260, 180 ); // set frame size
labelFrame.setVisible( true ); // display frame
} // end main
}
This is class two.
I noticed that with the one untyped (LabelFrame) class did not have a type, but I copied from Deitel's Java book. I assumed we was correct, but so far this is not running because of that little piece of code. I am wondering if it could be an issue with the Java version, since mine is the latest, and the book is from 2012. If you could enlighten me on why this code won't run in Eclipse, that would be greatly appreciated. In addition, the add did not work. Thanks.
OK.. it seems the problem is that the code would not even compile cleanly. This was largely due to the lack of logical indentation leading to incorrectly placed brackets.
This code compile, but fails (here) at run-time due to the missing image.
import java.awt.FlowLayout; // specifies how components are arranged
import javax.swing.JFrame; // provides basic window features
import javax.swing.JLabel; // displays text and images
import javax.swing.SwingConstants; // common constants used with Swing
import javax.swing.Icon; // interface used to manipulate images
import javax.swing.ImageIcon; // loads images
public class LabelFrame extends JFrame
{
private JLabel label1; // JLabel with just text
private JLabel label2; // JLabel constructed with text and icon
private JLabel label3; // JLabel with added text and icon
// LabelFrame constructor adds JLabels to JFrame
public LabelFrame() {
super( "Testing JLabel" );
setLayout( new FlowLayout() );
// JLabel constructor with a string argument
label1 = new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
add( label1 );
//JLabel constructor with string, Icon and alignment arguments
Icon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );
label2 = new JLabel( "Label with text and icon", bug,
SwingConstants.LEFT );
label2.setToolTipText( "This is label2" );
add( label2 );
label3 = new JLabel(); // JLabel constructor no arguments
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug ); // add icon to JLabel
label3.setHorizontalTextPosition( SwingConstants.CENTER );
label3.setVerticalTextPosition( SwingConstants.BOTTOM );
label3.setToolTipText( "This is label3" );
add( label3 );
}
public static void main( String[] args )
{
LabelFrame labelFrame = new LabelFrame(); // create LabelFrame
labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
labelFrame.setSize( 260, 180 ); // set frame size
labelFrame.setVisible( true ); // display frame
} // end main
}
The reason add is showing error is because you didn't "extend JFrame in the LabelFrame class,
It should be coded like this:
public class LabelFrame extends JFrame{
}
that should solve that problem, On the rest of your question, I'm having the same problem because the image is not there, It's null, If anyone can tell me how to get the image and use it, that would be greatly appreciated, Thanks!..
Copy and paste the picture in the package of your project and run the code.I hope it will work.
Another process:
Use
ImageIcon bug = new ImageIcon("java.png");//In the double quotes write the full path of the image.
instead of Icon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );
I hope it will also work.
I faced the same problem. Here is the solution... just make a png image (using photoshop) and name it as bug1.png. Now just copy & paste the image in your project's src folder. Thats all.
i need to display a image in JComboBox
Just add an Icon to the model instead of a String:
import java.awt.*;
import javax.swing.*;
public class ComboBoxIcon extends JFrame
{
JComboBox comboBox;
public ComboBoxIcon()
{
Object[] items =
{
new ImageIcon("about16.gif"),
new ImageIcon("add16.gif"),
new ImageIcon("copy16.gif")
};
comboBox = new JComboBox( items );
getContentPane().add( comboBox, BorderLayout.NORTH );
}
public static void main(String[] args)
{
JFrame frame = new ComboBoxIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
Take a look at this example that appears to do what you want.
http://www.java2s.com/Code/Java/Swing-JFC/CustomComboBoxwithImage.htm
What you are looking for is a custom renderer for the JComboBox. A renderer is simply a JComponent, so if you can create a component (JPanel with the necessary items contained), then you can create almost any result that you can think of). You can even override the paint method if using standard JComponents are not enough for you.
I have created a JFrame, and now I want to add a JLabel and textfields in it. Please tell me how to do that. I have used the following code but its not working.
JFrame i_frame = new JFrame("Select Locations");
i_from = new JLabel("From");
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
Problem is this code is showing frame window but it is not showing label in it. Please help.
That's your first question, later you'll ask:
How do I get the value from my text field
So, I suggest you to take a look at this tutorial
http://java.sun.com/docs/books/tutorial/uiswing/start/index.html
And ask us if you have questions from that tutorial. Using an IDE will simplify your life.
Here's a start anyway:
Code:
import javax.swing.*;
import java.awt.Color;
public class MyApp {
public static void main( String [] args ) {
JFrame frame = new JFrame();
frame.setBackground( new Color(0,0,0,64 ));
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel top = new JPanel();
top.add( new JLabel("What is your name"){{
setForeground(Color.white);
}});
top.add( new JTextField(10) );
frame.add( top );
frame.pack();
frame.setVisible( true );
}
}
EDIT
Dismiss this answer. It was posted when the question was rather ambiguous. I'm leaving it as CW for it may be helpful.
plus OSX frames with alpha background are too cool!
The main issue is the layout being used by the content pane (most likely JRootPane.RootLayout, A custom layout manager that is responsible for the layout of layeredPane, glassPane, and menuBar ) is not the best. This code should work;
JFrame i_frame = new JFrame("Select Locations");
JLabel i_from = new JLabel("From");
i_frame.getContentPane().setLayout(new FlowLayout());
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
setting a different layout does the trick
The problem is that you are adding a second component (Box.createRigidArea) in the same layout position (BorderLayout.CENTER) as the Label.
JFrame.add() results in the same as JFrame.getContentPane().add()...
So the label is being replaced by the RigidArea.
Try this:
JFrame i_frame = new JFrame("Select Locations");
i_from = new JLabel("From");
i_frame.getContentPane().add(i_from);
// i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
to add more components, change the LayoutManager:
JFrame i_frame = new JFrame("Select Locations");
JLabel i_from = new JLabel("From");
Container pane = i_frame.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS)); // any LayoutManager you need
pane.add(i_from);
pane.add(Box.createRigidArea(new Dimension(2,0))); // space after JLabel ?
i_frame.setSize(200,200); // better done before setLocationRelativeTo
i_frame.setLocationRelativeTo(null);
i_frame.setVisible(true);
Note: if you "just" want to add an empty border to your label, use a setBorder() instead of the RigidArea:
i_from.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
[]]
For adding JLabel to JFrame see the line of code see here
public class JLabelExample extends JFrame {
JLabel jLabel;
public JLabelExample() {
jLabel = new JLabel();
jLabel.setText("tutorialData.com");
jLabel.setForeground(Color.BLUE);
this.add(jLabel);
}
public static void main(String a[]) {
JLabelExample labelExample = new JLabelExample();
labelExample.setSize(250, 200);
labelExample.setTitle("tutorialData.com");
labelExample.setVisible(true);
}
}
Please refer more on JFrame