gpt4 book ai didi

Java 布局挫败感

转载 作者:行者123 更新时间:2023-12-01 20:53:45 26 4
gpt4 key购买 nike

我需要 GUI 布局指导

将范围缩小到要点:

  • 我有三个主要的 JPanel(信息部分、操作和数据结构)
  • 如果不移动 JLabels,我就无法填充这些内容
  • 我需要一个子面板来进行网格布局的操作(无法得到这个去工作,现在真的很烦我)
  • 我需要它看起来像下图
  • 红色分隔线是可选的,使其更整洁

我的下一步是实现一个堆栈,但我想首先让它看起来正常。

/image/R7G2g.jpg

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class StackPanel extends JPanel {

JPanel west, westSub1, east, south, southSub1;
JTextArea infoText, popText, pushText, peekText, resultText;
JLabel aTitle, bTitle, cTitle, Result;
JButton push, pop, peek, test;

public StackPanel() {

// Creating JPanels
setLayout(new BorderLayout());
west = new JPanel();
westSub1 = new JPanel(new GridLayout(3,2));
east = new JPanel();
south = new JPanel();
west.add(westSub1);

// Creating JLabels / JTextArea
aTitle = new JLabel("Operations");
bTitle = new JLabel("Data Structure Contents");
cTitle = new JLabel("Information");
infoText = new JTextArea("This is where commands will be displayed.");
pushText = new JTextArea("pushtxt");
popText = new JTextArea("poptxt");
peekText = new JTextArea("g");
resultText = new JTextArea("");
west.add(aTitle);
westSub1.add(pushText);
westSub1.add(popText);
westSub1.add(peekText);
westSub1.add(resultText);
east.add(bTitle);
south.add(cTitle);
south.add(infoText);

// Creating & Adding JButtons
push = new JButton("PUSH");
pop = new JButton("POP") ;
peek = new JButton("PEEK");
test = new JButton("TEST");
westSub1.add(push);
westSub1.add(pop);
westSub1.add(peek);
westSub1.add(test);

// Setting the placements of GUI objects
add(west, BorderLayout.WEST);
add(east, BorderLayout.CENTER);
add(south, BorderLayout.SOUTH);

// Declaring JPanel sizes // Width|Height
west.setPreferredSize(new Dimension(200,200));
east.setPreferredSize(new Dimension(400,100));
south.setPreferredSize(new Dimension(100,150));

// Setting black borders for JPanels
west.setBorder(BorderFactory.createLineBorder(Color.black));
east.setBorder(BorderFactory.createLineBorder(Color.black));
south.setBorder(BorderFactory.createLineBorder(Color.black));

// Setting JPanel background colours
west.setBackground(new Color(234,237,242));
east.setBackground(new Color(255,255,255));
south.setBackground(new Color(240,240,240));
}

}

最佳答案

也许您可以使用 TitledBorder,而不是在每个西/东/南面板的顶部使用标签。这将在面板周围放置一条矩形线,并在顶部显示标题。

阅读 Swing 教程中关于 How to Use Borders 的部分了解更多信息和工作示例。

如果您不想这样做,那么您可能需要将默认的 FlowLayout 或每个面板更改为其他布局。例如,您可以使用 BorderLayout。然后将标签添加到 PAGE_START 并将其他组件添加到 CENTER。要点是您可以嵌套具有不同布局的面板来实现您想要的布局。

关于Java 布局挫败感,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42750256/

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