Как добавить функцию прокрутки в JComponent на JFrame? - PullRequest
0 голосов
/ 28 июня 2018

Мой графический интерфейс состоит из класса Diagram, который расширяет JFrame. Я создал другой класс с именем DrawingTool, который расширяет JComponent. Класс DrawingTool похож на область холста, позволяющую пользователям перетаскивать фигуры. Я также добавил панель кнопок в нижней части JFrame, чтобы пользователи могли нажимать различные кнопки, чтобы выбрать желаемую форму и действия управления. Я добавил панель кнопок и экземпляр класса DrawingTool в класс Diagram. Как сделать область холста (DrawingTool) прокручиваемой? То, как я пытался это сделать, не работает, я знаю, что что-то упустил.

Вот класс Diagram:

public class Diagram extends JFrame {
JButton serverButton, vipButton, arrowButton, undoButton, dragButton, loadButton, submitButton;
JButton applicationButton;
int currentAction = 1;
Graphics2D graphSettings;
Color strokeColor = Color.BLUE, fillColor = Color.BLACK;

/**
 * Constructor to generate new diagram with empty drawing board and button
 * panel.
 */
public Diagram() {
    // Define the defaults for the JFrame

    this.setSize(1000, 1000);
    this.setTitle("Diagram Tool");
    //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel buttonPanel = new JPanel();

    // Swing box that will hold all the buttons

    Box theBox = Box.createHorizontalBox();

    // Make all the buttons in makeButtons by calling helper function

    serverButton = makeButtons("Server", 2);
    vipButton = makeButtons("VIPs", 3);
    arrowButton = makeButtons("Arrow", 4);
    undoButton = makeButtons("Undo", 5);
    dragButton = makeButtons("Drag", 6);
    loadButton = makeButtons("Load", 11);
    applicationButton = makeButtons("Application", 8);
    submitButton = makeButtons("Submit", 12);

    // Add the buttons to the box

    theBox.add(serverButton);
    theBox.add(vipButton);
    theBox.add(applicationButton);
    theBox.add(arrowButton);
    theBox.add(undoButton);
    theBox.add(dragButton);
    theBox.add(loadButton);
    theBox.add(submitButton);

    // Add the box of buttons to the panel



    buttonPanel.add(theBox);

    // Position the buttons in the bottom of the frame

    JPanel container=new JPanel();
    container.add(new DrawingBoard(),BorderLayout.CENTER);
    JScrollPane jsp=new JScrollPane(container);
    this.add(buttonPanel, BorderLayout.SOUTH);
    this.add(jsp);

    // Make the drawing area take up the rest of the frame

    // Show the frame

    this.setVisible(true);
}

Вот класс DrawingBoard:

private class DrawingBoard extends JComponent implements MouseListener, MouseMotionListener {
    //declare variables

    /**
     * Constructor to initialize the drawing board
     */
    public DrawingBoard() {
        addMouseListener(this);
        addMouseMotionListener(this);

    //  initializeCanvas();
    }
   //Rest of the code for DrawingBoard 
  }

Вот так это выглядит сейчас. Я хотел бы сделать область серого холста прокручиваемой.

Изображение диаграммы

https://i.stack.imgur.com/nF9oL.png

1 Ответ

0 голосов
/ 29 июня 2018

То, что MadProgrammer сказал в комментариях, почти правильно. Вам нужно установить некоторую информацию, чтобы ваш ScrollPanel знал, как себя вести. Каков его собственный размер, размер компонентов внутри него и т. Д.

Так что обычно у вас будет ContentPane, и внутри него будет отображаться ваш контент. Чтобы создать прокручиваемую панель, вам нужно всего лишь поместить ScrollPane внутри вашей ContentPane, а затем установить область просмотра для вашей ScrollPane. Небольшой код, который я использовал полностью функциональным:

contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);

JScrollPane scrollPane = new JScrollPane();

//Vertical and Horizontal scroll bar policy is set to choose when the scroll will be visible    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBounds(0, 217, 414, 505);
scrollPane.setPreferredSize(new Dimension(414, 414));

JPanel viewport = new JPanel();
viewport.setLayout(null);
viewport.setBounds(0, 0, 414, 505);

//Create your components here, then:
//viewport.add(component)

viewport.setPreferredSize(new Dimension(414, 150));
scrollPane.setViewportView(viewport);
contentPane.add(scrollPane);

Все, что вы положите внутрь ViewPort будет автоматически прокручиваться, если его размер больше, чем PreferredSize.

Обратите внимание, что все размеры, которые я указал, приведены только для примера.

...