Как разместить несколько панелей на jFrame? (Ява) - программирование
Подтвердить что ты не робот

Как разместить несколько панелей на jFrame? (Ява)

Layout wanted

Я в процессе создания своей собственной Java-игры. Моя игра рисуется хорошо на весь экран (там, где она говорит "рисовать графику здесь", но im живопись на весь jframe в данный момент). Я хочу добавить текстовое поле со строкой прокрутки для отображения текста только, не беру никакого ввода и другого текстового поля для ввода текстовых входов от пользователя, а затем кнопки для отправки текста для целей чата. Но на мой вопрос, как я даже начинаю это объяснять? Я понимаю, что мне нужен макет, но может ли кто-нибудь помочь мне в этом? Вот мой код на данный момент (этот код только устанавливает картину на весь экран в данный момент, нужно разделить экран вверх, как на картинке выше):

public class Setup extends JFrame implements Runnable{
     JPanel panel;
     JFrame window;
     public Setup(Starter start, JFrame window){
         window.setSize(600,500);
         window.setLocationRelativeTo(null);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setResizable(false);
         panel = new Display(start);
         this.window = window;
     }
     public void run(){
         window.getContentPane().add(panel);
         window.setBackground(Color.BLACK);
         window.setVisible(true);
     }
}

"new Display (start)" - это расширяет jpanel, в основном, там, где я рисую все графическое изображение.

Кроме того, я видел, как люди добавляли в разные панели, но я не могу иметь их одинакового размера. Как на картинке, панель "paint graphics here" является самой большой и т.д.

4b9b3361

Ответ 1

JPanel - фактически только контейнер, в который вы можете поместить в него разные элементы (даже другие JPanels). Поэтому в вашем случае я бы предложил один большой JPanel как своего рода основной контейнер для вашего окна. На этой основной панели вы назначаете Layout, который соответствует вашим потребностям (вот введение в макеты).

После того, как вы установите макет на свою основную панель, вы можете добавить панель рисования и другие JPanels, которые вы хотите (например, те, у которых есть текст в ней).

  JPanel mainPanel = new JPanel();
  mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

  JPanel paintPanel = new JPanel();
  JPanel textPanel = new JPanel();

  mainPanel.add(paintPanel);
  mainPanel.add(textPanel);

Это просто пример, который сортирует все подпанели вертикально (Y-Axis). Поэтому, если вы хотите, чтобы в нижней части вашего mainPanel (может быть, некоторые иконки или кнопки) были какие-то другие вещи, которые должны быть организованы с помощью другого макета (например, горизонтальный макет), просто создайте новый JPanel как контейнер для всех остальных вещей и установите setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS).

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

Или вы можете просто использовать NetBeans для написания своей программы. Там у вас есть довольно простой визуальный редактор (перетаскивание) для создания всех видов Windows и фреймов. (только понимание кода впоследствии... сложно иногда.)

ИЗМЕНИТЬ

Поскольку в этом вопросе есть много людей, я хотел бы представить полный пример того, как развернуть JFrame, чтобы он выглядел так, как это хочет OP.

Класс называется MyFrame и расширяет качели JFrame

public class MyFrame extends javax.swing.JFrame{

    // these are the components we need.
    private final JSplitPane splitPane;  // split the window in top and bottom
    private final JPanel topPanel;       // container panel for the top
    private final JPanel bottomPanel;    // container panel for the bottom
    private final JScrollPane scrollPane; // makes the text scrollable
    private final JTextArea textArea;     // the text
    private final JPanel inputPanel;      // under the text a container for all the input elements
    private final JTextField textField;   // a textField for the text the user inputs
    private final JButton button;         // and a "send" button

    public MyFrame(){

        // first, lets create the containers:
        // the splitPane devides the window in two components (here: top and bottom)
        // users can then move the devider and decide how much of the top component
        // and how much of the bottom component they want to see.
        splitPane = new JSplitPane();

        topPanel = new JPanel();         // our top component
        bottomPanel = new JPanel();      // our bottom component

        // in our bottom panel we want the text area and the input components
        scrollPane = new JScrollPane();  // this scrollPane is used to make the text area scrollable
        textArea = new JTextArea();      // this text area will be put inside the scrollPane

        // the input components will be put in a separate panel
        inputPanel = new JPanel();
        textField = new JTextField();    // first the input field where the user can type his text
        button = new JButton("send");    // and a button at the right, to send the text

        // now lets define the default size of our window and its layout:
        setPreferredSize(new Dimension(400, 400));     // let open the window with a default size of 400x400 pixels
        // the contentPane is the container that holds all our components
        getContentPane().setLayout(new GridLayout());  // the default GridLayout is like a grid with 1 column and 1 row,
        // we only add one element to the window itself
        getContentPane().add(splitPane);               // due to the GridLayout, our splitPane will now fill the whole window

        // let configure our splitPane:
        splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);  // we want it to split the window verticaly
        splitPane.setDividerLocation(200);                    // the initial position of the divider is 200 (our window is 400 pixels high)
        splitPane.setTopComponent(topPanel);                  // at the top we want our "topPanel"
        splitPane.setBottomComponent(bottomPanel);            // and at the bottom we want our "bottomPanel"

        // our topPanel doesn't need anymore for this example. Whatever you want it to contain, you can add it here
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS will arrange the content vertically

        bottomPanel.add(scrollPane);                // first we add the scrollPane to the bottomPanel, so it is at the top
        scrollPane.setViewportView(textArea);       // the scrollPane should make the textArea scrollable, so we define the viewport
        bottomPanel.add(inputPanel);                // then we add the inputPanel to the bottomPanel, so it under the scrollPane / textArea

        // let set the maximum size of the inputPanel, so it doesn't get too big when the user resizes the window
        inputPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75));     // we set the max height to 75 and the max width to (almost) unlimited
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));   // X_Axis will arrange the content horizontally

        inputPanel.add(textField);        // left will be the textField
        inputPanel.add(button);           // and right the "send" button

        pack();   // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
    }

    public static void main(String args[]){
        EventQueue.invokeLater(new Runnable(){
            @Override
            public void run(){
                new MyFrame().setVisible(true);
            }
        });
    }
}

Обратите внимание, что это только пример, и есть несколько подходов к оформлению окна. Все зависит от ваших потребностей, и если вы хотите, чтобы контент был изменчивым/отзывчивым. Другим действительно хорошим подходом будет GridBagLayout, который может обрабатывать довольно сложную компоновку, но также довольно сложно изучить.

Ответ 2

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

Просмотрите Визуальное руководство для менеджеров макетов для сравнения.

Вы можете использовать GridBagLayout, но один из самых сложных (и мощных) менеджеров компоновки, доступных в JDK.

Вместо этого вы можете использовать ряд составных менеджеров компоновки.

Я разместил графический компонент и текстовую область на одном JPanel, используя BorderLayout, с графическим компонентом в CENTER и текстовой областью в позиции SOUTH.

Я бы разместил текстовое поле и кнопку на отдельном JPanel с помощью GridBagLayout (потому что это самый простой способ, который я могу придумать для достижения желаемого результата)

Я бы разместил эти две панели на третьей, главной, панели, используя BorderLayout, с первой панелью в CENTER и второй в позиции SOUTH.

Но что я