【发布时间】:2013-08-29 04:56:36
【问题描述】:
我在使用 GridBagLayout 在 JTextArea 中添加 JScrollPane 时遇到问题。基本上,当不需要滚动条时程序运行良好,但布局变得混乱,内容在需要时被切断。相关代码如下
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class testGUI extends JFrame
{
public static String name;
static JTextField textfield = new JTextField(30);
static JTextArea textarea = new JTextArea(30,30);
public static void main( String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Checkem");
frame.setLocation(500,400);
frame.setSize(800,800);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JScrollPane scrolltxt = new JScrollPane(textarea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrolltxt.setWheelScrollingEnabled(true);
scrolltxt.getVerticalScrollBar().isVisible();
panel.add(scrolltxt, c);
JLabel label = new JLabel("Enter the Name of the file:");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2,2,2,2);
panel.add(label,c);
c.gridx = 0;
c.gridy = 1;
panel.add(textarea,c);
JButton button = new JButton("Search");
c.gridx = 1;
c.gridy = 1;
panel.add(button,c);
c.gridx = 1;
c.gridy = 0;
panel.add(textfield,c);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
Checkem record = new Checkem();
name = textfield.getText();
String [] print = record.run(name);
for (int i=0;i<print.length;i++)
{
if(print[i] == null || print[i].isEmpty())
{
continue;
}
else
{
textarea.append(print[i] + "\n");
}
}
}
});
}
}
我对挥杆真的很陌生,我真的不知道从这里往哪里走。感谢您的所有帮助。
【问题讨论】:
-
为什么不简单地使用
tArea.setLineWrap(true) and tArea.setWrapStyleWord(true)而不是定义ScrollBar策略,这在视图上甚至看起来不错:-) 请学习Java 命名约定并坚持下去,这会变得有点困难当有人在 Java 代码中使用非常规术语来理解代码时,乍一看:( -
此外,不要将
JTextArea添加到JPanel,而是将scrolltxt添加到相同的位置,因为JTextArea已经放置在JScrollPane内:-)
标签: java swing jscrollpane jtextarea gridbaglayout