JScrollPane上的JTextArea没有出现在JPanel上

时间:2018-11-21 00:32:59

标签: java swing jscrollpane jtextarea

我正在编写一个应该打印文本的程序。我需要将其放在JScrollPane上,并且还需要能够通过单击下一页按钮转到文本的下一页。

我可以显示任何文本的唯一方法是直接将文本添加到窗格中。 (第91行ctPanel.add(bText);

public class RP extends JPanel{

private Border simpleBorder;
private JPanel iPanel;
private JPanel ctPanel;
private JPanel nPanel;
private JLabel T; 
private JLabel A;
private JLabel P;
private JButton upButton;
private JButton downButton;
public JTextArea bText;
private JScrollPane Scroll;
private String placeholder;

public RP()
{

this.setPreferredSize(new Dimension(720,700));

simpleBorder = BorderFactory.createLineBorder(Color.GRAY);
//this.setBorder(BorderFactory.createTitledBorder(simpleBorder, "R"));
this.setLayout(new BorderLayout());

// start of i panel:

placeholder = new String("nothing right now");

iPanel = new JPanel();
this.add(iPanel, BorderLayout.NORTH);
iPanel.setBorder(BorderFactory.createTitledBorder(simpleBorder, "I"));

T = new JLabel();
T.setText("T: " + placeholder);
iPanel.add(T, BorderLayout.WEST);

A = new JLabel();
A.setText("B: " + placeholder);
iPanel.add(A, BorderLayout.CENTER);

P = new JLabel();
P.setText("P: " + placeholder);
iPanel.add(P, BorderLayout.EAST);


// start of ct panel (RP -> Ct Panel):

ctPanel = new JPanel();
ctPanel.setBorder(BorderFactory.createTitledBorder(simpleBorder, "C"));
ctPanel.setLayout(new BorderLayout());



// Create JScrollPane and add it to Ct Panel
Scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);



// create btext area
bText = new JTextArea();
bText.setEditable(false);
bText.setText("Nothing right now.");

//add text to scroll pane
Scroll.add(bText);



//add scroll pane to ct panel
ctPanel.add(Scroll, BorderLayout.CENTER);




//add ct panel to RP
ctPanel.add(bText); // IF I COMMENT THIS OUT, THE TEXT WON'T APPEAR IN THE 
CONTENT PANEL
this.add(ctPanel, BorderLayout.CENTER);

// start of navigation panel:

nPanel = new JPanel();
this.add(nPanel, BorderLayout.SOUTH);
nPanel.setBorder(BorderFactory.createTitledBorder(simpleBorder,"Navigation") 
);

upButton = new JButton();
upButton.setText("Up");
nPanel.add(upButton, BorderLayout.WEST);

downButton = new JButton();
downButton.setText("Down");
nPanel.add(downButton, BorderLayout.EAST);

// revalidate and repaint:  
this.revalidate();
this.repaint(); 
}       


// method to set text in bText JTextField from another class
public void setBText(String text)
{
bText.setText(text);
}

// method to set T info to i panel from another class
public void setTInfo(String text)
{
T.setText("T: " + text);
}

// method to set A info to i panel from another class
public void setAInfo(String text)
{
A.setText("B " + text);
}

}

1 个答案:

答案 0 :(得分:0)

首先,变量名称不应以大写字母开头。

Scroll.add(bText);

不要将组件直接添加到滚动窗格中。使用;

将组件添加到滚动窗格的viewport
//Scroll.add(bText);
scroll.setViewportView( bText );

一个组件也只能添加到一个组件中。所以摆脱:

//ctPanel.add(bText);

因为您已经将文本区域添加到了滚动窗格的视口中。