ScrollPane in TextArea - java

Here is part of my code:
JFrame window = new JFrame();
JPanel panel = new JPanel();
JTextArea text = new JTextArea();
JScrollPane scroll = new JScrollPane(text);
private Window()
{
createWindow();
}
public void createWindow()
{
window.setLayout(null);
window.setVisible(true);
panel.setVisible(true);
text.setBounds(20, 100, 320, 270);
}
public void update2(String employee)
{
text.setText(null);
try
{
scanner = new Scanner(employee);
}catch(Exception e){
e.printStackTrace();
}
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
text.append(line+"\n");
}
revalidate();
}
I'm wondering how to add scroll bar to TextArea "text". It's a database app and it sends String of data to TextArea. I want the app to show scrollbar (vertical or horizontal) if necessary - too many Strings in TextArea. I have been trying many things but nothing works. Constructor has to be private because I'm using Singleton.

Avoid using null layouts. Take a look at Layout Managers for better options.
Unless you are not including the part where you add the Scrollpane to the JFrame, I suggest you do something similar to this
frame.add(scrollpane, BorderLayout.CENTER);
The BorderLayout.CENTER is a position in the default layout for JFrames. Read here for more.

Btw, where did you add your scroll to the Frame?
window.add(scroll);
window.setVisible (true);
JScrollPane is a container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:.
JFrame window = new JFrame();
JPanel panel = new JPanel();
JTextArea text = new JTextArea();
JScrollPane scroll = new JScrollPane(text);
If the above did not work, use:
JScrollPane scroll = new JScrollPane ();
scroll.getViewport ().setView ( text );

Related

Adding JScrollPane to JPanel with another panels inside

i been working on some bigger project lately but couldn't figure it out why JScrollPane wouldn't work. I have never used it before and I read many solved problems about it on stackOverflow and other programming forums but non of the code were looking similar to mine to help me implement my method.
this is new project i made to make it short and show some examples.
Red colour is main panel that will contain another panel/JScrollPane inside that will be colour black
and i would like to make this Jpanel with colour black to be scrollable and hold any number of that white JPanels that might be from 0 to a 100+
public class ScrollablePane {
private JFrame frame;
private JPanel panelCopy;
private JPanel panel;
private JPanel container;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScrollablePane window = new ScrollablePane();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ScrollablePane() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
panel = new JPanel();
panel.setBackground(Color.RED);
panel.setBounds(0, 0, 434, 261);
frame.getContentPane().add(panel);
panel.setLayout(null);
container = new JPanel();
container.setBackground(Color.BLACK);
container.setBounds(10, 10, 414, 241);
container.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
panel.add(container);
for(int i = 0; i < 20; i++) {
if(i > 0) {
panelCopy = new JPanel();
panelCopy.setPreferredSize(new Dimension(400, 40));
container.add(panelCopy);
}
}
}
}
if you want to use a JScrollPane, then your code actually needs to use a JScrollPane. The code you posted doesn't even create a JScrollPane.
If you want the panels to display vertically then don't use a FlowLayout. The FlowLayout is a horizontal layout. You could use a BoxLayout or a GridBagLayout.
Why do you create the "panel" variable and add it the the content pane? The content pane of the frame already is a JPanel that uses a BorderLayout. There is no need to add another panel
Don't use a null layout!!! Swing was designed to be used with layout managers. Scrolling won't work if the panel added to the scroll pane uses a null layout.
So in your case the basic logic might be something like:
Box container = Box.createVerticalBox();
// add you child panels to the container.
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(container, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(wrapper);
frame.add(scrollPane, BorderLayout.CENTER);
Note the "wrapper" panel is used to prevent the panels from expanding in size when the scroll pane is larger then the preferred size of the "container" panel.
Try:
//JScrollPane scrollPane = new JScrollPane(wrapper);
JScrollPane scrollPane = new JScrollPane(container);
to see the different result.

Creating a WordWrap method for a JTextarea - Java

I think im heading in the wrong direction. Im creating a notepad app. I have every method running perfectly except one - WordWrap
Its just a JTextarea inside a panel inside a frame.
I think i should be using a JScrollPane instead of a Textarea? Or aswell as it even?
How would i go about resizing the width of a textarea or am i correct in saying i need to insert a JScrollPane.
Edit
Ok so my attempt is gone wrong somehow. Text area doesnt work. Something possibly needs resizing.
public class TextEditor extends JFrame implements ActionListener{
JFrame textFrame = new JFrame();
JPanel textPanel = new JPanel();
JTextField textArea = new JTextField();
JScrollPane scroll = new JScrollPane(textArea);
JTextArea text = new JTextArea(24,33);
public TextEditor(String str){
super(str);
textFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
textFrame.add(textPanel);
textPanel=(JPanel)getContentPane();
textPanel.setLayout(new FlowLayout());
textPanel.setBackground(Color.WHITE);
// Create text Area
textPanel.add(scroll);
scroll.add(text);
textPanel.setFont(textAreaFont);
textArea.setFont(textAreaFont);
text.setFont(textAreaFont);
}
public static void main(String args[])
{
TextEditor notePad = new TextEditor("Notepad");
notePad.setSize(500,500);
notePad.setVisible(true);
notePad.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Have a look at what I have tried to put together:
public class SO{
public static void main(String[] args) {
JFrame f = new JFrame();
JPanel p = new JPanel();
JTextArea outputArea = new JTextArea();
outputArea.setColumns(20);
outputArea.setRows(20);
outputArea.setLineWrap(true); //Set line wrap
outputArea.setWrapStyleWord(true); //set word wrap
JScrollPane sp = new JScrollPane(outputArea); //Create new scroll pane with textarea inside
p.add(sp); //add scrollPane to panel
f.add(p); //Add panel to frame
f.pack()
f.setLocationRelativeTo(null); //frame location
f.setVisible(true);
}
}
The scroll pane is created using the textarea in the constructor, this seems to allow the scroll pane to 'contain' the JTextArea, adding scroll bars when the text the area contains exceeds the limits. Earlier when creating the JTextArea I set two lines of code to set a word wrap on it, this stops words seeping off the sides by pushing them onto the next line. Have a look and see if it can help with your project.
Good Luck!
import java.awt.*;
import javax.swing.*;
public class TextEditor extends JFrame {
JFrame textFrame = new JFrame();
JPanel textPanel = new JPanel();
JTextArea textArea = new JTextArea(10,25);
public TextEditor(String str){
super(str);
textFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); // nicer
add(textPanel);
textPanel.setLayout(new GridLayout());
textPanel.setBackground(Color.WHITE);
// Create text Area
JScrollPane scroll = new JScrollPane(textArea);
textPanel.add(scroll);
}
public static void main(String args[])
{
TextEditor notePad = new TextEditor("Notepad");
notePad.setVisible(true);
notePad.setDefaultCloseOperation(EXIT_ON_CLOSE);
notePad.pack();
}
}
There were so many things wrong in that short code that I lost track of the changes. Two things I can recall are:
The code was quite confused about what was a JTextField and what was a JTextArea.
It added strange things to other strange things for no apparent reason.

Any other way to add scrollbar to JPanel other than JscrollPane

I have developed a desktop application. Now in that app I want to add panel with a scrollbar. I am trying using JScrollPane, but its not working.
JPanel paraJPanel = new JPanel();
JScrollPane SP_para_list = new JScrollPane(paraJPanel);
add(SP_para_list).setBounds(10,30,250,350);
This way I am adding scrollbars to panel. But it shows only empty panel with borders. It is not showing components in the panel. Although I have added several labels in it. Is it correct? Is there any other way to add scroll bar to panel.
Thanks in advance
You need to set the PreferredSize for the panel, to make the scrollbar show up, like below.
even you do not set a layout, the panel already has a default layout set.
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 1000);
}
};
panel.add(new JLabel("Test1"));
panel.add(new JLabel("Test2"));
frame.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);
frame.setSize(600, 800);
frame.setVisible(true);
}

How can I refresh a JScrollPane after choosing an element from a JComboBox?

I have a JComboBox, and I want to load in a JScrollPane a different content everytime I choose a different element from the JComboBox. The content consists of a various number of JLabels and JTextFields.
What I have done:
JScrollPane scrollPane;
JComboBox combo;
JPanel back = new JPanel(new BorderLayout());
combo = new JComboBox({ "Bird", "Cat", "Dog", "Rabbit", "Pig" });
combo.addActionListener(new AnimalLoader());
scrollPane = showPanel((String) combo.getSelectedItem());
back.add(combo, BorderLayout.NORTH);
back.add(scrollPane, BorderLayout.SOUTH);
back.setVisible(true);
protected JScrollPane showPanel(String name)
{
JPanel contentPanel = new JPanel(new JLabel(name));
scrollPane = new JScrollPane(contentPanel);
return scrollPane;
}
private class AnimalLoader implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JComboBox cb = (JComboBox) e.getSource();
String selected = (String) cb.getSelectedItem();
scrollPane = showPanel(selected);
}
}
I didn't manage to make this reload a different JScrollPane when I choose another item.
Only the JScrollPane that belongs to the first item (the default one) of the JComboBox is loaded.
Any ideas of what I've done wrong please?
scrollPane = showPanel(selected);
Don't create a new scoll pane when you select an item. Instead you need to change the panel that is contained in the viewport of the scroll pane. That is, your "showPanel" method should return the panel, not a scrollpane. Then you can use:
scrollPane.setViewportView( showPanel(selected) );
Next time a proper SSCCE should be posted.
There is no evidence the newly created JScrollPane is ever added to anything.
I would try either of:
Add a JPanel with a CardLayout to
the JScrollPane, and add other
collections of components to the
JPanel.
Call
setViewportView(Component view) on
the existing JScrollPane.
panel.revalidate();
panel.repaint();
As you are using this example, try this variation at line 73, near the end of the ComboBoxDemo constructor:
//Lay out the demo.
add(petList, BorderLayout.PAGE_START);
JScrollPane jsp = new JScrollPane(picture);
jsp.getViewport().setPreferredSize(new Dimension(100, 100));
add(jsp, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));

Swing: Showing a transparent Panel hovering over another Panel

I want to show a textArea showing some text (will show log lines) , and have an animated gif hoovering above it. I tried the solution described here , but all I get is a grey screen. Hints?
public class TestLayeredPanes {
private JFrame frame = new JFrame();
private JLayeredPane lpane = new JLayeredPane();
public TestLayeredPanes() {
frame.setPreferredSize(new Dimension(600, 400));
frame.setLayout(new BorderLayout());
frame.add(lpane, BorderLayout.CENTER);
//Build the animated icon
JLabel buildingIcon = new JLabel();
buildingIcon.setIcon(new ImageIcon(this.getClass().getResource(
"/com/ct/tasks/cmviewer/gui/progress_bar.gif")));
JPanel iconPanel = new JPanel();
iconPanel.add(buildingIcon);
//Build the textArea
JTextArea textLog = new JTextArea("Say something");
JPanel textPanel = new JPanel();
textPanel.add(new JScrollPane(textLog));
//Add the panels to the layered pane
lpane.add(textPanel, 0);
lpane.add(iconPanel, 1);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new TestLayeredPanes();
}
}
Try putting your animated GIF on the glass pane of your root pane:
http://download.oracle.com/javase/tutorial/uiswing/components/rootpane.html
JXLayer make easier to do that. Look at JXLayer samples.
You also can take a look at code of XSwingX
Since you started with a working example, why did you remove lines of code from the example you copied?
Layered panes don't use a layout manager therefore the size of your components are (0, 0), so there is nothing to display. The setBounds(...) method in the example are there for a reason.

Categories