java - JCheckboxes 和 JButton 不随机显示

标签 java swing button user-interface layout-manager

我有一个基本的图形用户界面(它不需要看起来漂亮,它只需要工作。它是一个图形用户界面,用于显示我正在为论文实现的几种算法。)但是复选框和按钮不会显示随机的。有时它们会出现,有时则不会。老实说,我不知道为什么会发生这种情况,而且我在挥杆时非常疲惫,所以我迷路了。

编辑:这是我希望我的图形用户界面看起来像这样:

enter image description here

//import java.awt.*;
import java.awt.Dimension;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.*;

import javax.swing.ButtonGroup;

import javax.swing.*;  //notice javax
public class MapWindowController extends JFrame implements ActionListener, ItemListener
{
    private static final int WIDTH = 600, HEIGHT = 800;
    private static final int SETTINGS_WIDTH = 600, SETTINGS_HEIGHT = 200;
    private static final int NUM_MAP_TYPE = 2;
    private static final int NUM_ALGORITHM_TYPE = 4;
    private static final int MAP_IMAGE_SIZE = 400, ACTUAL_MAP_SIZE = 10;


    private JButton run;
    private JCheckBox[] map_type;
    private JCheckBox[] algorithm_type;
    JPanel panel = new JPanel();
    JPanel settings_panel = new JPanel();
    MapView map_view = new MapView(MAP_IMAGE_SIZE);
    SettingsButtonsPanel settings = new SettingsButtonsPanel();

    MapModel map_model = new MapModel(ACTUAL_MAP_SIZE, map_view);

    ButtonGroup bgMap;
    ButtonGroup bgAlgorithm;

    public MapWindowController()
    {

        setLocationRelativeTo(null);
        setTitle("HPA* Test");
        setSize(WIDTH, HEIGHT);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(panel);
        panel.setBounds(0, 0, 600, 800);
        panel.setLayout(null);
        /*GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;*/
        instantiateSettingsPanel();
        //panel.add(settings);
        /*c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 1;*/

        panel.add(map_view);
        map_view.setBounds(0,200,600,600);
        //button_panel.setBounds(0,0);
        map_view.repaint();

    }

    public void instantiateSettingsPanel() {
        settings_panel.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();

        //this.setLayout(null);

        map_type = new JCheckBox[NUM_MAP_TYPE];

        map_type[0] = new JCheckBox("Sparse");
        map_type[0].setSelected(true);

        map_type[1] = new JCheckBox("Maze");
        map_type[1].setSelected(false);

        algorithm_type = new JCheckBox[NUM_ALGORITHM_TYPE];

        algorithm_type[0] = new JCheckBox("A*");
        algorithm_type[0].setSelected(true);

        algorithm_type[1] = new JCheckBox("HPA*");
        algorithm_type[1].setSelected(false);

        algorithm_type[2] = new JCheckBox("TA*");
        algorithm_type[2].setSelected(true);

        algorithm_type[3] = new JCheckBox("PTHPA*");
        algorithm_type[3].setSelected(false);

        bgMap = new ButtonGroup( );
        bgAlgorithm = new ButtonGroup( );



        settings_panel.setMaximumSize(new Dimension(600,200));
        for(int i = 0; i < NUM_MAP_TYPE; i++)
        {
            bgMap.add(map_type[i]);
            map_type[i].addItemListener(this);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 0;
            c.gridy = i+1;
            settings_panel.add(map_type[i], c);
        }

        for(int i = 0; i < NUM_ALGORITHM_TYPE; i++)
        {
            bgAlgorithm.add(algorithm_type[i]);
            algorithm_type[i].addItemListener(this);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 1;
            c.gridy = i+1;
            settings_panel.add(algorithm_type[i], c);
        }

        run = new JButton("Run");
        run.addActionListener(this);
        settings_panel.add(run);
        panel.add(settings_panel);
        settings_panel.setBounds(0,0,SETTINGS_WIDTH,SETTINGS_HEIGHT);
    }

    public void itemStateChanged(ItemEvent e)
    {
        Object source = e.getItemSelectable();
        //if(source == )
    }

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();

        String algorithm = "A*";
        String map = "Sparse";
        for(int i = 0; i < algorithm_type.length; i++) {
            if(algorithm_type[i].isSelected()) {
                algorithm = algorithm_type[i].getText();
                break;
            }
        }

        for(int i = 0; i < map_type.length; i++) {
            if(map_type[i].isSelected()) {
                map = map_type[i].getText();
                break;
            }
        }

        if(source == run) {
            if(map.equals("Sparse")) 
                map_model.createRandomObstaclesSparse(10, 1);
            else
                map_model.createRandomObstaclesMaze(1);
            map_model.startPathfinding(algorithm, 0, true);
            map_view.setMapScale(ACTUAL_MAP_SIZE);
            map_view.setMapModel(map_model);
        }
    }
}

最佳答案

您的第一个错误是使用了 null 布局,第二个错误是在 UI 完成之前调用 setVisible

您的基本想法是正确的,将各个职责领域分成单独的组件,这将使您的生活更加轻松。

基本上,我使用了 GridBagLayout,因为它允许您定义每个组件的填充权重,为按钮和其余部分提供 1/4 垂直空间到 map ...

Map

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MapWindowController extends JFrame implements ActionListener, ItemListener {

    private static final int WIDTH = 600, HEIGHT = 800;
    private static final int SETTINGS_WIDTH = 600, SETTINGS_HEIGHT = 200;
    private static final int NUM_MAP_TYPE = 2;
    private static final int NUM_ALGORITHM_TYPE = 4;
    private static final int MAP_IMAGE_SIZE = 400, ACTUAL_MAP_SIZE = 10;

    private JButton run;
    private JCheckBox[] map_type;
    private JCheckBox[] algorithm_type;
    JPanel content = new JPanel();
    JPanel settings_panel = new JPanel();
    private JPanel mapPane = new JPanel(new BorderLayout());

    ButtonGroup bgMap;
    ButtonGroup bgAlgorithm;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                new MapWindowController();
            }
        });
    }

    public MapWindowController() {

        setLocationRelativeTo(null);
        setTitle("HPA* Test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        content.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weighty = 0.25;
        gbc.weightx = 1;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        content.add(settings_panel, gbc);
        gbc.gridy++;
        gbc.weighty = 0.75;
        content.add(mapPane, gbc);

        try {
            mapPane.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/Map.png")))));
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        add(content);
        /*GridBagConstraints c = new GridBagConstraints();
         c.fill = GridBagConstraints.HORIZONTAL;
         c.gridx = 0;
         c.gridy = 0;*/
        instantiateSettingsPanel();
        //panel.add(settings);
        /*c.fill = GridBagConstraints.HORIZONTAL;
         c.gridx = 0;
         c.gridy = 1;*/

        pack();
        setLocationByPlatform(true);
        setVisible(true);


    }

    public void instantiateSettingsPanel() {
        settings_panel.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();

        //this.setLayout(null);
        map_type = new JCheckBox[NUM_MAP_TYPE];

        map_type[0] = new JCheckBox("Sparse");
        map_type[0].setSelected(true);

        map_type[1] = new JCheckBox("Maze");
        map_type[1].setSelected(false);

        algorithm_type = new JCheckBox[NUM_ALGORITHM_TYPE];

        algorithm_type[0] = new JCheckBox("A*");
        algorithm_type[0].setSelected(true);

        algorithm_type[1] = new JCheckBox("HPA*");
        algorithm_type[1].setSelected(false);

        algorithm_type[2] = new JCheckBox("TA*");
        algorithm_type[2].setSelected(true);

        algorithm_type[3] = new JCheckBox("PTHPA*");
        algorithm_type[3].setSelected(false);

        bgMap = new ButtonGroup();
        bgAlgorithm = new ButtonGroup();

        settings_panel.setMaximumSize(new Dimension(600, 200));
        for (int i = 0; i < NUM_MAP_TYPE; i++) {
            bgMap.add(map_type[i]);
            map_type[i].addItemListener(this);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 0;
            c.gridy = i + 1;
            settings_panel.add(map_type[i], c);
        }

        for (int i = 0; i < NUM_ALGORITHM_TYPE; i++) {
            bgAlgorithm.add(algorithm_type[i]);
            algorithm_type[i].addItemListener(this);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 1;
            c.gridy = i + 1;
            settings_panel.add(algorithm_type[i], c);
        }

        run = new JButton("Run");
        run.addActionListener(this);
        settings_panel.add(run);
    }

    public void itemStateChanged(ItemEvent e) {
        Object source = e.getItemSelectable();
        //if(source == )
    }

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();

        String algorithm = "A*";
        String map = "Sparse";
        for (int i = 0; i < algorithm_type.length; i++) {
            if (algorithm_type[i].isSelected()) {
                algorithm = algorithm_type[i].getText();
                break;
            }
        }

        for (int i = 0; i < map_type.length; i++) {
            if (map_type[i].isSelected()) {
                map = map_type[i].getText();
                break;
            }
        }

        if (source == run) {
//            if (map.equals("Sparse")) {
//                map_model.createRandomObstaclesSparse(10, 1);
//            } else {
//                map_model.createRandomObstaclesMaze(1);
//            }
//            map_model.startPathfinding(algorithm, 0, true);
//            map_view.setMapScale(ACTUAL_MAP_SIZE);
//            map_view.setMapModel(map_model);
        }
    }
}

不要在窗口上使用setBoundssetSize,而是使用pack根据这是内容的首选大小。

关于java - JCheckboxes 和 JButton 不随机显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22598447/

相关文章:

java - 用java获取文件的第一行

java - 无法从 JTable 中的模型接收数据

java - 使用 JScrollPane 添加时 JTable 不可见

java - 将自身设置为 JFrame 的默认按钮的 JButton 子类

java - 如何更改未单击的按钮的背景颜色?

java - 在 Button/TextView 上使用 getDimension() 始终返回相同的值

wpf - 在 WPF : how to disable the animation when the button after be pressed? 中

java - 用一副纸牌填充堆栈 Java

java - 从包含json数据的字符串中提取json数据

java - org.springframework.beans.TypeMismatchException : Failed to convert value 'java.lang.String' to 'java.lang.Class' spring