使用 JTextFields 或 JTextAreas 创建矩阵
我必须制作一个程序,该程序必须能够以 Jtextfields 或 Jtextareas 的形式显示矩阵,以便用户可以在其中写入(每个 Jtextfield 的多个矩阵)。 问题是我不知道如何使用用户指定的 Jtextfields 的大小和数量(每次都不同)创建自定义 JPanel。 我已经用谷歌搜索了这个问题,但没有结果。
I have to do make a program that has to be able to show a matrix in form of Jtextfields or Jtextareas, so that the user can write in them(a number of the matrix for each Jtextfield).
The problem is that I have no idea how to create a custom JPanel with the size and quantity of Jtextfields that the user specifies(a different each time).
I have already googled the question, to no avail.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看一下 GridLayout。将网格与几个参数(行数和列数)放在一起非常简单。从 JavaDoc 中解释:
将导致
JTextFields
的 3 行 x 2 列网格编辑:
这里还有更多内容,在名为
Demo
的类中:Take a look at GridLayout. It is pretty simple to put together a grid together with a couple params (row and col count). To paraphrase from the JavaDoc:
would result in a 3 row by 2 col grid of
JTextFields
EDIT:
here is some more, in a class named
Demo
:首先,我将构建一个文本字段\区域的二维数组。当您获得用户输入时,您可以初始化数组并“新建”所有小部件。将它们全部添加到父面板\框架后,您可能需要根据已用尺寸进行一些计算并调整顶层窗口的大小。除此之外,正如已经建议的那样,GridLayout 对于直接父组件来说是一个不错的选择。
希望这有帮助。
First of all, I would build a 2d array of the text fields\areas. When you get the user input you can then initialize the arrays and "new up" all of the widgets. After adding all of them to the parent panel\frame you may have to do some calculation based on the used up size and resize your top level window. Aside from that, as already suggested, GridLayout will be a good choice for the direct parent component.
Hope this helps.
要在运行时更改外观,您所需要做的就是用新组件替换内容。
因此,根据您获取输入的方式,您可以用输入替换 akf 答案中给出的数字。
然后为了显示新面板,您可以将其添加到 JFrame 中并进行
分配,但是可能类似于子类化 JPanel 以显示矩阵。我从你的措辞中得到了这种印象。那么它是一个完全不同的解决方案。
如果您的唯一目标是实现一个可以编辑值的矩阵,那么 JTable 是迄今为止最简单的。将以下内容放入 JFrame
这也将简化使用 data.setRowCount( newValue ) 修改矩阵的高度和宽度。
To change the appearance at runtime, all you need to do is replace the content with new components.
So depending on how you get your input, you replace the numbers given in akf's answer with the input.
and then to show the new panel you add it in the JFrame with
Your assignment however might be something along the lines of subclassing a JPanel to show a matrix. I get that impression in your wording. Then its a whole different solution.
If your only goal is to implement a matrix where you can edit values a JTable is by far the simplest. Put the following in a JFrame
This would also simplify modifying the height and width of the matrix by using data.setRowCount( newValue ).