2017-10-05 78 views
0

我想要创建一个类,在该类中可以通过调用不同的方法来创建JFrame。然而沿着我的JTextArea是迷路线...某处当通过方法构建时,JTextArea不会出现在JScrollPane中

下面是一个名为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; 
    } 

我想打电话从这个类我的主要方法并建立一个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的和滚动窗格出现什么happense。但是我的文字区域似乎没有被添加到滚动窗格。

我误解或忽略了某些东西?这可能是值得一提的是,如果在addJTextArea方法我直接将它添加到JFrame中不使用它出现在JScrollPane的方法(显然没有滚动窗格)

回答

2

虽然JScrollPane可能看起来/ ACT /听起来类似于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); 
}