【发布时间】:2023-03-28 18:45:01
【问题描述】:
我想将 JPanel 类型的对象添加到 JFrame。
我正在尝试这个,但没有添加 Jpanel。
想法是:向 P2 添加一个 P5,该 P5 具有在类 P5 中定义的组件。
会发生什么?,我不想在 First_view 类中创建所有 JPanel,因为代码会很混乱。
代码:
import javax.swing.*;
import java.awt.*;
public class First_view extends JFrame {
Container Frame;
public First_view() {
super("title");
Frame = this.getContentPane();
Frame.setLayout(new BorderLayout());
Frame.add((new P2()), BorderLayout.WEST);
setSize(900, 500);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class P2 extends JPanel {
public P2() {
this.setLayout(new BorderLayout());
add((new P5()), BorderLayout.NORTH);
}
}
class P5 extends JPanel {
JScrollPane informacion = new JScrollPane(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JTextArea T1 = new JTextArea();
public P5() {
setLayout(new FlowLayout());
setBorder(BorderFactory.createEmptyBorder(20, 10, 0, 0));
add(setInformacion());
}
private JScrollPane setInformacion() {
T1.append("Information, bla bla bla");
T1.setEditable(false);
T1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
T1.setLineWrap(true);
informacion.add(T1);
informacion.setBorder(BorderFactory.createLineBorder(Color.BLACK));
return informacion;
}
}
图片:
【问题讨论】:
-
并且没有异常创建
JScrollPane? -
一般建议:1) 不要扩展
JFrame或JPanel,除非有必要这样做。这两个类都不需要。 2) 对类使用描述性名称,并学习常见的 Java 命名法(命名约定 - 例如EachWordUpperCaseClass、firstWordLowerCaseMethod()、firstWordLowerCaseAttribute,除非它是UPPER_CASE_CONSTANT)并始终如一地使用它。First_view应该是FirstView。P2应该类似于ApplicationContainer。 3) 为了尽快获得更好的帮助,请发布minimal reproducible example 或Short, Self Contained, Correct Example。 .. -
.. 4) 以最小尺寸提供 ASCII 艺术或 GUI 的 预期 布局的简单绘图,如果可调整大小,则具有更大的宽度和高度。 5) 源代码中的一个空白行是永远需要的。
{之后或}之前的空行通常也是多余的。 -
忽略 MCVE 的评论 - 我没有注意到
P5的定义包含在内,但我现在不会删除评论并重新编号。 :P 6)JTextArea T1 = new JTextArea();应该更像JTextArea T1 = new JTextArea(20,3); // suggest a size in columns & rows