我创建了一个JFrame,我在其中创建了JTextArea。我已将此JTextArea作为构造函数传递给另一个类。 JFrame如下:
JFrame frame = new JFrame("Find");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JTextArea textArea = new JTextArea(20,15);
frame.add(textArea,BorderLayout.NORTH);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
Texts text = new Texts(textArea);
frame.add(text.pane(),BorderLayout.CENTER);
JScrollPane pane = new JScrollPane(textArea);
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
JOptionPane.showMessageDialog(null, "Thank you for using finder");
System.exit(0); //Close program
}
});
}
我已将JTextArea传递给其他类但是它没有显示在JFrame中,只显示了按钮。:
公共课文本{
public JTextArea tx;
JTextField findField = new JTextField( 10);
int pos = 0;
public Texts(JTextArea textArea) {
// TODO Auto-generated constructor stub
tx=textArea;
tx.setVisible(true);
}
public Component pane() {
// TODO Auto-generated method stub
JButton findButton = new JButton("Find");
JButton clearButton = new JButton("Clear");
JPanel header = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
header.add(findField, gbc);
gbc.gridx++;
header.add(findButton, gbc);
tx.add(header, BorderLayout.SOUTH);
header.add(clearButton);
findButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Get the text to find...convert it to lower case for easier comparison
String find = findField.getText();
// Focus the text area, otherwise the highlighting won't show up
tx.requestFocusInWindow();
// Make sure we have a valid search term
if (find != null && find.length() > 0) {
Document document = tx.getDocument();
..........
答案 0 :(得分:0)
首先你这样做......
frame.add(textArea,BorderLayout.NORTH);
然后你这样做......
JScrollPane pane = new JScrollPane(textArea);
这有效地从帧中删除textArea
,这是因为组件只能有一个父组件。
相反,尝试类似......
JScrollPane pane = new JScrollPane(textArea);
frame.add(pane,BorderLayout.NORTH);