我在使用 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");
}
}
}
});
}
}
我真的很陌生,我真的不知道从这里去哪里。感谢你的帮助。