import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Exec67 extends JFrame implements ActionListener{ JDialog win1,win2; public Exec67() { setTitle("Test"); setSize(400,400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); JMenuBar bar = new JMenuBar(); JMenuItem menu1 = new JMenuItem("正方形"); JMenuItem menu2 = new JMenuItem("三角形"); menu1.addActionListener(this); menu2.addActionListener(this); setJMenuBar(bar); bar.add(menu1);bar.add(menu2); win1 = new JDialog(this,true); win1.setLayout(new FlowLayout()); win1.setSize(200,200); win1.setTitle("正方形"); win1.setLocationRelativeTo(this); win1.add(new JLabel("输入边长:")); final JTextField input = new JTextField(6); final JTextField result = new JTextField(6); result.setEditable(false); win1.add(input); win1.add(new JLabel("计算结果:")); win1.add(result); JButton bt = new JButton("计算"); bt.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ double r = Double.valueOf(input.getText()); result.setText(String.format("%.3f", r*r)); } }); win1.add(bt); win2 = new JDialog(this,false); win2.setSize(200,200); win2.setLocationRelativeTo(this); win2.add(new JLabel("TEST TEST")); } /** * @param args */ public static void main(String[] args) { new Exec67().setVisible(true); } @Override public void actionPerformed(ActionEvent e) { JMenuItem menu = (JMenuItem)(e.getSource()); if (menu.getActionCommand().equals("正方形")) {win1.setVisible(true);win1.pack();} else win2.setVisible(true); } }
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)