Cannot get text from JTextPane - java

So I have a JTextPane, and I have a method that returns a String containing the text in the JTextPane. I have been trying to fix this for weeks. The getText() method returns a blank line. I tried getting the document length, but that returns 0.
Here is the code:
import java.awt.*;
import javax.swing.*;
public class CodeTabs extends JTabbedPane {
private JTextPane codearea;
private JScrollPane scroll;
public CodeTabs() {
setTabPlacement(JTabbedPane.BOTTOM);
codearea = new JTextPane();
scroll = new JScrollPane(codearea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize()));
addTab("Code", scroll);
}
public String getCode() {
String s = codearea.getText();
System.out.println(s);
return s;
}
}

I took your code and added a main method and a button to trigger the getCode() method. Everything works as expected. When I type something in the text area, it gets printed when I press the button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CodeTabs extends JTabbedPane {
private JTextPane codearea;
private JScrollPane scroll;
public CodeTabs() {
setTabPlacement(JTabbedPane.BOTTOM);
codearea = new JTextPane();
scroll = new JScrollPane(codearea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setPreferredSize(new Dimension( 300,300 ));
JPanel panel = new JPanel( new BorderLayout() );
panel.add( scroll, BorderLayout.CENTER );
JButton comp = new JButton( "Print text" );
comp.addActionListener( new ActionListener() {
#Override
public void actionPerformed( ActionEvent e ) {
getCode();
}
} );
panel.add( comp, BorderLayout.SOUTH );
addTab( "Code", panel );
}
public String getCode() {
String s = codearea.getText();
System.out.println(s);
return s;
}
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame( "TestFrame" );
frame.getContentPane().add( new CodeTabs() );
frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
} );
}
}
Note: there is no need to extend JTabbedPane. Use it instead of extending it (I left it in the code posted in this answer to match your code as closely as possible)

Do this way:-
codearea.getDocument().getText(0, codearea.getDocument().getLength());

Related

Clear current FocusOwner (jTextfield)

Developing an application in swing, just a little query :-
I want to clear the current focus owner textfield using a button. It is possible to determine whether a textfield is the current focus owner or not using isFocusOwner() but how to clear the textfield which is currently on focus?
Thanks!!!
You might be able use a TextAction. A TextAction has access to the last text component that had focus. So then in the text action you just clear the text in the component. All the logic is fully contained in the one place.
Here is an example that demonstrates the concept of using a TextAction. In this case the number represented by the button is appended to the text field with focus:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.*;
public class NumpadPanel extends JPanel
{
public NumpadPanel()
{
setLayout( new BorderLayout() );
JTextField textField1 = new JTextField(4);
JTextField textField2 = new JTextField(2);
JTextField textField3 = new JTextField(2);
JPanel panel = new JPanel();
panel.add( textField1 );
panel.add( textField2 );
panel.add( textField3 );
add(panel, BorderLayout.PAGE_START);
Action numberAction = new TextAction("")
{
#Override
public void actionPerformed(ActionEvent e)
{
JTextComponent textComponent = getFocusedComponent();
if (textComponent != null)
textComponent.replaceSelection(e.getActionCommand());
}
};
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setMargin( new Insets(20, 20, 20, 20) );
button.setFocusable( false );
buttonPanel.add( button );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Numpad Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new NumpadPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
In your case instead of using the replaceSelection() method you would just use the setText() method.
If you want to clear a textfield using the clicking of a button, you have to write the code to clear the textfield in the the ActionListener class's ActionPerformed method. This method is called when the button is pressed. But in order to press the button you have to get the focus from other component to this button. So in the method ActionPerformed you would get false to textField.isFocusOwner().
My suggestion to overcome this problem is:
add focus listeners to these 6 text fields.
declare a variable say lastFocused as type JTextField in initialise it to null in the Class that you are implementing all these.
write the following code to the focusListerners Overridden methods
void focusGained(FocusEvent e){
lastFocused = (JTextField) e.getComponent();
}
void focusLost(FocusEvent e){
lastFocused = null;
}
now in the ActionListener overridden method write the following:
void actionPerformed(ActionEvent e){
if(lastFocused != null){
lastFocused.setText("");
}
}
I feel this should solve your problem.

Append value to JTextField?

I want to append a value into a JTextField in Java. Something like:
String btn1="1";
textField.appendText(btn1);
I think you'll find setText is the answer. Just combine the current value with the new value:
textField.setText(textField.getText() + newStringHere);
If you text field is not editable, you could use:
textField.replaceSelection("...");
If it is editable you might use:
textField.setCaretPosition( textField.getDocument().getLength() );
textField.replaceSelection("...");
This would be slightly more efficient (than using setText()) because you are just appending text directly to the Document and would more resemble a JTextArea.append(...).
It would only result in a single DocumentEvent - insertUpdate().
You can also access the Document directly and do the insert:
Document doc = textField.getDocument();
doc.insertString(...);
but I find this more work because you also have to catch the BadLocationException.
Simple example, that also demonstrate the use of Key Bindings:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(50, 50) );
buttonPanel.add( button );
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
button.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
// UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

JLabel misplaced after adding JPanel

I'm almost blind after reading lots of java swing articles, and still can not get panel to work.
When i add 2 JLabels, they are nicely aligned to left, with 5px padding defined by EmptyBorder, just as i want them to be.
I found that after adding ProgressBar with extra border for padding, does not work as expected, added 1 more panel, where i add ProgressBar. Progress looks good, but all my labels are displaced.
And finally it look like this (RED background is for debug, to see how JPanel draws):
Question1: How to fix this?
Question2: Is it standard approach for swing to place panel inside of other panel with other panels just to get formating i want?
Source:
public class AppInitProgressDialog {
private static final int VIEW_PADDING_VAL = 5;
private static final Border viewPaddingBorder = new EmptyBorder( VIEW_PADDING_VAL, VIEW_PADDING_VAL, VIEW_PADDING_VAL, VIEW_PADDING_VAL );
private JPanel view; // Dialog view
private JPanel panel;
private JPanel progressPanel;
private JLabel title;
private JLabel progressDesc;
private JProgressBar progressBar;
private void initPanel( int w, int h ) {
view = new JPanel();
view.setBorder( BorderFactory.createRaisedSoftBevelBorder() );
view.setBackground( Color.LIGHT_GRAY );
view.setSize( w, h );
view.setLayout( new BorderLayout() );
panel = new JPanel();
panel.setBorder( viewPaddingBorder );
panel.setLayout( new BoxLayout(panel, BoxLayout.PAGE_AXIS) );
//panel.setLayout( new SpringLayout() );
panel.setOpaque( false );
JFrame parent = AppContext.getMe().getAppWindow().getFrame();
int posx = (parent.getWidth() - w)/2;
int posy = (parent.getHeight() - h)/2;
view.add( panel, BorderLayout.CENTER );
view.setLocation( posx, posy );
}
private void initTitle() {
title = new JLabel( "Progress title" );
title.setAlignmentX( JComponent.LEFT_ALIGNMENT );
panel.add(title);
}
private void initProgress() {
progressPanel = new JPanel( new BorderLayout() );
progressPanel.setBackground( Color.LIGHT_GRAY );
progressPanel.setBorder( new EmptyBorder( 15, 30, 15, 30) );
progressPanel.setBackground( Color.RED );
progressBar = new JProgressBar(0, 10000);
progressBar.setStringPainted(true);
progressBar.setAlignmentX( JComponent.LEFT_ALIGNMENT );
progressPanel.add(progressBar);
panel.add( progressPanel );
progressDesc = new JLabel( "Progress description" );
panel.add(progressDesc);
}
public AppInitProgressDialog() {
initPanel( 400, 100 );
initTitle();
initProgress();
}
public JComponent getView() {
return view;
}
}
Alternatively, you can use BorderLayout for panel:
panel = new JPanel(new BorderLayout());
...
panel.add(title, BorderLayout.NORTH);
...
panel.add(progressPanel); // default CENTER
...
panel.add(progressDesc, BorderLayout.SOUTH);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.border.EmptyBorder;
/**
* #see http://stackoverflow.com/a/16837816/230513
*/
public class Test {
private JFrame f = new JFrame("Test");
private void display() {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new AppInitProgressDialog().getView());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
class AppInitProgressDialog {
private static final int VIEW_PADDING_VAL = 5;
private JPanel view; // Dialog view
private JPanel panel;
private JPanel progressPanel;
private JLabel title;
private JLabel progressDesc;
private JProgressBar progressBar;
private void initPanel(int w, int h) {
view = new JPanel();
view.setBorder(BorderFactory.createRaisedBevelBorder());
view.setBackground(Color.LIGHT_GRAY);
view.setSize(w, h);
view.setLayout(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createLineBorder(Color.blue));
panel.setOpaque(false);
view.add(panel, BorderLayout.CENTER);
}
private void initTitle() {
title = new JLabel("Progress title");
title.setAlignmentX(JComponent.LEFT_ALIGNMENT);
panel.add(title, BorderLayout.NORTH);
}
private void initProgress() {
progressPanel = new JPanel(new BorderLayout());
progressPanel.setBackground(Color.LIGHT_GRAY);
progressPanel.setBorder(new EmptyBorder(15, 30, 15, 30));
progressPanel.setBackground(Color.RED);
progressBar = new JProgressBar(0, 10000);
progressBar.setStringPainted(true);
progressBar.setAlignmentX(JComponent.LEFT_ALIGNMENT);
progressPanel.add(progressBar);
panel.add(progressPanel);
progressDesc = new JLabel("Progress description");
panel.add(progressDesc, BorderLayout.SOUTH);
}
public AppInitProgressDialog() {
initPanel(400, 100);
initTitle();
initProgress();
}
public JComponent getView() {
return view;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}
Use Layout Managers rather than just adding panels to each other. Specifically in your case I think you can use GridLayout.
panel.setLayout(new GridLayout(1,1,0,0));
Fore more details on layout refer to this tutorial.

Toggling text wrap in a JTextpane

How would I go about toggling text wrap on a JTextpane?
public JFrame mainjFrame = new JFrame("Text Editor");
public JTextPane mainJTextPane = new JTextPane();
public JScrollPane mainJScrollPane = new JScrollPane(mainJTextPane);
mainjFrame.add(mainJScrollPane);
See No Wrap Text Pane.
Edit:
Well, if you want to toggle the behaviour, then you would also need to toggle the getScrollableTracksViewportWidth() value. See Scrollable Panel. You should be able to toggle between FIT and STRETCH.
package test;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class TestVisual extends JFrame {
private boolean wrapped;
private JButton toggleButton = null;
private JTextPane textPane = null;
private JPanel noWrapPanel = null;
private JScrollPane scrollPane = null;
public TestVisual() {
super();
init();
}
public void init() {
this.setSize(300, 200);
this.setLayout(new BorderLayout());
wrapped = false;
textPane = new JTextPane();
noWrapPanel = new JPanel( new BorderLayout() );
noWrapPanel.add( textPane );
scrollPane = new JScrollPane( noWrapPanel );
toggleButton = new JButton("wrap");
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (wrapped == true){
scrollPane.setViewportView(noWrapPanel);
noWrapPanel.add(textPane);
toggleButton.setText("wrap");
wrapped = false;
}else {
scrollPane.setViewportView(textPane);
toggleButton.setText("unWrap");
wrapped = true;
}
}
});
this.add(scrollPane, BorderLayout.CENTER);
this.add(toggleButton, BorderLayout.NORTH);
}
}
I don't know any other way for what you are looking for..
But this is working well.
( Based on camickr's answer.. +1 )

Java: "Add Tab Button" for a JTabbedPane

Is it possible to add a button to a tabbed pane like in firefox.
The plus-button is what I want.
Thanks
I think you should be able to manage it by building your own JTabbedPaneUI and setting it on the JTabbedPane using setUI.
Your ComponentUI has methods to get a hold of the accessible children. If you specify a JButton and a JLabel then you may be in business.
I haven't attempted this myself though. This is "at your own risk" :)
You can try this:
public static void main (String[] args) {
JFrame parent = new JFrame ();
final JTabbedPane pane = new JTabbedPane ();
pane.addTab ("test", null);
FlowLayout f = new FlowLayout (FlowLayout.CENTER, 5, 0);
// Make a small JPanel with the layout and make it non-opaque
JPanel pnlTab = new JPanel (f);
pnlTab.setOpaque (false);
// Create a JButton for adding the tabs
JButton addTab = new JButton ("+");
addTab.setOpaque (false); //
addTab.setBorder (null);
addTab.setContentAreaFilled (false);
addTab.setFocusPainted (false);
addTab.setFocusable (false);
pnlTab.add (addTab);
pane.setTabComponentAt (pane.getTabCount () - 1, pnlTab);
ActionListener listener = new ActionListener () {
#Override
public void actionPerformed (ActionEvent e) {
String title = "Tab " + String.valueOf (pane.getTabCount () - 1);
pane.addTab (title, new JLabel (title));
}
};
addTab.setFocusable (false);
addTab.addActionListener (listener);
pane.setVisible (true);
parent.add (pane);
parent.setSize (new Dimension (400, 200));
parent.setVisible (true);
}
Write Following Code in Default Constructor Of Class
JPanel panel = new JPanel();
tabbedPane.addTab("Welcome", null, panel, null);
tabbedPane.addTab(" + ", null, panel1, null);
tabbedPane.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent evt)
{
JTabbedPane tabbedPane = (JTabbedPane)evt.getSource();
if(tabbedPane.getSelectedIndex() == tabbedPane.indexOfTab(" + "))
{
createTab();
}
}
});
And Create Method to declare and initialized int tab2 = 2; at Starting of main class. Its Worked.
private void createTab()
{
tabbedPane.addTab("New Tab",new Panel());
tabbedPane.addTab(" + ",null,panel1,null);
tabbedPane.setSelectedIndex(tab2);
tab2++;
}
I have tried several solutions and came with this one:
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class TestTab {
public static void main(String[] args) {
JFrame parent = new JFrame();
final JTabbedPane tabEntity = new JTabbedPane();
tabEntity.addTab("Details", null, new JScrollPane());
tabEntity.addTab("Context", null, new JScrollPane());
tabEntity.addTab("", null, new JScrollPane());
addButtonToTab(tabEntity);
parent.add(tabEntity);
parent.setSize(new Dimension(400, 200));
parent.setVisible(true);
}
public static void addButtonToTab(final JTabbedPane tabEntity) {
tabEntity.setTabComponentAt(tabEntity.getTabCount() - 1, new JButton(
"+"));
}
}
So you have:

Categories

Resources