简体   繁体   English

JPanel的Java AWT边框不起作用

[英]Java awt border for for JPanel not working

For some reason my borders aren't showing for my panels and i am unsure why, is there something i'm missing? 由于某些原因,我的面板没有显示边框,我不确定为什么会丢失什么东西?

I have a main class which runs the frame class as well as other classes separate to the GUI 我有一个主类,它运行框架类以及与GUI分开的其他类

This is the code from my frame class: 这是我的框架类中的代码:

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);
            }
        });
    }
}

The frame.java takes its panels from MainFrame.java: 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);

    }
}

This calls up my three panels which look like this: 这将调出我的三个面板,如下所示:

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));
    }
}

when the code runs the window launches as full screen but no borders or possibly panels are visible. 当代码运行时,窗口以全屏模式启动,但是没有边框或面板可见。

Thanks for any help, sorry if my questions are tedious, i'm relatively new to programming. 感谢您的帮助,如果我的问题很乏味,对不起,我是编程的新手。

This is roughly what i want my panels to look like, eventually ill add in components to the panel and use GridBagConstraints to control the formatting 这大致是我希望面板看起来像的样子,最终将组件添加到面板中并使用GridBagConstraints来控制格式

在此处输入图片说明

// this creates the JPanels and sets their preferred sizes
JFrame frame = new MainFrame("Warlock of Firetop Mountain");

//this sets your size static contents -- after the above's been done!
Toolkit tk = Toolkit.getDefaultToolkit();
Frame.xsize = (int) tk.getScreenSize().getWidth();
Frame.ysize = (int) tk.getScreenSize().getHeight();

You're setting preferred sizes of all your JPanels to 0, 0, and so you're not seeing any borders. 您正在将所有JPanel的首选大小设置为0、0,因此看不到任何边框。 Your sizing is being created after you've created your JPanels, and this method of sizing looks dangerous to me. 创建JPanel后,将创建大小调整,这种大小调整方法对我来说很危险。


OK, thanks for posting an image of the desired GUI. 好的,感谢您发布所需GUI的图像。 My recommendations are: 我的建议是:

  • First and foremost, don't try setting sizes as you're doing. 首先,不要尝试在设置大小时尝试设置大小。
  • Instead, let the components and their layout managers size themselves. 而是让组件及其布局管理器自行调整大小。
  • Nest JPanels, each using its own layout manager to allow you to simply create complex GUI's. Nest JPanels,每个都使用其自己的布局管理器,使您可以简单地创建复杂的GUI。
  • When displaying images / ImageIcons, let them set the sizes of things as well. 在显示图像/ ImageIcons时,也让它们设置事物的大小。
  • If your GUI starts up with no icons displaying, consider creating a blank ImageIcon with a blank image of the right size as a placeholder icon. 如果您的GUI启动时没有显示任何图标,请考虑创建一个空白ImageIcon,并将其大小合适的空白图像作为占位符图标。

For example, something like this: 例如,如下所示:

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();
            }
        });
    }
}

Would create this realizable GUI: 将创建此可实现的GUI:

在此处输入图片说明

Note that the GUI is roughly made, has no functionality other than the enter and exit buttons. 请注意,GUI是大致制作的,除了Enter和Exit按钮外,没有其他功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM