문제

Here is the code:

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

public class TestGrid {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Colored Trails");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4, 9));
        panel.setMaximumSize(new Dimension(9*30-20,4*30));

        JButton btn;
        for (int i=1; i<=4; i++) {
            for (int j=1; j<=4; j++) {
                btn = new JButton();
                btn.setPreferredSize(new Dimension(30, 30));
                panel.add(btn);
            }

            btn = new JButton();
            btn.setPreferredSize(new Dimension(30, 10));
            panel.add(btn);

            for (int j=1; j<=4; j++) {
                btn = new JButton();
                btn.setPreferredSize(new Dimension(30, 30));
                panel.add(btn);
            }

        }
        mainPanel.add(panel);
        frame.add(mainPanel);

        frame.setSize(450,950);
        frame.setVisible(true);
    }
}

I suppose to have a table of buttons with 4 rows and 9 columns. And the middle column should be narrower that other columns. I tried Dimension(30, 10) and Dimension(30, 10) both have no effect on the width of the middle column. Why?

도움이 되었습니까?

해결책

Layout managers are free to ignore the preferred size. Specifically, GridLayout will always make each cell in the grid exactly the same size (it's a pretty useless layout manager for that reason).

You'll have to use a different layout manager, such as nested BoxLayout or a GroupLayout.

다른 팁

호스트 웹의 색상을 사용하려면 일부 JavaScript로 호스트 웹 스타일 시트를 동적으로로드해야합니다.페이지에서 jQuery를 사용하는 경우 다음 JavaScript 블록을 사용하여 호스트 웹 스타일 시트를 페이지에 주입 할 수 있습니다.

(function () {
    // Retrieve the host web's URL from the query string
    var scriptbase = $.queryString('SPHostUrl') + '/_layouts/15/';

    // Create a <link> tag for the style sheet
    var $doclink = $('link').attr('rel', 'stylesheet');
    // The style sheet is loaded through an ASP.NET HTTP handler (defaultcss.ashx)
    $doclink.attr('href', scriptbase + 'defaultcss.ashx');

    // Add the style sheet link to the 
    $('head').append($doclink);
})();
.

이 작동하지 않으면 Microsoft의 기사 방법 : jQuery가 필요하지 않은 예는 SharePoint 앱에서 SharePoint 웹 사이트의 스타일 시트를 사용합니다.

setPreferredSize will not change the size of the button until dimension is set by using Dimension.

Example:-

Dimension dim = new Dimension(20,20), then use setPerferredSize(dim).

I found this method version, that fits perfect to your solution:

.addComponent(<<a jButton instance>>, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, <<put here an integer to set you max width button size>>)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top