【发布时间】:2014-03-06 21:02:55
【问题描述】:
每当我在我的 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);
}
}
}
【问题讨论】:
-
你的问题是什么?
-
如何让我的清除按钮真正清除文本面板?
-
代码太过分了,请将此代码转储更改为SSCCE,没有人愿意查看所有内容。
-
按下按钮时是否有任何控制台输出?
-
我什么也没得到,它根本不影响 textPanel。
标签: java swing jbutton jtextarea settext