我正在尝试制作一个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);
}
});
}
}发布于 2014-05-27 04:29:01
您将需要一个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,然后设置垂直滚动= always on:
JTextArea textArea= new JTextArea();
JScrollPane scroll= new JScrollPane(textArea);
scroll. setVerticalScrollBarPolicy( JScrollPane. VERTICAL_SCROLLBAR_ALWAYS ); 点击这里阅读教程:Tutorial Link
发布于 2014-05-27 04:26:45
只需在JScrollPane中添加JTextArea,然后在容器中添加JScrollPane,而不是添加JTextArea本身。
不需要添加JScrollBar,如果需要,默认情况下会显示滚动条。
示例代码:
textArea = new JTextArea("");
scrollPane = new JScrollPane(textArea);在此处查找工作示例How can we add JScrollPane on JTextArea in java?
我在你的代码中注意到了一些要点:
JFrame默认布局更改为FlowLayoutsetLayout(新的FlowLayout());
BorderLayout属性添加组件add(scrollBar,BorderLayout.EAST);
注意:首先在容器中添加组件,例如JPanel,然后最后在JFrame中添加JPanel。
请再读一遍A Visual Guide to Layout Managers,并为您的应用程序设计选择合适的布局管理器。
https://stackoverflow.com/questions/23877214
复制相似问题