JScrollPane 上的 JTextArea 未出现在 JPanel 上

JTextArea on JScrollPane not appearing on JPanel

我正在编写一个应该打印文本的程序。我需要它在 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);
}

}

首先变量名不能以大写字符开头。

Scroll.add(bText);

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

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

另外一个组件只能添加到一个组件中。所以去掉:

//ctPanel.add(bText);

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