import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Sqrt2 extends JFrame { private JLabel label = new JLabel("Här visas roten"); private JTextField text = new JTextField("Skriv talet här"); private JButton button = new JButton("Visa rot!"); private ButtonListener bl = new ButtonListener(); public Sqrt2() { super("Sqrt2"); button.addActionListener(bl); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(text); cp.add(button); cp.add(label); } // Inre klass för att lyssna på knapp class ButtonListener implements ActionListener { // Hantera klick på roten-ur-knapp public void actionPerformed(ActionEvent event) { String numbuf = text.getText(); try { float num = Float.parseFloat(numbuf); float res = (float)Math.sqrt(num); if (Float.isNaN(res)) label.setText("Det måste vara ett positivt tal."); else label.setText("Roten ur " + num + " är " + res); } catch (NumberFormatException exc) { label.setText("'" + numbuf + "' är inte ett tal."); } } // actionPerformed } // class ButtonListener public static void main(String[] args) { String laf = UIManager.getSystemLookAndFeelClassName(); try { UIManager.setLookAndFeel(laf); // If you want the Cross Platform L&F instead, replace // UIManager.getSystemLookAndFeelClassName() // with // UIManager.getCrossPlatformLookAndFeelClassName() } catch (UnsupportedLookAndFeelException exc) { System.err.println("Warning: UnsupportedLookAndFeel: " + laf); } catch (Exception exc) { System.err.println("Error loading " + laf + ": " + exc); } Sqrt2 frame = new Sqrt2(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 100); frame.setVisible(true); } } // class Sqrt2