Scroll bar not working for JTextArea, why? - java

I'm trying to create a scrollable text area, (much like the one i'm writing in right now as in stack overflow's one). It seems as if the scrollpane and the text area are mutually exclusive and i'd like to create a connection between them
package Notepad;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.JTextArea;
import javax.swing.JScrollBar;
public class test {
private JFrame frame;
private Font f = new Font(null);
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test window = new test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public test() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
JTextArea textArea = new JTextArea();
frame.getContentPane().add(textArea, BorderLayout.CENTER);
textArea.setLineWrap(true);
textArea.setFont(f.deriveFont(40f));
JScrollBar scrollBar = new JScrollBar();
frame.getContentPane().add(scrollBar, BorderLayout.EAST);
}
}

use JScrollPane rather than JScrollBar
Wrong:
JScrollBar scrollBar = new JScrollBar();
Right:
JScrollPane scroller = new JScrollPane(textArea);
you can set the size of this ScrollPane like so:
Dimension size = new Dimension (0, 50);
scroller.setPreferredSize(size);
NOTE: When you use JScrollPanes, be sure to put where you want it in parentheses, or it will not show up.

JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setFont(f.deriveFont(40f));
JScrollPane scrollPane = new JScrollPane(textArea);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

OMG sorry guys. I imported JScrollBar not JScrollPane. Thank you all. I'm going to test this fix and get back to you.
Edit:
It works. Thank you guys!!!

Related

JTextArea parameter and user input issues

I have a JTextArea where I want to allow the user to input any number of strings up to 100 but it could be less. When I set the JTextArea as I have in my code below where it is commented out (i.e. //tfResult= new JTextArea(10, 0);) and the user inputs ten lines of strings then my code runs exactly as expected and prints out what I need it to.
But if I try to input more of less lines I get
java.lang.ArrayIndexOutOfBoundsException
followed by the number of lines of user input, whether I have it declared with no bounds or as I have it commented out.
I am new to graphics in java and I can't figure out why this is happening and I have searched everywhere for answers. Do I have the bounds set wrong or have I declared the JTextArea wrong?
I also am trying to include a JScrollPane but I am having issues with that also as its not showing up.
I would really appreciate any help as I am struggling to solve this issue.
class Window {
JFrame windowFrame;
Panel bottomPanel;
JScrollPane scroll;
JTextArea tfResult;
Button btnPlayAgain;
Font font;
Window(int width, int height, String title)
{
windowFrame = new JFrame();
windowFrame.setTitle(title);
windowFrame.setBounds(0,0,width,height);
windowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
windowFrame.setResizable(true);
windowFrame.setCursor(new Cursor(Cursor.HAND_CURSOR)); // setting cursor to hand
windowFrame.setLayout(null);
createBottomPanel();
windowFrame.add(bottomPanel);
//windowFrame.add(field.getCanvas());
windowFrame.setVisible(true);
}
private void createBottomPanel()
{
JButton b = new JButton("Compute");
bottomPanel = new Panel();
bottomPanel.setBackground(Color.PINK);
bottomPanel.setBounds(0,400,800,140);
bottomPanel.setLayout(null);
//*********
//tfResult= new JTextArea(10, 0);
tfResult= new JTextArea();
tfResult.setBounds(10,10,600,100);
tfResult.setFont(new Font("SansSerif", Font.BOLD, 16));
tfResult.setFocusable(true);
scroll = new JScrollPane(tfResult);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
btnPlayAgain = new Button("Compute");
btnPlayAgain.setBounds(620,10,150,100);
btnPlayAgain.setBackground(Color.RED);
btnPlayAgain.setFont(new Font("SansSerif", Font.BOLD, 24));
btnPlayAgain.setFocusable(true);
bottomPanel.add(tfResult);
bottomPanel.add(btnPlayAgain);
bottomPanel.add(b);
bottomPanel.add(scroll);
tfResult.setVisible(true);
scroll.setVisible(true);
btnPlayAgain.setVisible(true);
bottomPanel.setVisible(true);
btnPlayAgain.addActionListener(new ActionListener()
{
//#Override
public void actionPerformed(ActionEvent e)
{
//should include the code to genrate the output inside here
String input = tfResult.getText();
Mat xy;
xy = new Mat();
//String output = xy.getOutput(input).toString();
String output = xy.getOutput(input);
//String output = Output(input);
tfTarget.setText(output);
}
});
}
}
I went ahead and created the following GUI that allows you to enter data with a JTextArea.
The first thing I did was start my Swing application with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
Next, I created a JFrame. Then I created a JPanel with a BorderLayout. The JTextArea is inside of a JScrollPane, which is then placed inside of the center of a JPanel.
The JButton is placed after the last line of the JPanel.
Here's the complete runnable code, otherwise known as a minimal runnable example.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class JTextAreaInputGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JTextAreaInputGUI());
}
private JTextArea textArea;
#Override
public void run() {
JFrame frame = new JFrame("JTextArea Input GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
textArea = new JTextArea(10, 40);
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Submit");
button.addActionListener(new ButtonListener());
panel.add(button, BorderLayout.AFTER_LAST_LINE);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
System.out.println(textArea.getText().trim());
}
}
}

scroll pane graphic bug

I got an unexpected behavior on my JScrollPane:
My ScrollPanel is filled with different panels
(Transparency is needed because in the end I will have images in background instead of just colors)
I made a quick example of my problem:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.border.Border;
public class ScrollPaneTest extends JPanel{
ScrollPaneTest(){
JPanel Content = new JPanel();
BoxLayout ColumnLayout = new BoxLayout(Content,BoxLayout.Y_AXIS);
Content.setLayout(ColumnLayout);
for(int i = 0 ; i < 10 ; i++){
JPanel pane = new JPanel();
JLabel elem = new JLabel("element "+i);
pane.setBackground(new Color(0,0,0,125));
pane.add(elem);
Content.add(pane);
}
Content.setBackground(Color.ORANGE);
JScrollPane scrollPane = new JScrollPane(Content);
scrollPane.setPreferredSize(new Dimension(100,100));
scrollPane.setBackground(new Color(0,0,0,250));
add(scrollPane);
}
public static void main(String[] args) throws Exception {
JFrame f = new JFrame();
JPanel bck = new JPanel();
bck.setBackground(Color.RED);
bck.add(new ScrollPaneTest());
f.add(bck);
f.setSize(200, 200);
f.setVisible(true);
}
}
With this you can see that when I scroll, the graphics are all messed up :/
Thanks for Helping :p
I have the Following Solution for your Problem
When you scroll through the elements the elements are not repainted so you need to repaint them when you scroll the scroll bar. Add the following code after this line JScrollPane scrollPane = new JScrollPane(Content); it will work!
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener(){
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
repaint();
}
});

I wanted to ask about java program

I am a java programmer and i want to ask that why is my program not working:
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Cool extends JFrame{
public void AL(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500 , 200);
frame.setVisible(true);
frame.setTitle("Java");
JTextArea textarea = new JTextArea();
textarea.setEditable(false);
textarea.setLineWrap(true);
JTextField field = new JTextField();
field.setText("Hi! This is the text!");
}
}
this is my main class:
#SuppressWarnings("serial")
public class Main {
public static void main(String[] args){
Cool dude = new Cool();
dude.AL();
}
}
It does not display anything just a blank JFrame.It does give the title but nothing else it has everything.
You have to add the JTextArea and the JTextField to the JFrame.
I don't see you adding the widgets to the JFrame, so why should they appear?
frame.add(textarea);
frame.add(field);
You are not adding the JTextArea nor the JTextField to the JFrame. You can do it through the method add which is inherited from Container. According to Java Docs:
Appends the specified component to the end of this container.
Code:
frame.add(textarea);
frame.add(field);
I know there are a good half-dozen answers with the same answer: you should add the elements to your frame. But I also wanted to add that you usually want to encapsulate your JTextArea inside a JScrollPane so that you can write more text that will be shown using scroll bars.
You should also make sure that you're adding your elements to a content pane with a layout manager so that the elements will get arranged in the way that you expect. Take a look at A Visual Guide to Layout Managers to familiarize yourself with the available layout managers. An additional, popular layout manager is MigLayout although it requires an external Jar file.
Below is a simple example with my suggestions:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Cool extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Cool frame = new Cool();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Cool() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
textField = new JTextField();
contentPane.add(textField, BorderLayout.NORTH);
textField.setColumns(30);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea txtrImAText = new JTextArea();
txtrImAText.setRows(10);
txtrImAText.setColumns(30);
scrollPane.setViewportView(txtrImAText);
pack();
}
}
You forgot to add the elements to the frame:
frame.add(textarea );
frame.add(field);
Add thise lines and you will see a result.
I haven't used swing, but it seems that you have to add textarea and field to your JFrame frame.
Looking on the net i have seen this example:
frame.getContentPane().add(textarea);
You have to add text area and text field to the JFrame in AL method
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500 , 200);
frame.setVisible(true);
frame.setTitle("Java");
JTextArea textarea = new JTextArea();
textarea.setEditable(false);
textarea.setLineWrap(true);
JTextField field = new JTextField();
field.setText("Hi! This is the text!");
frame.add(textarea); // <-- here
frame.add(field);

Scroll bar not showing in JTextArea - Swing GUI

The scroll bar doesn't show. I've tried most of the codes people replied with in previous questions like this one.
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea_2 = new JTextArea();
textArea_2.setRows(200);
textArea_2.setBounds(0, 22, 434, 120);
textArea_2.setEditable(false);
JScrollPane scrollv2 = new JScrollPane (textArea_2);
frame.add(scrollv2);
frame.getContentPane().add(textArea_2);
scrollv2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.setVisible (true);
You are adding your JTextArea to your content pane where you should be actually adding your JScrollPane to the content pane of your JFrame. You should add the JTextArea to the content pane of the JScrollPane. Below is an example of the visible scroll bar in action:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class SimpleScrollBars extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SimpleScrollBars frame = new SimpleScrollBars();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SimpleScrollBars() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea(5, 15);
scrollPane.setViewportView(textArea);
pack();
}
}
The scrollbars will appear automatically when the preferred size of the text area is greater than the size of the scroll pane.
Your text area doesn't have any text to display, therefore its preferred size is (0, 0).
Also:
Don't use textArea_2.setBounds(...). This does nothing. The scrollpane has its own layout manager and will determine the appropriate size for the text area.
Don't use textArea_2.setRows(200). The 200 represents rows of text, not pixels. Your monitor can't display 200 rows of text. So use a reasonable value, like 10 or 20 depending on your application requirements.

Garbled text in OSX Java text field

When I edit text in a JTextField in my Swing application on OSX, the text gets garbled. It's most pronounced when I insert or delete characters but there are artifacts just when moving the cursor around. The data is fine, but the UI rendering is not.
What causes this and how can I fix it?
I'm using com.apple.laf.AquaLookAndFeel, as in this sample program. Type in some text and move the cursor around with the arrow keys to observe the weirdness.
import java.awt.*;
import javax.swing.*;
class TextFieldDisplay {
public static void main(String[] args) {
MainWindow app = new MainWindow();
}
}
class MainWindow extends JFrame {
public MainWindow() {
try {
UIManager.setLookAndFeel("com.apple.laf.AquaLookAndFeel");
} catch(Exception e) {
System.out.println("AquaLookAndFeel is not supported on your platform.");
System.exit(1);
}
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setMinimumSize(new Dimension(300, 100));
JPanel innerPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(250, 20));
scrollPane.setViewportView(innerPanel);
JPanel mainPanel = new JPanel();
getContentPane().add(mainPanel);
mainPanel.add(innerPanel);
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(250, 20));
innerPanel.add(textField);
pack();
}
}
I noticed as I was writing the SSCCE that the display issues seemed to crop up after I added the JScrollPane.
Not sure if it's relevant but I'm using Apple Java version 1.6.0_51 with a retina display.
Two things jump out at me.
Firstly, you're not initalisig your UI in the EDT, secondly, you're messing with the preferred and minimum sizes of your components.
You are not taking into consideration the font metrics when calculating the size of your components, which seems to be causing issues when it is rendering the content
Start by taking a look at Initial Threads.
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
class TextFieldDisplay {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
//UIManager.setLookAndFeel("com.apple.laf.AquaLookAndFeel");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println("AquaLookAndFeel is not supported on your platform.");
System.exit(1);
}
MainWindow app = new MainWindow();
}
});
}
}
class MainWindow extends JFrame {
public MainWindow() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
// setMinimumSize(new Dimension(300, 100));
JPanel innerPanel = new JPanel();
// JScrollPane scrollPane = new JScrollPane();
// scrollPane.setPreferredSize(new Dimension(250, 20));
// scrollPane.setViewportView(innerPanel);
JPanel mainPanel = new JPanel();
getContentPane().add(mainPanel);
mainPanel.add(innerPanel);
JTextField textField = new JTextField(20);
// textField.setPreferredSize(new Dimension(250, 20));
innerPanel.add(textField);
pack();
}
}

Categories

Resources