通过方法

时间:2017-10-05 17:54:27

标签: java jframe jscrollpane jtextarea

我正在尝试创建一个类,我可以通过调用不同的方法来创建一个JFrame来构建它。然而,在某些地方,我的JTextArea正在迷失......

下面是一个名为App的类,它包含了开始构建所需的方法......

public class App {
    private JFrame frame = new JFrame();
    private JTextArea textArea = new JTextArea();
    private JScrollPane scrollPane = new JScrollPane();

    public void openJFrame(String title, int x, int y){
        JFrame.setDefaultLookAndFeelDecorated(true);
        frame.setTitle(title);
        frame.setSize(x, y);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public JFrame getJFrame(){
        return frame;
    }
    public void addJTextArea(JScrollPane scrollPane){
        scrollPane.add(textArea);
        textArea.setLineWrap(true);
        textArea.setEditable(true);
        textArea.setVisible(true);
    }
    public JTextArea getJTextArea(){
        return textArea;
    }
    public void addJScrollPane(JFrame frame){
        frame.add(scrollPane);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    }
    public JScrollPane getJScrollPane(){
        return scrollPane;
    }

我想从我的main方法中调用这个类并构建一个JFrame。以下是我的尝试。

public class Main {
    public static void main(String[] args){
        App app = new App();

        app.addJTextArea(app.getJScrollPane());
        app.addJScrollPane(app.getJFrame());
        app.openJFrame("title", 500, 500);
    }

JFrame和ScrollPane会出现什么......但是我的文本区域似乎没有添加到滚动窗格。

我误解或忽略了什么吗?值得注意的是,如果在addJTextArea方法中我将其直接添加到JFrame而不使用它出现的JScrollPane方法(显然没有滚动窗格)

2 个答案:

答案 0 :(得分:2)

虽然JScrollPane可能看起来/行为/声音类似于JPanel,但事实并非如此。因此,使用JScrollPane.add()向滚动窗格添加组件可能听起来很自然,但却是错误的。 JScrollPane内部只能滚动一个组件,因此add()错误,但setViewportView()是要使用的方法。

您必须调整方法addJTextArea以使用scrollPane.setViewportView()代替scrollPane.add()

public void addJTextArea(JScrollPane scrollPane){
    scrollPane.setViewportView(textArea);
    textArea.setLineWrap(true);
    textArea.setEditable(true);
    textArea.setVisible(true);
}

答案 1 :(得分:1)

undefined替换为else if ((value === undefined || !value) && item.get(this.path)) { ... }

有关详细信息,请参阅How to Use Scroll Panes