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.
Related
This question is very similiar to this: JScrollPane doesn't top align when there is more than enough space to show the content I tried this solution, but it does not work.
When I add a jlabel to jscrollpane, when the jlabel is small, the label becomes centered. It works normally when the scrollbar shows. Setting boxlayout does not change anything. I feel like this isn't working properly because I'm setting a perferred size to the panel? But if I remove the line panel.setPreferredSize(new Dimension((int)(screenSize.width*0.7 - 50), screenSize.height-150)); The label becomes small when there is no text, and grows to accomdate text, which I don't want. If I add the panel instead of the label, it makes the screen scrollable even though there isn't text?
This is my code:
public class Test {
// JFrame
static JFrame frame = new JFrame("Test");
//panel 1
static JPanel panel = new JPanel(new BorderLayout());
// label to display text
static JLabel label = new JLabel();
//scroll panel in main method
public static void main(String[] args) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
label.setBorder(new EmptyBorder(5, 5, 5, 20));
label.setText("any text makes it centered beyond 40 lines");
//create panel
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(label, BorderLayout.NORTH);
panel.add(Box.createVerticalGlue());
panel.setPreferredSize(new Dimension((int)(screenSize.width*0.7 - 50), screenSize.height-150));
panel.setBorder(new EmptyBorder(5, 5, 5, 10));
JScrollPane jspanel = new JScrollPane(label, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//jspanel.add(label, BorderLayout.CENTER);
jspanel.setPreferredSize(new Dimension((int)(screenSize.width*0.7 - 70), screenSize.height-180));
jspanel.getVerticalScrollBar().setUnitIncrement(20);
jspanel.setBorder(BorderFactory.createEmptyBorder());
jspanel.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
jspanel.setAlignmentY(JScrollPane.TOP_ALIGNMENT);
//panel.setPreferredSize(new Dimension(640, 480));
//frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(jspanel);
frame.setSize((int)(screenSize.width*0.7), screenSize.height - 50);
frame.revalidate();
frame.pack();
frame.setVisible(true);
}
}
jspanel.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
jspanel.setAlignmentY(JScrollPane.TOP_ALIGNMENT);
That will align the scrollpane in its parent container, depending on the layout manager being used. It does not affect the alignment of any component added to the scrollpane. It is not needed.
the label becomes centered
The label is sized to fill the entire space available, so you need to customize how the text of the label is painted.
If you don't want it centered then you can place it at the top using:
label.setVerticalAlignment( SwingConstants.TOP );
After reworking your code, I came up with the following GUI.
I added a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
I eliminated all static references, except for the main method.
I reworked your code into methods so I could focus on one part of the GUI at a time.
Here's the complete runnable example. This is a minimal reproducible example.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class JScrollPaneTestGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JScrollPaneTestGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("JScrollPane Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane jspanel = createJScrollPane();
frame.add(jspanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private JScrollPane createJScrollPane() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(Color.YELLOW);
panel.setPreferredSize(new Dimension(400, 300));
JLabel label = new JLabel();
label.setBorder(new EmptyBorder(5, 5, 5, 20));
label.setText("any text makes it centered beyond 40 lines");
//create panel
panel.add(label, BorderLayout.NORTH);
JScrollPane jspanel = new JScrollPane(panel);
return jspanel;
}
}
I'm currently working on a media player for java, and with the power of VLCJ I was working on implementing an equalizer adjust window. There will be 11 vertical sliders with a JLabel underneath them indicating the hZ band and the dB level of the band. However, the slider keeps adding a huge gap between itself and the JLabel. I tried stacking just two JLabels on top of each other and there's barely a gap at all. My code is below. (The return equalizer stuff hasn't been implemented yet. I just want a basic UI working before I start adding in the functionality)
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import uk.co.caprica.vlcj.player.Equalizer;
public class VideoEQFrame {
public VideoEQFrame() {
//constructor
}
public Equalizer show() {
JFrame frame = new JFrame("Effects");
JPanel panel = new JPanel();
JPanel sliders= new JPanel();
JPanel gainObjects = new JPanel(new GridLayout(2, 0, 2, 0));
JSlider gainS = new JSlider(JSlider.VERTICAL, -12, 12, 0);
gainS.setMajorTickSpacing(2);
gainS.setPaintTicks(true);
gainS.setToolTipText("Adjust the gain");
JLabel gainL = new JLabel("Text");
gainObjects.add(gainS);
gainObjects.add(gainL);
sliders.add(gainObjects);
panel.add(sliders);
frame.add(panel);
frame.setSize(new Dimension(600, 300));
//frame.setResizable(false);
frame.setVisible(true);
Equalizer eq = new Equalizer(0);
return eq;
}
}
You are using GridLayout to lay the slider and the text label. That means that they will both occupy the same height. So because the slider has bigger height, the height of the label also adjusts to this height. Try using another LayoutManager like BorderLayout, like so:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
public class VideoEQFrame {
public VideoEQFrame() {
//constructor
}
public void show() {
JFrame frame = new JFrame("Effects");
JPanel panel = new JPanel();
JPanel sliders= new JPanel();
JPanel gainObjects = new JPanel(new BorderLayout());
JSlider gainS = new JSlider(JSlider.VERTICAL, -12, 12, 0);
gainS.setMajorTickSpacing(2);
gainS.setPaintTicks(true);
gainS.setToolTipText("Adjust the gain");
JLabel gainL = new JLabel("Text");
gainObjects.add(gainS, BorderLayout.CENTER);
gainObjects.add(gainL, BorderLayout.PAGE_END);
sliders.add(gainObjects);
panel.add(sliders);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
//frame.setResizable(false);
frame.setVisible(true);
// Equalizer eq = new Equalizer(0);
// return eq;
}
public static void main(final String[] args) {
new VideoEQFrame().show();
}
}
i am writing simple code with GUI that should have one text area which should be scrollable. So far so good.
I created my frame and the text area and i can write in it ok. Next I created my ScrollPane and added the TextArea in it, then added the ScrollPane to the frame but nothing shows.
Here is the code i have at this point:
JFrame frame = new JFrame();
frame.setBounds(100, 100, 325, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//textArea
JTextArea textArea = new JTextArea();
textArea.setEnabled(true);
textArea.setEditable(true);
JScrollPane scroll = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
textArea.setBounds(10, 101, 272, 149);
textArea.setWrapStyleWord(true);
frame.getContentPane().add(scroll);
change
frame.getContentPane().setLayout(null);
to
frame.getContentPane().setLayout(new BorderLayout());
and you are done
You have to set the bounds to the component that is being added to the content pane of the frame. In this case, it should be: scroll.setBounds(10,101,271,149).
However, I strongly recommend to not use null layout. Use a layout manager of your choice, BorderLayout for instance. In this case you don't have to worry about the bounds, it will fit the frame size (it will resize when you change the size of the frame). Here's your example, tweaked a little bit:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(100, 100, 325, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
// textArea
JTextArea textArea = new JTextArea();
textArea.setEnabled(true);
textArea.setEditable(true);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
textArea.setWrapStyleWord(true);
frame.getContentPane().add(scroll, BorderLayout.CENTER);
frame.setVisible(true);
}
}
I'm still learning however by looking at this case.
I have couple of issues:
There is issue with setting bounds of textArea
Layout of frame/container should not be set to null.
I have removed this sentence, and I tried this code, it displays desired textArea.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/*
* Tester class
*/
public class GuiTester extends JFrame{
public static void main(String[] args) {
// create new instance of JFrame
GuiTester s = new GuiTester();
// set the frame to be visible
s.setVisible(true);
}
/**
* Tester constructor calling method which initialise all widgets.
*/
GuiTester() {
//
invokeWidget();
}
/*
* This code is yours, just removed setting up the values of container and did that straight on the frame.
*/
void invokeWidget() {
setBounds(100, 100, 325, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JTextArea textArea = new JTextArea();
textArea.setEnabled(true);
textArea.setEditable(true);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
textArea.setWrapStyleWord(true);
add(scroll);
}
}
This is the line that was causing issues, as well as setting layout Manager to null.
// textArea.setBounds(10, 101, 272, 149);
I hope I helped, and if I'm wrong please correct me as well.
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!!!
I'm using JSplitPane includes two JScrollPane at each side. I don't know how to make them at equals size at start up. Here is my main code:
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
inputTextArea = new JTextArea();
outputTextArea = new JTextArea();
// put two TextArea to JScrollPane so text can be scrolled when too long
JScrollPane scrollPanelLeft = new JScrollPane(inputTextArea);
JScrollPane scrollPanelRight = new JScrollPane(outputTextArea);
// put two JScrollPane into SplitPane
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
scrollPanelLeft, scrollPanelRight);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(650); // still no effect
contentPane.add(splitPane, BorderLayout.CENTER);
I have used splitPane.setDividerLocation(getWidth() / 2); but still no effect.
Please tel me how to fix this.
For more detail. Here is my full code:
package com.view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
//import com.controller.Controller;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public JTextArea inputTextArea;
public JTextArea outputTextArea;
private JButton inputBtn;
private JButton outputBtn;
private JButton sortBtn;
public JRadioButton firstButton;
public JRadioButton secondButton;
public JRadioButton thirdButton;
JSplitPane splitPane;
//Controller controller;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
// controller = new Controller(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
/**
* center
* include two TextArea for display text
*/
inputTextArea = new JTextArea();
outputTextArea = new JTextArea();
// put two TextArea to JScrollPane so text can be scrolled when too long
JScrollPane scrollPanelLeft = new JScrollPane(inputTextArea);
JScrollPane scrollPanelRight = new JScrollPane(outputTextArea);
// put two JScrollPane into SplitPane
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
scrollPanelLeft, scrollPanelRight);
splitPane.setOneTouchExpandable(true);
contentPane.add(splitPane, BorderLayout.CENTER);
/**
* Top
* Include two button : SelectFile and WriteToFile
* this layout includes some tricky thing to done work
*/
// create new input button
inputBtn = new JButton("Select File");
// declare action. when user click. will call Controller.readFile() method
// (see this method for detail)
inputBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// controller.readFile();
}
});
// create new output button
outputBtn = new JButton("Write To File");
// declare action. when user click. will call Controller.writeFile() method
// (see this method for detail)
outputBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// controller.writeFile();
}
});
// put each button into seperate panel
JPanel tmpPanel1 = new JPanel();
tmpPanel1.add(inputBtn);
JPanel tmpPanel2 = new JPanel();
tmpPanel2.add(outputBtn);
// finnally. put those two pane into TopPane
// TopPane is GridLayout
// by using this. we can sure that both two button always at center of screen like Demo
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 2));
topPanel.add(tmpPanel1);
topPanel.add(tmpPanel2);
contentPane.add(topPanel, BorderLayout.NORTH);
/**
* Bottom panel
* Include all radionbutton and sortbutton
*/
// Group the radio buttons.
firstButton = new JRadioButton("Last Name");
secondButton = new JRadioButton("Yards");
thirdButton = new JRadioButton("Rating");
// add those button into a group
// so . ONLY ONE button at one time can be clicked
ButtonGroup group = new ButtonGroup();
group.add(firstButton);
group.add(secondButton);
group.add(thirdButton);
// create sor button
sortBtn = new JButton("Sort QB Stats");
// add action for this button : will Call Controller.SortFile()
sortBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// controller.sortFile();
}
});
// add all to bottomPanel
JPanel bottomPanel = new JPanel(new FlowLayout());
bottomPanel.add(firstButton);
bottomPanel.add(secondButton);
bottomPanel.add(thirdButton);
bottomPanel.add(sortBtn);
contentPane.add(bottomPanel, BorderLayout.SOUTH);
setContentPane(contentPane);
setTitle("2013 College Quarterback Statistics");
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
setVisible(true);
System.out.println("getwidth: " + getWidth());
splitPane.setDividerLocation(getWidth()/2);
}
}
Thanks :)
I got it right for you. I add this;
contentPane.add(splitPane, BorderLayout.CENTER);
splitPane.setResizeWeight(0.5); <------- here :)
And I got rid of the setDviderLocation() at the bottom
Inititally sets the resize wieght property. values are 0.0 to 1.0, a double value percentage to split the pane. There's a whole lot to exaplain about preferred sizes and such that I read about in the JSplitPane tutorial, so you can check it out for yourself.
It really depends on the exact behaviour you want for the split pane.
You can use:
splitPane.setResizeWeight(0.5f);
when you create the split pane. This affects how the space is allocated to each component when the split pane is resized. So at start up it will be 50/50. As the split pane increased in size the extra space will also be split 50/50;
splitPane.setDividerLocation(.5f);
This will only give an initial split of 50/50. As the split pane size is increased, the extra space will all go to the last component. Also, note that this method must be invoked AFTER the frame has been packed or made visible. You can wrap this statement in a SwingUtilities.invokeLater() to make sure the code is added to the end of the EDT.
Initially getWidth() size is 0. Add splitPane.setDividerLocation(getWidth()/2); after setvisible(true). Try,
// put two JScrollPane into SplitPane
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
scrollPanelLeft, scrollPanelRight);
splitPane.setOneTouchExpandable(true);
// still no effect
add(splitPane, BorderLayout.CENTER);
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
setVisible(true);// JFrame setVisible
splitPane.setDividerLocation(getWidth()/2); //Use setDividerLocation here.