每当我在 Java GUI 中按“清除”时,它都不起作用,请帮助我完成此操作。如果我用另一个按钮替换“textPanel”,它就可以工作,否则用“textpanel”就不行。
这是我的代码的轻量级版本,演示了该问题:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainFrame extends JFrame {
private TextPanel textPanel;
private FormPanel formpanel;
public MainFrame(){
super("My Frame");
createLayout();
createFrame();
}
public void createFrame(){
setSize(600, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void createLayout(){
BorderLayout myLayout = new BorderLayout();
setLayout(myLayout);
textPanel = new TextPanel();
formpanel = new FormPanel();
// adding components
add(textPanel, BorderLayout.CENTER);
add(formpanel, BorderLayout.WEST);
}
public static void main(String[] args){
new MainFrame();
}
public static class FormPanel extends JPanel {
private JButton clear;
private TextPanel textPanel;
public FormPanel(){
clear = new JButton("Clear Cart!");
textPanel=new TextPanel();
add(clear);
clear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent aev){
System.out.println("Test");
textPanel.setText("");
}
});
createGrid();
}
/* this methods simply creates the layout */
void createGrid(){
//creating layout
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.gridy++;
gc.weightx = .1;
gc.weighty = .1;
gc.gridx = 2;
gc.gridy=5;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0,0,0,0);
add(clear, gc);
}
}
public static class TextPanel extends JPanel {
private JTextArea textArea;
TextPanel (){
textArea = new JTextArea();
setLayout(new BorderLayout());
JScrollPane p = new JScrollPane(textArea);
add(p, BorderLayout.CENTER);
}
public void appendSomeText(String t){
textArea.append(t);
}
public void setText(String s){
textArea.setText(s);
}
}
}
最佳答案
您有两个 TextPanel
实例,一个在 MainFrame
中,另一个在 FormPanel
中。 FormPanel
中定义的 TextPanel
实际上并未添加到面板中,因此 textPanel.setText("");
对它没有任何影响,因为它是不可见的。
当文本附加 Add To Cart!
按钮时,它实际上会通过 MainFrame
中的一个方法 - formEventOccurred()
执行 textPanel.appendSomeText()
。这是 TextPanel
的另一个实例,它是 MainFrame
的一部分,并且实际上是可见的。
看起来您需要将重复的逻辑从主框架移动到面板。通常您不应该扩展JFrame
,因为您没有添加任何新功能。
关于java - textPanel.setText ("");不工作或不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22235899/