gpt4 book ai didi

java - 用于 GUI 应用程序的 JPanel

转载 作者:行者123 更新时间:2023-12-01 14:38:36 25 4
gpt4 key购买 nike

所以我自学 Java,但遇到了一点困难。对于其中一项练习,这是我无法理解的说明。任何解释帮助将不胜感激。这是我对遇到问题的部分的尝试。

import java.awt.Dimension;  
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ButtonPanel extends JPanel {


public ButtonPanel(JButton[] buttons, JTextArea textArea) {
//TODO: Create a sub-panel with a 4 row, 3 column GridLayout

setLayout(new GridLayout(4,3)); //Layout of subPanel1

JButton b1 = new JButton ("A");
JButton b2 = new JButton ("B");
JButton b3 = new JButton ("C");
JButton b4 = new JButton ("1");
JButton b5 = new JButton ("2");
JButton b6 = new JButton ("3");
JButton b7 = new JButton ("X");
JButton b8 = new JButton ("Y");
JButton b9 = new JButton ("Z");

add(b1);
add(b2);
add(b3);
add(b4);
add(b4);
add(b5);

//TODO: Populate the grid with buttons

//TODO: Add the grid panel to this panel

//TODO: Create a JScrollPane containing textArea

JButton cr = new JButton();

//TODO: Set the preferred size of the scroll pane to 80x120
setPreferredSize (new Dimension(80, 120));

//TODO: Add the scroll pane to this panel

}


}

最佳答案

这是一个基本概念。

要将组件添加到容器,您需要

  1. 创建容器
  2. 将布局管理器应用于该容器
  3. 将组件添加到该容器
  4. 将容器添加到父容器,该父容器(以某种方式)附加到顶级容器

例如

public void ButtonPanel(JButton[] buttons, JTextArea textArea) {
//TODO: Create a sub-panel with a 4 row, 3 column GridLayout

JPanel buttonPanel = new JPanel(new GridLayout(4,3)); //Layout of subPanel1

JButton b1 = new JButton ("A");
JButton b2 = new JButton ("B");
JButton b3 = new JButton ("C");
JButton b4 = new JButton ("1");
JButton b5 = new JButton ("2");
JButton b6 = new JButton ("3");
JButton b7 = new JButton ("X");
JButton b8 = new JButton ("Y");
JButton b9 = new JButton ("Z");

buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
buttonPanel.add(b4);
buttonPanel.add(b4);
buttonPanel.add(b5);

//TODO: Populate the grid with buttons

//TODO: Add the grid panel to this panel

//TODO: Create a JScrollPane containing textArea

JButton cr = new JButton();

//TODO: Set the preferred size of the scroll pane to 80x120
// This is a bad idea
setPreferredSize (new Dimension(80, 120));

//TODO: Add the scroll pane to this panel

}

花时间阅读并理解 Creating a UI with Swing

关于java - 用于 GUI 应用程序的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226116/

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