程序要求:在文本框中输入一个数字。点击按钮后,在窗口下半部画图。
图形根据输入的数字有所不同。需要将变量num、str传递到绘图方法中。
程序不能通过。程序如下,缩进已乱。良好格式请下载附件。
import java.awt.*;
import javax.swing.*;
import java.util.*; import java.awt.event.*;
public class program extends JFrame {
public static void main(String args[]) {
Demo myDemo=new Demo();
}
}
class ShapesPanel extends JPanel {
ShapesPanel() {
setBackground(Color.white);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setSize(350,200);
g.setColor(Color.red);
g.fillRect(1, 1, num*10, num*10);
g.drawString(str,100,100);
}
}
class Demo extends JFrame implements ActionListener {
JTextField input= new JTextField(4);
public Demo() {
setSize(800,600);
setLayout(new FlowLayout());
JButton start=new JButton("开始");
Container con=getContentPane();
con.add(new JLabel("请输入数字(1—10)"));
con.add(input);
con.add(start);
start.addActionListener(this);
con.add(new ShapesPanel());
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int num=Integer.parseInt(input.getText());
String str=input.getText();
}
}
------解决方案--------------------
首先类要大写
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ProgramA {
private JFrame frame;
private DrawPane drawPane;
private JTextField tf1;
public void createAndShowUI(){