[英]JAVA Swing: Can't append a text to a TextArea
如果我按下按钮,我只是尝试将文本 append 到文本区域。 我把它分开了,所以 textArea 在另一个名为 TextPanel 的 class 中制作了。 有趣的是,如果我按下该按钮,我也会将文本打印到控制台并且它可以在控制台上运行,只是不能将它 append 到我的 textArea ......这是我的代码:
工具栏.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Toolbar extends JPanel implements ActionListener{
private JButton helloButton;
private JButton goodbyeButton;
private TextPanel textPanel;
public Toolbar() {
helloButton = new JButton("Hello!");
goodbyeButton = new JButton("Goodbye!");
textPanel = new TextPanel();
helloButton.addActionListener(this);
goodbyeButton.addActionListener(this);
setLayout(new FlowLayout(FlowLayout.LEFT));
add(helloButton);
add(goodbyeButton);
}
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton)e.getSource();
if (clicked == helloButton) {
textPanel.appendText("Hello!\n");
System.out.println("Hello!\n");
}
else if (clicked == goodbyeButton) {
textPanel.appendText("Goodbye!\n");
System.out.println("Goodbye!\n");
}
}
/*
public void setTextPanel(TextPanel textPanel) {
this.textPanel = textPanel;
}
*/
}
文本面板.java
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextPanel extends JPanel{
private JTextArea textArea;
public TextPanel() {
textArea = new JTextArea();
setLayout(new BorderLayout());
add(new JScrollPane(textArea), BorderLayout.CENTER);
}
public void appendText(String text) {
textArea.append(text);
}
}
主机.java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;
public class MainFrame extends JFrame{
private JButton btn;
private TextPanel textPanel;
private Toolbar toolbar;
public MainFrame() {
super("My First JAVA Swing Window");
setLayout(new BorderLayout());
textPanel = new TextPanel();
toolbar = new Toolbar();
add(textPanel, BorderLayout.CENTER);
add(toolbar, BorderLayout.NORTH);
setSize(600,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
App.java
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class App {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame();
}
});
}
}
您需要使用add(textPanel);
由于添加了主要的 class 代码,因此得到了扩展答案: .
从工具栏 class 中删除textPanel = new TextPanel()
,取消注释setTextPanel
方法并在使用toolbar = new Toolbar()
创建工具栏后调用toolbar.setTextPanel(textPanel)
)。
问题是您正在创建两个 textPanel 实例,并且只修改了一个尚未添加到框架中的实例。
您是否尝试为JTextArea
设置初始大小?
您可以尝试使用setRows和setColumns
public TextPanel() {
textArea = new JTextArea();
textArea.setRows(10);
textArea.setColumns(10);
setLayout(new BorderLayout());
add(new JScrollPane(textArea), BorderLayout.CENTER);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.