Кнопка заполняет всю ячейку в GridLayout, Java - PullRequest
3 голосов
/ 27 февраля 2012

Я новичок и делаю домашнее задание.Моя кнопка заполняет всю ячейку в gridLayout.Я читал о GridBagLayout, но моя книга ничего об этом не упоминает, поэтому я думаю, что в моем текущем коде просто ошибка.Учитель пытался помочь мне, но мы не можем понять это, поэтому я решил попробовать здесь.Любая помощь будет оценена!Вот что у меня есть:

package riddle;

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

public class Riddle implements ActionListener {
    private final String LABEL_TEXT = "Why did the chicken cross the road?";
    JFrame frame;
    JPanel contentPane;
    JLabel label, label1;
    JButton button;
    JButton button1;
    private static int i;

    public Riddle() {
        /* Create and set up the frame */
        frame = new JFrame(LABEL_TEXT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /* Create a content pane with a GridLayout and empty borders */
        contentPane = new JPanel();
        contentPane.setLayout(new GridLayout(0, 2, 10, 5));


        /* Create and add label that is centered and has empty borders */
        label = new JLabel("Why did the chicken cross the road?");
        label.setAlignmentX(JButton.LEFT_ALIGNMENT);
        label.setBorder(BorderFactory.createEmptyBorder(20, 50, 20, 50));
        contentPane.add(label);

        label1 = new JLabel(" ");
        label1.setAlignmentX(JButton.LEFT_ALIGNMENT);
        label1.setBorder(BorderFactory.createEmptyBorder(20, 50, 20, 50));
        contentPane.add(label1);

        /* Create and add button that is centered */
        button = new JButton("Answer");
        button.setAlignmentX(JButton.RIGHT_ALIGNMENT);
        button.setActionCommand("Show Answer");
        button.addActionListener(this);

        contentPane.add(button);

        /* Add content pane to frame */
        frame.setContentPane(contentPane);

        /* Size and then display the frame */
        frame.pack();
        frame.setVisible(true);
     }

    /** Handle button click action event
     * pre: 
     * post: clicked button shows answer
     */
    public void actionPerformed(ActionEvent event) {
        String eventName = event.getActionCommand();

        if (eventName.equals("Show Answer")) {
            label1.setText("To get to the other side. ");
            button.setText("Answer");
            button.setActionCommand("Answer");
        } 
    }

    /** 
     * Create and show the GUI
     */
    private static void runGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);

        Riddle greeting = new Riddle();
    }



    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                runGUI();
            }
        });
    }
}

1 Ответ

3 голосов
/ 27 февраля 2012

Вот цитата из учебника Swing о GridLayout :

Объект GridLayout размещает компоненты в сетке ячеек. каждый Компонент занимает все доступное пространство в своей ячейке, и каждая ячейка точно такой же размер.

Если ваша книга не говорит о такой важной вещи, это плохая книга, и я бы посоветовал использовать учебник по Swing. Я удивлен, что твой учитель не смог тебе этого сказать.

Если это поведение не того, которое вам нужно, выберите другой менеджер раскладки. Учебник по Swing содержит руководство для всех стандартных .

...