gpt4 book ai didi

java - 在 JPanel 中的每个元素周围添加边框

转载 作者:行者123 更新时间:2023-11-29 08:31:50 28 4
gpt4 key购买 nike

我有一个 JPanel,我要在网格内部添加 25 个 JPanel。我希望每个面板周围都有一个边框,这样您就可以清楚地区分每个元素。填充也可以。如果我尝试添加边框,我将面板添加到面板的方式会将其应用于包含元素的较大面板。

public class LightsOutView

{ GridLayout experimentLayout = new GridLayout(5, 5);

// Creates layout of the GUI
public LightsOutView ()
{
JFrame frame = new JFrame();
frame.setTitle("Lights Out");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setContentPane(makeContents());
frame.setVisible(true);
}

/**
* Creates the blank game board. Returns the panel
*
* @return JPanel
*/
public JPanel makeContents ()
{
// Create a panel to hold the 5x5 grid
JPanel board = new JPanel(new GridLayout(5, 5));
board.setLayout(experimentLayout);

// Add the components to the panel
for (int i = 0; i < 25; i++)
{
board.add(new JPanel()).setBackground(Color.YELLOW);
}

// Return the panel
return board;
}

如何在每个元素周围添加边框。我是否需要更改向网格添加面板的方式?

最佳答案

一种方式:

将您的 GridLayout 更改为如下内容:

GridLayout experimentLayout = new GridLayout(5, 5, gap, gap);

其中 gap 是一些小的 int 值,比如 1 到 3(对于像素)。然后给背景容器一个背景颜色,它会透过缝隙显示出来。您还需要为背景 JPanel 提供具有相同间隙宽度的线条边框。

例如:

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;

@SuppressWarnings("serial")
public class GridWithBorders extends JPanel {
private static final int SIDES = 6;
private static final int SIDE_LENGTH = 60;
private static final int GAP = 3;
private static final Color BG = Color.BLACK;
private static final Color CELL_COLOR = Color.GREEN.darker();

public GridWithBorders() {
setBackground(BG);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new GridLayout(SIDES, SIDES, GAP, GAP));
Dimension prefSize = new Dimension(SIDE_LENGTH, SIDE_LENGTH);
for (int i = 0; i < SIDES; i++) {
for (int j = 0; j < SIDES; j++) {
JPanel cell = new JPanel();
cell.setBackground(CELL_COLOR);
cell.setPreferredSize(prefSize);
add(cell);
}
}
}

private static void createAndShowGui() {
GridWithBorders mainPanel = new GridWithBorders();

JFrame frame = new JFrame("GridWithBorders");
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(() -> createAndShowGui());
}
}

关于java - 在 JPanel 中的每个元素周围添加边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47384707/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com