猿问

展开 J文本区域在网格包布局

我从来没有使用过网格袋布局,但我相信它可能是别的东西。目前,我正在尝试添加一个 TextArea,以充当正在执行的任何代码的控制台视口窗口。就目前而言,文本区域很小,实际上看不到任何文本。

我尝试查阅此页面以获取其中一个建议,但我仍然无法正确显示JTextArea。

代码粘贴在下面,如果您需要其他任何内容,请告诉我。我还附上了一张额外的图片,显示了它目前正在做什么。编辑:设置(); 是一个空的正文。

@SuppressWarnings("serial")

public abstract class MainComponent extends JPanel {


protected String componentName = "DEMO";


private JLabel title;

private GridBagConstraints gbc;

private Insets spacing; 

private Font buttonFont;


/*

 * Redirection manipulation for the project.

 */

private JTextArea localConsole;


public MainComponent(Dimension dim) {


    setup();


    /* Set main body */

    setLayout(new GridBagLayout());

    gbc = new GridBagConstraints();

    spacing = new Insets(100,5,100,5);

    buttonFont = new Font("Consolas", Font.ITALIC, 22);


    /* Set title */

    title = new JLabel(componentName);

    title.setFont(new Font("Consolas", Font.BOLD, 48));

    gbc.fill = GridBagConstraints.CENTER;

    gbc.gridx = 1;

    gbc.gridy = 0;

    add(title, gbc);


    JButton run = new JButton("Run Project");

    run.setFont(buttonFont);

    gbc.fill = GridBagConstraints.HORIZONTAL;

    gbc.insets = spacing;

    gbc.gridx = 0;

    gbc.gridy = 2;

    add(run, gbc);


    JButton open = new JButton("Open Codebase");

    open.setFont(buttonFont);

    gbc.fill = GridBagConstraints.HORIZONTAL;

    gbc.insets = spacing;

    gbc.gridx = 1;

    gbc.gridy = 2;

    add(open, gbc);


    JButton exit = new JButton("Exit Program");

    exit.setFont(buttonFont);

    gbc.fill = GridBagConstraints.HORIZONTAL;

    gbc.insets = spacing;

    gbc.gridx = 2;

    gbc.gridy = 2;

    add(exit, gbc);


}

http://img4.mukewang.com/6333edb50001a6a806540398.jpg

一只斗牛犬
浏览 130回答 1
1回答

慕仙森

给我们一个它目前所做的事情的图片并没有真正的帮助,因为我们不知道你想要实现什么,很难提出一个确切的建议。因此,所看到的是试图:在顶部显示 3 个按钮让文本区域填充底部的剩余空间因此,我建议您永远不需要使用单个布局管理器。很多时候,布局管理器的组合更容易。所以我建议你:使用边界布局作为主布局。为按钮创建一个面板,并添加到边框布局Page_START将滚动窗格添加到“边界布局”中。CENTER所以基本代码是:setLayout( new BorderLayout() );JPanel buttonsPanel = new JPanel();buttonsPanel.add(run);buttonsPane.add((open);buttonsPanel.add(exit);add(buttonsPanel, BorderLayout.PAGE_START);JTextArea textArea = new JTextArea(10, 30); // give text area a default preferred sizeadd(new JScrollPane(textArea), BorderLayout.CENTER);比尝试使用网格包布局更简单,代码更少。但是,如果您想练习使用网格包布局,请首先阅读有关如何使用网格包布局的 Swing 教程,以获取有关约束的更多信息。基本代码可能如下所示:gbc.gridx = 0;gbc.gridy = 0;add(run, gbc);gbc.gridx = 1;gbc.gridy = 0;add(open, gbc);gbc.gridx = 2;gbc.gridy = 0;add(exit, gbc);localConsole = new JTextArea(5, 20);JScrollPane scrollPane = new JScrollPane(localConsole);gbc.fill = GridBagConstraints.CENTER;gbc.gridx = 0;gbc.gridy = 1;gbc.gridwidth = 3; // try this with 1 and 2 to see the difference.add(scrollPane, gbc);也就是说,您不能只是随机使用网格x/网格宽度/网格高度值。组件需要显示在网格中。你不能在网格中留下间隙。因此,如果您希望按钮排成一行,则需要为相同的网格值按顺序递增 gridx。如果需要按钮下方的文本区域,请按顺序递增网格,并从新的 gridx 值开始。
随时随地看视频慕课网APP

相关分类

Java
我要回答