看不到TextField和Button为什么啊。
package defaults;
import java.awt.Color;
import java.awt.Container;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Counter {
public static void main(String[] args)
{
JFrame frame = new CounterFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class CounterFrame extends JFrame{
public static final int WIDTH = 250;
public static final int HEIGHT = 150;
private TextField textField = new TextField(20);
public CounterFrame(){
setSize(WIDTH,HEIGHT);
setTitle("Counter");
Container contentPane = getContentPane();
JPanel textPanel = new JPanel();
textField.setBackground(new Color(10,10,10));
textPanel.add(textField);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel,"start",new ActionListener(){
public void actionPerformed(ActionEvent evt){
addCounter();
}
});
}
public void addButton(Container c,String title,ActionListener listener){
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
public void addCounter(){
for (int i =0;i<50;i++){
try{
textField.setText(Integer.toString(i));
Thread.sleep(50);
}catch(InterruptedException e){
}
}
}
}
[解决办法]
你没有textPanel,buttonPanel加入到容器中,而且给容器添加布局器、
[解决办法]
楼上正解:
import java.awt.Color;import java.awt.Container;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.BorderLayout;//引入布局管理器。import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;public class Counter{ public static void main(String[] args) { JFrame frame = new CounterFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); }}class CounterFrame extends JFrame{ public static final int WIDTH = 250; public static final int HEIGHT = 150; private TextField textField = new TextField(20); public CounterFrame() { setSize(WIDTH,HEIGHT); setTitle("Counter"); Container contentPane = getContentPane(); JPanel textPanel = new JPanel(); textField.setBackground(new Color(255,255,255));//换成白底。 textPanel.add(textField); contentPane.add(textPanel,BorderLayout.NORTH);//添加 textPanel. JPanel buttonPanel = new JPanel(); addButton(buttonPanel,"start",new ActionListener() { public void actionPerformed(ActionEvent evt) { addCounter(); } }); contentPane.add(buttonPanel,BorderLayout.SOUTH);//添加buttoPanel. } public void addButton(Container c,String title,ActionListener listener) { JButton button = new JButton(title); c.add(button); button.addActionListener(listener); } public void addCounter() { for (int i =0;i<50;i++) { try { textField.setText(Integer.toString(i)); Thread.sleep(50); } catch(InterruptedException e) { } } }}