我有一个功能齐全的基于控制台的数据库,我需要向其中添加 GUI。我创建了一个选项卡页(当前只有一个选项卡),其中包含一个“显示所有学生”按钮,该按钮在触发时将显示 JTextArea 内的学生列表,该列表当然位于其自己的类中,而不是在按钮的操作监听器类中。问题是,按钮的操作监听器内部无法识别 JTextArea。如果我将参数添加到操作监听器中,则会出现更多错误。帮忙?
我已经在 Stack Overflow 上搜索了类似的问题,但是当我在代码中尝试它时,并没有真正解决问题?或者也许我只是需要轻轻一推我的头脑。无论如何。
这是迄今为止我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StudDatabase extends JFrame
{
private JTabbedPane tabbedPane;
private JPanel studentPanel;
private static Scanner input = new Scanner(System.in);
static int studentCount = 0;
static Student studentArray[] = new Student[500];
public StudDatabase()
{
setTitle("Student Database");
setSize(650, 500);
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create the tab pages
createStudentPage();
// more tabs later...
// Create a tab pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Student Admin", studentPanel );
topPanel.add( tabbedPane, BorderLayout.CENTER );
}
public void createStudentPage()
{
studentPanel = new JPanel();
studentPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton listButton = new JButton("List All Student(s)");
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(studentCount > 0)
{
for(int i=0; i<studentCount; i++)
{
// print out the details into JTextArea
// ERROR! textDisplay not recognised!!!
textDisplay.append("Student " + i);
}
System.out.printf("\n");
}
else // no record? display warning to user
{
System.out.printf("No data to display!\n\n");
}
}
});
studentPanel.add(listButton);
JTextArea textDisplay = new JTextArea(10,48);
textDisplay.setEditable(true); // set textArea non-editable
JScrollPane scroll = new JScrollPane(textDisplay);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
studentPanel.add(scroll);
}
public static void main(String[] args)
{
StudDatabase mainFrame = new StudDatabase();
mainFrame.setVisible(true);
}
最佳答案
您的代码不起作用,其原因与此不起作用:
int j = i+5;
int i = 4;
在 Java 中使用变量之前必须声明它们。
其次,为了使用 inner class 内部的变量(本地或实例) - 这就是您的 ActionListener
的内容 - 您需要将其设为 final
。
因此,以下代码将编译并运行:
final JTextArea textDisplay = new JTextArea(10,48);
...
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
...
textDisplay.append("Student " + i);
关于java - 从位于另一个类中的 JButton 的 actionPerformed 更改 JTextArea 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23861650/