D
D
Dima2015-11-10 01:54:39
Java
Dima, 2015-11-10 01:54:39

How to make JList scroll horizontally?

Hello, while a newbie, tell me how to solve the problem.
I don't understand why JList horizontal scroll is not displayed. The JList is added to the panel in BorderLayout.WEST, as there will be a table in the center, buttons on the right, etc.
I tried different options (I commented in the code). Googled, but apparently there is a nuance with BorderLayout.WEST.

What I want is approximately - i.imgur.com/1PxEoeQ.jpg , here in the eclipse on the left, although there is a JTree, but the point is - there is a horizontal scroll if the text does not fit, and apparently the JTree is in the BorderLayout.WEST area.

The code:

import java.awt.BorderLayout;
import javax.swing.*;
public class ListDemo {

  private JFrame frame;

  private JPanel mainPanel;

  public ListDemo() {

    createPartControl();
  }

  private void createPartControl() {
    frame = new JFrame();
    frame.setTitle("JList Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    createMainPanel();

    frame.add(new JScrollPane(mainPanel));
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
  }

  private void createMainPanel() {
    mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());

    String[] words = { "Word1", "Word2", "Word2", "Word4", "Word5", "very long worddddddddddddddd" };
    JList<String> list = new JList<>(words);
    // list.setFixedCellWidth(100);
    JScrollPane pane = new JScrollPane(list);
    // pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    mainPanel.add(list, BorderLayout.WEST);

  }

  public static void main(String[] args) {
    new ListDemo();
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kornachev, 2015-11-10
@dmds

instead of a sheet,
you need to insert a scrollpane with a sheet
. In your case, when the window is resized, the topmost scrollpane will work. pack will calculate the dimensions in such a way that all components fit into the viewport and do not include scrolling.

frame.add(new JScrollPane(mainPanel)); //от скролла лучше избавиться
frame.pack(); //а паком нужно уметь пользоваться,  для многих компонентов нужно указывать предпочтительный размер иначе pack может натворить дел.Я не пользуюсь им вовсе.

It is better to remove this scrollpane, and set the preferred sizes of the components.
For example, if you add the initialization of the preferred sizes of the scrollbar with the sheet.
then everything should work as you need.
In general, switch to JavaFX, everything is easier there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question