JPanel的Java awt边框不工作

JPanel的Java awt边框不工作,java,swing,jpanel,awt,Java,Swing,Jpanel,Awt,由于某些原因,我的边框没有显示在面板上,我不确定为什么,我缺少了什么吗 我有一个主类,它运行frame类以及独立于GUI的其他类 这是我的框架类中的代码: import javax.swing.*; import java.awt.*; public class Frame { public static int xsize; public static int ysize; public static void main() { SwingU

由于某些原因,我的边框没有显示在面板上,我不确定为什么,我缺少了什么吗

我有一个主类,它运行frame类以及独立于GUI的其他类

这是我的框架类中的代码:

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

public class Frame
{
    public static int xsize;
    public static int ysize;

    public static void main()
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame frame = new MainFrame("Warlock of Firetop Mountain");

                //Implementing Toolkit to allow computer to get dimensions of screen and assign them to two int values
                Toolkit tk = Toolkit.getDefaultToolkit();
                Frame.xsize = (int) tk.getScreenSize().getWidth();
                Frame.ysize = (int) tk.getScreenSize().getHeight();

                frame.setTitle("Warlock of Firetop Mountain");
                frame.setSize(new Dimension(xsize, ysize));
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setResizable(true);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
frame.java从MainFrame.java获取其面板:

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

public class MainFrame extends JFrame
{
    private Panel1 storyPanel;
    private Panel2 statsPanel;
    private Panel3 commandsPanel;

    public MainFrame(String title)
    {
        super(title);

        // Setting Layout
        setLayout(new BorderLayout());

        storyPanel = new Panel1();
        statsPanel = new Panel2();
        commandsPanel = new Panel3();

        Container p = getContentPane();

        p.add(storyPanel, BorderLayout.WEST);
        p.add(statsPanel, BorderLayout.EAST);
        p.add(commandsPanel, BorderLayout.SOUTH);

    }
}
这将调用我的三个面板,如下所示:

import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Dimension;
import java.awt.Color;

public class Panel1 extends JPanel
{
    public Panel1()
    {
        //Set size of Panel1
        int xsizeP1 = (Frame.xsize / 2);
        int ysizeP1 = (Frame.ysize / 3 * 2);
        setPreferredSize(new Dimension(xsizeP1, ysizeP1));

        setBorder(BorderFactory.createLineBorder(Color.black));
    }
}
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;

@SuppressWarnings("serial")
public class TomGuiPanel extends JPanel {
    // rows and cols for jtextarea
    private static final int CURRENT_AREA_ROWS = 20;
    private static final int CURRENT_AREA_COLS = 40;

    // columns for command jtextfied
    private static final int COMMANDS_FIELD_COLS = 50;

    // size of GUI component gaps
    private static final int EB_GAP = 3;
    private static final int NUMBER_OF_OPTIONS = 5;

    // number if ImageIcons displayed within the user image char JList
    private static final int CHAR_IMG_VISIBLE_ROWS = 5;

    // a guess of the width of the largest image icon in the JList
    // You'd use a different number
    private static final int USER_IMG_CHAR_IMG_WIDTH = 70;

    private JTextArea currentTextArea = new JTextArea(CURRENT_AREA_ROWS, CURRENT_AREA_COLS);
    private JTextField commandsField = new JTextField(COMMANDS_FIELD_COLS);
    private EnterAction enterAction = new EnterAction("Enter");
    private DefaultListModel<Icon> charImgListModel = new DefaultListModel<>();
    private JList<Icon> charImgList = new JList<>(charImgListModel);

    public TomGuiPanel() {
        JPanel topBtnPanel = new JPanel(new GridLayout(1, 0, EB_GAP, EB_GAP));
        String[] btnTexts = { "Inventory", "Options", "Save", "Load" };
        for (String txt : btnTexts) {
            topBtnPanel.add(new JButton(txt));
        }

        JPanel characteristicsPanel = new JPanel(new GridBagLayout());
        addCharacteristics(characteristicsPanel, "HP", 20, 0);
        addCharacteristics(characteristicsPanel, "Attack", 12, 1);
        addCharacteristics(characteristicsPanel, "Defence", 8, 2);
        addCharacteristics(characteristicsPanel, "Agility", 9, 3);
        addCharacteristics(characteristicsPanel, "Luck", 2, 4);

        JScrollPane imgListPane = new JScrollPane(charImgList);
        imgListPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        charImgList.setVisibleRowCount(CHAR_IMG_VISIBLE_ROWS);
        charImgList.setPrototypeCellValue(createProtoType());

        JPanel rightPanel = new JPanel(new BorderLayout(EB_GAP, EB_GAP));
        rightPanel.add(topBtnPanel, BorderLayout.PAGE_START);
        rightPanel.add(imgListPane, BorderLayout.CENTER);
        rightPanel.add(characteristicsPanel, BorderLayout.LINE_END);

        JPanel optionsPanel = new JPanel(new GridLayout(1, 0));
        for (int i = 0; i < NUMBER_OF_OPTIONS; i++) {
            String text = "Option " + (i + 1);
            optionsPanel.add(new JCheckBox(text));
        }

        currentTextArea.setWrapStyleWord(true);
        currentTextArea.setLineWrap(true);
        currentTextArea.setFocusable(false);
        JScrollPane taScrollPane = new JScrollPane(currentTextArea);
        taScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(taScrollPane, BorderLayout.CENTER);
        centerPanel.add(rightPanel, BorderLayout.LINE_END);
        centerPanel.add(optionsPanel, BorderLayout.PAGE_END);

        JPanel commandsPanel = new JPanel();
        commandsPanel.setLayout(new BoxLayout(commandsPanel, BoxLayout.LINE_AXIS));
        commandsPanel.add(commandsField);
        commandsPanel.add(Box.createHorizontalStrut(EB_GAP));
        commandsPanel.add(new JButton(enterAction));
        commandsPanel.add(Box.createHorizontalStrut(EB_GAP));
        commandsPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
        commandsField.setAction(enterAction); // use same action for button and
                                              // text field

        setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
        setLayout(new BorderLayout(EB_GAP, EB_GAP));
        add(centerPanel, BorderLayout.CENTER);
        add(commandsPanel, BorderLayout.PAGE_END);
    }

    private void addCharacteristics(JPanel cPanel, String text, int value, int row) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.weightx = 1.0;
        gbc.weighty = 0.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        cPanel.add(new JLabel(text), gbc);

        gbc.insets.left = 20;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.gridx = 1;
        cPanel.add(new JLabel(String.valueOf(value)), gbc);

    }

    private Icon createProtoType() {
        int w = USER_IMG_CHAR_IMG_WIDTH;
        int h = w;
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Icon icon = new ImageIcon(img);
        return icon;
    }

    private class EnterAction extends AbstractAction {
        public EnterAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String text = commandsField.getText();
            currentTextArea.append(text + "\n");
            commandsField.selectAll();
        }
    }

    private class ExitAction extends AbstractAction {
        public ExitAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Component source = (Component) e.getSource();
            Window win = SwingUtilities.getWindowAncestor(source);
            win.dispose();
        }
    }

    private static void createAndShowGUI() {
        TomGuiPanel mainPanel = new TomGuiPanel();

        JFrame frame = new JFrame("Tom's GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
当代码运行时,窗口将全屏启动,但没有边框或可能的面板可见

谢谢你的帮助,如果我的问题很枯燥,很抱歉,我对编程还比较陌生

这大致就是我希望面板的外观,最终我将向面板中添加组件,并使用GridBagConstraints控制格式


您正在将所有JPanel的首选大小设置为0、0,因此看不到任何边界。您的大小是在创建JPanel之后创建的,这种大小调整方法对我来说很危险


好的,感谢您发布所需GUI的图像。我的建议是:

  • 首先也是最重要的是,不要像现在这样尝试设置尺寸
  • 相反,让组件及其布局管理器自行调整大小
  • 嵌套JPanel,每个都使用自己的布局管理器,允许您简单地创建复杂的GUI
  • 当显示图像/图像图标时,也可以让它们设置事物的大小 <> LI>如果你的GUI在没有图标显示的情况下启动,考虑创建一个空白图像图标,把空白大小的图像作为占位符图标。

例如,类似这样的内容:

import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Dimension;
import java.awt.Color;

public class Panel1 extends JPanel
{
    public Panel1()
    {
        //Set size of Panel1
        int xsizeP1 = (Frame.xsize / 2);
        int ysizeP1 = (Frame.ysize / 3 * 2);
        setPreferredSize(new Dimension(xsizeP1, ysizeP1));

        setBorder(BorderFactory.createLineBorder(Color.black));
    }
}
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;

@SuppressWarnings("serial")
public class TomGuiPanel extends JPanel {
    // rows and cols for jtextarea
    private static final int CURRENT_AREA_ROWS = 20;
    private static final int CURRENT_AREA_COLS = 40;

    // columns for command jtextfied
    private static final int COMMANDS_FIELD_COLS = 50;

    // size of GUI component gaps
    private static final int EB_GAP = 3;
    private static final int NUMBER_OF_OPTIONS = 5;

    // number if ImageIcons displayed within the user image char JList
    private static final int CHAR_IMG_VISIBLE_ROWS = 5;

    // a guess of the width of the largest image icon in the JList
    // You'd use a different number
    private static final int USER_IMG_CHAR_IMG_WIDTH = 70;

    private JTextArea currentTextArea = new JTextArea(CURRENT_AREA_ROWS, CURRENT_AREA_COLS);
    private JTextField commandsField = new JTextField(COMMANDS_FIELD_COLS);
    private EnterAction enterAction = new EnterAction("Enter");
    private DefaultListModel<Icon> charImgListModel = new DefaultListModel<>();
    private JList<Icon> charImgList = new JList<>(charImgListModel);

    public TomGuiPanel() {
        JPanel topBtnPanel = new JPanel(new GridLayout(1, 0, EB_GAP, EB_GAP));
        String[] btnTexts = { "Inventory", "Options", "Save", "Load" };
        for (String txt : btnTexts) {
            topBtnPanel.add(new JButton(txt));
        }

        JPanel characteristicsPanel = new JPanel(new GridBagLayout());
        addCharacteristics(characteristicsPanel, "HP", 20, 0);
        addCharacteristics(characteristicsPanel, "Attack", 12, 1);
        addCharacteristics(characteristicsPanel, "Defence", 8, 2);
        addCharacteristics(characteristicsPanel, "Agility", 9, 3);
        addCharacteristics(characteristicsPanel, "Luck", 2, 4);

        JScrollPane imgListPane = new JScrollPane(charImgList);
        imgListPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        charImgList.setVisibleRowCount(CHAR_IMG_VISIBLE_ROWS);
        charImgList.setPrototypeCellValue(createProtoType());

        JPanel rightPanel = new JPanel(new BorderLayout(EB_GAP, EB_GAP));
        rightPanel.add(topBtnPanel, BorderLayout.PAGE_START);
        rightPanel.add(imgListPane, BorderLayout.CENTER);
        rightPanel.add(characteristicsPanel, BorderLayout.LINE_END);

        JPanel optionsPanel = new JPanel(new GridLayout(1, 0));
        for (int i = 0; i < NUMBER_OF_OPTIONS; i++) {
            String text = "Option " + (i + 1);
            optionsPanel.add(new JCheckBox(text));
        }

        currentTextArea.setWrapStyleWord(true);
        currentTextArea.setLineWrap(true);
        currentTextArea.setFocusable(false);
        JScrollPane taScrollPane = new JScrollPane(currentTextArea);
        taScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(taScrollPane, BorderLayout.CENTER);
        centerPanel.add(rightPanel, BorderLayout.LINE_END);
        centerPanel.add(optionsPanel, BorderLayout.PAGE_END);

        JPanel commandsPanel = new JPanel();
        commandsPanel.setLayout(new BoxLayout(commandsPanel, BoxLayout.LINE_AXIS));
        commandsPanel.add(commandsField);
        commandsPanel.add(Box.createHorizontalStrut(EB_GAP));
        commandsPanel.add(new JButton(enterAction));
        commandsPanel.add(Box.createHorizontalStrut(EB_GAP));
        commandsPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
        commandsField.setAction(enterAction); // use same action for button and
                                              // text field

        setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
        setLayout(new BorderLayout(EB_GAP, EB_GAP));
        add(centerPanel, BorderLayout.CENTER);
        add(commandsPanel, BorderLayout.PAGE_END);
    }

    private void addCharacteristics(JPanel cPanel, String text, int value, int row) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.weightx = 1.0;
        gbc.weighty = 0.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        cPanel.add(new JLabel(text), gbc);

        gbc.insets.left = 20;
        gbc.anchor = GridBagConstraints.EAST;
        gbc.gridx = 1;
        cPanel.add(new JLabel(String.valueOf(value)), gbc);

    }

    private Icon createProtoType() {
        int w = USER_IMG_CHAR_IMG_WIDTH;
        int h = w;
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Icon icon = new ImageIcon(img);
        return icon;
    }

    private class EnterAction extends AbstractAction {
        public EnterAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String text = commandsField.getText();
            currentTextArea.append(text + "\n");
            commandsField.selectAll();
        }
    }

    private class ExitAction extends AbstractAction {
        public ExitAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Component source = (Component) e.getSource();
            Window win = SwingUtilities.getWindowAncestor(source);
            win.dispose();
        }
    }

    private static void createAndShowGUI() {
        TomGuiPanel mainPanel = new TomGuiPanel();

        JFrame frame = new JFrame("Tom's GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
导入java.awt.BorderLayout;
导入java.awt.Component;
导入java.awt.GridBagConstraints;
导入java.awt.GridBagLayout;
导入java.awt.GridLayout;
导入java.awt.Insets;
导入java.awt.Window;
导入java.awt.event.ActionEvent;
导入java.awt.event.KeyEvent;
导入java.awt.image.buffereImage;
导入javax.swing.*;
@抑制警告(“串行”)
公共类TomGuiPanel扩展了JPanel{
//jtextarea的行和列
私有静态最终int当前_区域_行=20;
专用静态最终int电流面积=40;
//命令jtextfied的列
私有静态final int命令\u FIELD\u COLS=50;
//GUI组件间隙的大小
专用静态最终int EB_间隙=3;
私有静态最终整数个选项=5;
//如果用户图像字符列表中显示图像图标,则编号
私有静态final int CHAR\u IMG\u VISIBLE\u ROWS=5;
//猜测JList中最大图像图标的宽度
//你应该用另一个号码
私有静态最终整数用户\u IMG\u字符\u IMG\u宽度=70;
私有JTextArea currentTextArea=新JTextArea(当前区域行、当前区域列);
私有JTextField commandsField=新JTextField(COMMANDS\u FIELD\u COLS);
私人企业行动企业行动=新企业行动(“进入”);
private DefaultListModel charImgListModel=新的DefaultListModel();
私人JList charImgList=新JList(charImgListModel);
公共TomGuiPanel(){
JPanel topBtnPanel=新JPanel(新网格布局(1,0,EB_间距,EB_间距));
字符串[]btnTexts={“库存”、“选项”、“保存”、“加载”};
用于(字符串txt:btnTexts){
添加(新的JButton(txt));
}
JPanel characteristicsPanel=新的JPanel(新的GridBagLayout());
添加特征(特征spanel,“HP”,20,0);
添加特征(特征spanel,“攻击”,12,1);
添加特征(特征“防御”,8,2);
addCharacteristics(characteristicsPanel,“敏捷性”,9,3);
addCharacteristics(characteristicsPanel,“运气”,2,4);
JScrollPane imgListPane=新的JScrollPane(charimglistpane);
imgListPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL\u SCROLLBAR\u ALWAYS);
charImgList.setVisibleRowCount(CHAR\u IMG\u VISIBLE\u ROWS);
setPrototypeCellValue(createProtoType());
JPanel rightPanel=新JPanel(新边界布局(EB_间隙,EB_间隙));
右面板。添加(topBtnPanel,BorderLayout.PAGE_START);
添加(imgListPane,BorderLayout.CENTER);
右面板。添加(特征面板、边界布局。线_端);
JPanel选项面板=新JPanel(新网格布局(1,0));
for(int i=0;i<选项的数量;i++){
String text=“Option”+(i+1);
添加(新的JCheckBox(文本));
}
currentTextArea.setWrapStyleWord(真);
currentTextArea.setLineWrap(真);
currentTextArea.setFocusable(假);
JScrollPane taScrollPane=新的JScrollPane(currentTextArea);
taScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL\u SCROLLBAR\u ALWAYS);
JPanel centerPanel=newjpanel(newborderlayout());
添加(taScrollPane,BorderLayout.CENTER);
中心面板。添加(右面板,边框布局。线条结束);
中心面板。添加(选项面板,边框布局。第页\结束);
JPanel commandsPanel=新的JPanel();
commandsPanel.setLayout(新的BoxLayout(commandsPanel,BoxLayout.LINE_轴));
commandsPanel.add(commandsField);
commandsPanel.add(框。创建水平支柱(EB_间隙));
commandsPanel.add(新JButton(entreaction));
commandsPanel.add(框。创建水平支柱(EB_间隙));
add(newjbutton(newexitAction(“Exit”,KeyEvent.VK_X));
commandsField.setAction(enterAction);//对按钮和
//文本字段
setBORDORDER(BorderFactory.createEmptyBorder(EB_GAP,EB_GAP,EB_GAP,EB_GAP));
setLayout(新边界布局(EB_GAP,EB_GAP));
添加(中心面板,BorderLayout.CENTER);
添加(commandsPanel,BorderLayout.PAGE_END);
}
私有void addCharacteristics(JPanel cPanel、字符串文本、int值、int行){
GridBagConstraints gbc=新的GridBagConstraints();