我正在尝试制作一个GUI服务器到客户端消息程序。我写了网络端,那与问题无关。我正在尝试使用JScrollBar使JTextArea滚动。我该怎么做?这是我给客户端的代码(大部分网络代码已删除):
public class MyClient extends JFrame
{
public Client client;
public static Scanner scanner;
public JTextField textField;
public JLabel label;
public static String string;
public static JTextArea textArea;
public String username;
public JScrollBar scrollBar;
public JScrollPane scrollPane;
public MyClient()
{
setTitle("Client");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
textArea = new JTextArea("");
scrollBar = new JScrollBar();
label = new JLabel("Please enter your message");
add(label);
textField = new JTextField(70);
add(textField);
textField.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
textArea.append(username + ": " + textField.getText() + "\n"); textField.setText(null);
}
});
add(textArea);
add(scrollBar, BorderLayout.EAST);
string = textField.getText();
scanner = new Scanner(System.in);
}
class MyAdjustmentListener implements AdjustmentListener
{
public void adjustmentValueChanged(AdjustmentEvent e)
{
label.setText(" New Value is " + e.getValue() + " ");
repaint();
}
}
public static void main(String[] args) throws IOException
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
MyClient myClient = new MyClient();
myClient.setVisible(true);
myClient.setResizable(false);
}
});
}
}
最佳答案
您需要一个JScrollPane
而不是JScrollBar
,请尝试以下代码:
JTextArea textArea = new JTextArea ("");
JScrollPane scroll = new JScrollPane (textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
在上面的代码中,您正在为
textArea
分配ScrollPane
并使它滚动vertically
和horizontally
。另一种方法是,创建包含TextArea的ScrollPane,然后将“ vertical scroll = always”设置为on:
JTextArea textArea= new JTextArea();
JScrollPane scroll= new JScrollPane(textArea);
scroll. setVerticalScrollBarPolicy( JScrollPane. VERTICAL_SCROLLBAR_ALWAYS );
在此处阅读教程:Tutorial Link