编写程序,实现如图所示功能:在宽高文本框中输入数值,当单击“更改”按钮时,将窗体大小改为文本框中输入值,单击“退出”时,退出应用程序。
----------------解决方案--------------------------------------------------------
贴一个代码,随便写的,不过能运行:)
class LabelPanel extends JPanel { JTextField width, hight;
LabelPanel() { add(new JLabel(\"宽\")); width = new JTextField(10); add(width);
add(new JLabel(\"高\")); hight = new JTextField(10); add(hight); } }
class MyFrame extends JFrame { private LabelPanel panel = new LabelPanel(); public MyFrame() { setTitle(\"窗口大小\"); setSize(300, 200);
Container contentPane = getContentPane(); contentPane.add(panel, BorderLayout.CENTER); contentPane.add(new ButtonPanel(), BorderLayout.SOUTH); } private class ButtonPanel extends JPanel implements ActionListener { JButton modify = new JButton(\"更改\"); JButton quit = new JButton(\"退出\"); public ButtonPanel() { modify.addActionListener(this); quit.addActionListener(this);
add(modify); add(quit); }
public void actionPerformed(ActionEvent e) { Object source = e.getSource();
if(source == modify) { String width = panel.width.getText(); String hight = panel.hight.getText(); if(width.equals(\"\") || hight.equals(\"\")) JOptionPane.showMessageDialog(MyFrame.this, \"Please enter the data!\"); else { int w = Integer.parseInt(width); int h = Integer.parseInt(hight); MyFrame.this.setSize(w, h); } } else if(source == quit) { System.exit(0); } } } }
public class EventTest { public static void main(String[] args) { MyFrame test = new MyFrame(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.show(); } }
----------------解决方案--------------------------------------------------------