我是Java编程语言的新手,我尝试编写一个简单的代码
public class TextPanel extends JPanel {
private JTextArea textArea;
public TextPanel() {
textArea = new JTextArea();
setLayout(new BorderLayout());
setVisible(true);
add(new JScrollPane(textArea), BorderLayout.CENTER);
}
public String getTextAreaText() {
String text = textArea.getText();
return text;
}
}
我在星形按钮(startBtn
)中添加了一个动作监听器,但是当我运行该程序时,即使我在System.out.println(textPanel.getTextAreaText())
方法中放置actionPerformed()
,也无法在控制台中显示任何内容(代码如下) )。
public class Toolbar extends JPanel {
private JButton startBtn;
private JButton stopBtn;
private TextPanel textPanel;
public Toolbar() {
startBtn = new JButton("Start");
stopBtn = new JButton("Stop");
textPanel = new TextPanel();
setLayout(new FlowLayout(FlowLayout.LEFT));
add(startBtn);
add(stopBtn);
startBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(textPanel.getTextAreaText());
}
});
}
}
我需要帮助来解决这个问题。
答案 0 :(得分:2)
有关合适的资源,请查看Java和Swing代码的信息部分:
因此,请考虑添加一个创建JFrame的main方法,并将组件添加到JFrame中,例如:
private static void createAndShowGui() {
JFrame frame = new JFrame("My JFrame");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// add your components to your JFrame here
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
// the main method which Java uses as the starting point for your program
public static void main(String[] args) {
// let's call our Swing GUI in a thread-safe manner
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
修改强>
您的代码还显示了可能的变量阴影。您在工具栏类中创建一个TextPanel对象,但是您将此TextPanel添加到任何内容。这表明你可能在其他地方显示了一个TextPanel对象(我们只能猜测,因为看起来你没有显示足够的代码让我们确切知道)。如果是这样,那么按下开始按钮将从不显示工具栏的JTextArea获取文本。而是考虑将TextPanel引用传递给工具栏,如下所示:
class Toolbar extends JPanel {
private JButton startBtn;
private JButton stopBtn;
private TextPanel textPanel;
public Toolbar() {
startBtn = new JButton("Start");
stopBtn = new JButton("Stop");
// textPanel = new TextPanel(); // *** note change
setLayout(new FlowLayout(FlowLayout.LEFT));
add(startBtn);
add(stopBtn);
startBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
if (textPanel != null) {
System.out.println(textPanel.getTextAreaText());
}
}
});
}
// **** note this method ****
public void setTextPanel(TextPanel textPanel) {
this.textPanel = textPanel;
}
}
然后在创建对象时,传入您的参考:
private static void createAndShowGui() {
Toolbar toolBar = new Toolbar();
TextPanel textPanel = new TextPanel();
toolBar.setTextPanel(textPanel); // ****** passing in my reference *******
JFrame frame = new JFrame("Add New Lines");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(textPanel);
frame.getContentPane().add(toolBar, BorderLayout.PAGE_START);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}