使用JPanel Java自动调整JFrame大小

Ang*_*ing 5 java swing resize jpanel jframe

我正在实施对扫雷游戏的改变.其中一个问题就是难度.我已经设法做到这一点并且它的工作,但随着游戏板(在它自己的Jpanel中)变得更大和更小(取决于难度),我无法让JFrame自动调整大小.我在用:

setPreferredSize(new Dimension(WIDTH, HEIGHT));
Run Code Online (Sandbox Code Playgroud)

设置窗口的初始大小,但这使它真的很小,就像只显示JMenuBar中的'File'一词一样.我必须手动调整大小.

我在ActionListener事件上尝试了setSize()和frame.pack()之类的东西,但我似乎无法让它调整大小.

关于使用什么代码/方法的任何提示.

编辑:已发布的代码

package mines;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class SetupFrame extends JFrame {

    private final int WIDTH = 600;
    private final int HEIGHT = 500;
    public JFrame frame;
    public JMenuBar menubar;
    public JMenu file;
    public JMenu levels;
    public JMenu help;
    public JMenuItem login;
    public JMenuItem save;
    public JMenuItem resume;
    public JMenuItem exit;
    public JMenuItem easy;
    public JMenuItem medium;
    public JMenuItem hard;
    private JLabel statusbar;
    public JPanel main;
    public JPanel buttonPanel;
    public JPanel saved;
    public JPanel game;
    public Board mineGame;
    public JButton ngButton;
    public JButton undoButton;
    public JButton redoButton;
    public JTabbedPane tp;
    public String[] levelPicker;
    public JComboBox levelSelect;
    public JFileChooser chooser;
    public String filename;

    public int difficulty;

    public SetupFrame(){

      frame = new JFrame();

      String filename = JOptionPane.showInputDialog(frame, "Enter Your Name.");

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


      setLocationRelativeTo(null);
      setTitle("Minesweeper");

      //menubar, menus, menu items
      menubar = new JMenuBar();
      setJMenuBar(menubar);

      file = new JMenu("File");
      help = new JMenu("Help");

      menubar.add(file);
      menubar.add(help);

      login = new JMenuItem("Login..");
      save = new JMenuItem("Save..");
      resume = new JMenuItem("Resume..");
      exit = new JMenuItem("Exit");

      file.add(login);
      file.add(save);
      file.add(resume);
      file.addSeparator();
      file.add(exit);

      statusbar = new JLabel("");



      chooser = new JFileChooser(); // new File Chooser for saved tab
      undoButton = new JButton(" Undo "); //undo Button for game panel 
      ngButton = new JButton(" New Game ");//new game Button for game panel
      redoButton = new JButton(" Redo");//redo Button for game panel

      main = new JPanel(new BorderLayout()); //new panel for main game
      //main.add(mineGame, BorderLayout.CENTER); //add instance mineGame to main panel

      game = new JPanel(new BorderLayout());// new panel for game tab
      main.add(game, BorderLayout.CENTER); //add the mineGames panel to game panel
      game.add(statusbar, BorderLayout.SOUTH); //add statusbar to bottom of game panel
            //game.add(button, BorderLayout.NORTH); // add buttons (eventually be redo, undo, new game)

      saved = new JPanel(); // create new panel for the saved tab
      saved.add(chooser);//add the File Chooser to the saved tab

      String[] levelPicker = {"Easy", "Medium", "Hard"};
      levelSelect = new JComboBox(levelPicker);
      levelSelect.setSelectedIndex(0);
            //levelSelect.addActionListener(this);

       buttonPanel = new JPanel();
       buttonPanel.add(undoButton);
       buttonPanel.add(ngButton);
       buttonPanel.add(redoButton);
       buttonPanel.add(levelSelect);
       main.add(buttonPanel, BorderLayout.NORTH);

       //create & add the tabs
       tp = new JTabbedPane();
       tp.addTab ("Game", main);
       tp.addTab ("Saved", saved);
       tp.addTab ("Statistics", null);
       add(tp);

       setPreferredSize(new Dimension(WIDTH, HEIGHT));
       setResizable(true);
       setVisible(true);
       frame.pack();


        class listener implements ActionListener{
            public void actionPerformed (ActionEvent e)
            {   
                if(e.getSource() == ngButton){
                    //JOptionPane.showInputDialog(frame, "Do You want To Save");
                    newMineGame();
                }
                JComboBox cb = (JComboBox)e.getSource();
                String picker = (String)cb.getSelectedItem();
                if (picker == "Easy"){
                    difficulty = 0;
                    newMineGame();
                }
                if (picker == "Medium"){
                    difficulty = 1;
                    newMineGame();
                    frame.pack();
                }
                if (picker == "Hard"){
                    difficulty = 2;
                    newMineGame();
                    frame.pack();
                }
            }


            private void newMineGame() {
                game.removeAll();
                mineGame = new Board(statusbar, difficulty);
                game.add(mineGame, BorderLayout.CENTER);
                game.add(statusbar, BorderLayout.SOUTH);
                repaint();
            }

        }

        ngButton.addActionListener(new listener());
        undoButton.addActionListener(new listener());
        redoButton.addActionListener(new listener());
        levelSelect.addActionListener(new listener());


    }

public static void main(String[] args) {
        new SetupFrame();

    }
Run Code Online (Sandbox Code Playgroud)

mKo*_*bel 7

其中一个问题就是难度.我已经设法做到这一点并且它的工作,但随着游戏板(在它自己的Jpanel中)变得更大和更小(取决于难度),我无法让JFrame自动调整大小.

在ActionListener事件上尝试了setSize()和frame.pack()之类的东西,但我似乎无法让它调整大小.

  • JFrame.pack() 以防万一

    1. 所有JComponents代表地雷(有最好的使用方法JToggleButton)都正确地PreferredSize返回其父(JPanel)

    2. 由GridLayout奠定的父(JPanel)(非常简单)

    3. 有两种方式,何时,何地 JFrame.pack()

      • 使用CardLayout,接下来的代码行后swithching CardJFrame.pack()

      • 删除旧JPanel(从JFrame)并替换为新,然后您需要调用JFrame.(re)validate(),JFrame.repaint()JFrame.pack()作为最后的代码行

  • 也许还有另一个问题,重要的是在有设置的情况下的代码排序 JFrame.setResizable(false);


编辑后

  • 使用Cardlayout

  • 你错过了代码行(不要扩展JFrame,创建这个对象Local variable)JFrame.(re)validate(),JFrame.repaint()以及JFrame.pack()最后的代码行private void newMineGame() {


但我不明白你的意思是:"你错过了代码行(不要扩展JFrame,将此Object创建为Local变量);

代码可以

import javax.swing.*;

public class SetupFrame {

    private JFrame frame;
    private JMenuBar menubar = new JMenuBar();
    private Board mineGame;

    public SetupFrame() {
        //there add required JComponents

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setTitle("Minesweeper");
        frame.setJMenuBar(menubar);
        frame.add(mineGame);
        //frame.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        //frame.setResizable(true);//not neccessary
        frame.pack();
        frame.setVisible(true);
    }

    private void newMineGame() {
        //remove old Board
        //add a new Board
        frame.validate();
        frame.repaint();
        frame.pack();
    }

    private static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SetupFrame();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)


dic*_*c19 7

这是你的错:

frame.pack();

frame如果您的SetupFrame实际延伸,为什么还需要JFrame?只需改变这一行pack()就可以了.

@mKorbel已经发布了关于pack()行为的完整且非常有用的解释(谢谢).

更新

同样在你的listener课堂上,当你JButton按下时你会得到这个例外:

java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JComboBox
Run Code Online (Sandbox Code Playgroud)

你需要做一些改变以避免这种情况:

class listener implements ActionListener{

    public void actionPerformed (ActionEvent e) {
        if(e.getSource() == ngButton){
            //JOptionPane.showInputDialog(frame, "Do You want To Save");
            newMineGame();
        } else if(e.getSource() instanceof JComboBox){ // add this else-if block
            JComboBox cb = (JComboBox)e.getSource();
            String picker = (String)cb.getSelectedItem();
            if (picker.equals("Easy")){ // <-- picker == "Easy" is not the proper way to compare string, use equals() method instead
                difficulty = 0;
                newMineGame();
            }
            if (picker.equals("Medium")){
                difficulty = 1;
                newMineGame();
                //frame.pack();  <--- again, just use pack();
                pack();
            }
            if (picker.equals("Hard")){
                difficulty = 2;
                newMineGame();
                //frame.pack();  <--- again, just use pack();
                pack();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

或者更好的是,使用一个实现ItemListener来监听JComboBox选择更改ActionListener