'next line'에 해당되는 글 1건

  1. 2021.12.27 FlowLayout 에서 component 가 다음 라인으로 이동시 panel resize

FlowLayout 에서 component 가 다음 라인으로 이동시 panel resize

프로그래밍/java 2021. 12. 27. 22:31
반응형

Resize 이벤트 발생시 JPanel의 높이를 마지막 component 에 맞추는 코드

package test.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

// resize panel
public class MainTest {
    public static void main(String[] args) {
        MainUI mainUI = new MainUI();
        mainUI.setVisible(true);
    }
}

class MainUI extends JFrame {
    FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT, 0, 0);
    JPanel resizePane = new JPanel(flowLayout);
    JButton testBtn1 = new JButton("TEST 1");
    JButton testBtn2 = new JButton("TEST 2");
    JButton testBtn3 = new JButton("TEST 3");
    JButton testBtn4 = new JButton("TEST 4");
    JButton testBtn5 = new JButton("TEST 5");
    JComponent lastComponent = testBtn5;

    MainUI() {
        setPreferredSize(new Dimension(500, 300));
        setLayout(new BorderLayout());

        resizePane.setBackground(Color.BLUE);
        resizePane.addComponentListener(new ComponentAdapter() {
            Point prevPoint = null;

            @Override
            public void componentResized(ComponentEvent e) {
                super.componentResized(e);
                if (prevPoint == null || prevPoint.y != lastComponent.getLocation().y) {
                    System.out.println("lastComonent moved to " + lastComponent.getLocation());
                    resizePane.setPreferredSize(new Dimension(resizePane.getPreferredSize().width, lastComponent.getLocation().y + lastComponent.getHeight()));
                    resizePane.updateUI();
                }
                prevPoint = lastComponent.getLocation();
            }
        });

        resizePane.add(testBtn1);
        resizePane.add(testBtn2);
        resizePane.add(testBtn3);
        resizePane.add(testBtn4);
        resizePane.add(testBtn5);
        add(resizePane, BorderLayout.NORTH);

        JPanel pane = new JPanel();
        pane.add(new JLabel("TEST TEST"));
        add(pane, BorderLayout.CENTER);

        pack();
    }
}

최초 실행

JPanel 크기 변경 1

JPanel 크기 변경 2

반응형
: