Невозможно выполнить мое приложение, даже если компиляция прошла успешно - PullRequest
0 голосов
/ 10 марта 2019

Несмотря на то, что компиляция class внизу прошла успешно, я не могу заставить мой код работать.GUI просто не появляется.Короче говоря, я просто хочу, чтобы пользователь ввел произвольный int в javax.swing.JTextField, а затем показал "итальянское" представление его пользователю.Вот весь код моего приложения.

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class Example extends JFrame implements ActionListener {

    public ItalianStringNumberConversionFrame() {
        Container c = getContentPane();
        JButton button1 = new JButton("Convert");
        JTextField textField = new JTextField("Enter Integer: ");
        JPanel panel = new JPanel();
        JFrame frame = new JFrame();
        frame.setVisible(true);
        panel.setVisible(true);
        JLabel label1, label2;
        label1 = new JLabel("Enter an Integer to convert to Italian String:" );
        label2 = new JLabel("The text version of the number entered in Italian is: ");
        panel.add(label1,label2);
        panel.add(button1);
        panel.add(textField);
        c.add(panel);
    }

    public void actionPerformed(ActionEvent e) {
        new Example();
    }
}

1 Ответ

0 голосов
/ 10 марта 2019

Глядя на ваш пример, несколько вещей привлекли мое внимание.

Основная проблема в примере - отсутствие точки входа.Без точки входа вы не сможете запустить свой код.Чтобы определить действительную точку входа в Java , добавьте метод public static void main(java.lang.String[]) к существующему class.

public class Example
{
    public Example()
    {
        System.out.println("Hello world.");
    }

    public static void main(final String arguments)
    {
        new Example();
    }
}

Если вы используете интегрированную среду разработки, такую ​​как IntelliJ , вы можете просто щелкнуть зеленую стрелку рядом с методом public static void main(java.lang.String[]), чтобы выполнить вашу программу.

Далее вы используете Swing .В соответствии с документацией, вам необходимо вызвать ваш код, связанный с G- / UI , в потоке Event Dispatch , если не указано иное явным образом.

В общем, Swing не безопасен для потоков.Все компоненты Swing и связанные с ними классы, если не указано иное, должны быть доступны в потоке диспетчеризации событий.

Давайте применим это новое знание к вашему приложению!

public class ItalianStringNumberConversionFrame extends ...
{
    ...

    public static void main(final String[] arguments)
    {
        javax.swing.SwingUtilities.invokeLater(ItalianStringNumberConversionFrame::new);
    }
}

Там выидти.Мы еще не закончили.Ваш код Swing , скорее всего, не будет работать так, как вы ожидаете.

Давайте начнем с инициализации функционала javax.swing.JFrame.Хорошо, во-первых, никогда не расширяйте класс javax.swing.JFrame напрямую.Это просто очень плохой дизайн.Вместо этого попробуйте что-то вроде этого.

import java.awt.*;

import javax.swing.*;

public class Example
{
    public Example()
    {
        // Allocate a new instance of the class in question into memory. 
        JFrame jFrame = new JFrame("Hello world.");
        // Terminate the underlying VM when the user is trying to close the window.
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        // Define a custom width and height for the window.
        jFrame.setSize(new java.awt.Dimension(384, 288));
        // In a nutshell: center the window relative to the primary monitor.
        jFrame.setLocationRelativeTo(null);
        // Let's use a FlowLayout manager for the content pane. If you'd like to know more about layout managers or Swing in general, take a look at the link below.
        jFrame.getContentPane().setLayout(new FlowLayout());
        // Let's instantiate a few components for our content pane.
        JButton convert = new JButton("Perform the conversion!");
        JTextField number = new JTextField("");
        // Ensure that the text field is big enough.
        number.setPreferredSize(new Dimension(jFrame.getWidth() / 2, 16));
        JLabel description = new JLabel("Enter an int to convert into an italian string literal: ");
        JLabel result = new JLabel("And the resulting string literal is: \"?\".");
        // Add each component in the correct order to the content pane.
        jFrame.getContentPane().add(description);
        jFrame.getContentPane().add(number);
        jFrame.getContentPane().add(convert);
        jFrame.getContentPane().add(result);
        /* 
         * I saw that you tried to add an action listener to your button.
         * Because of that, I wanted to add a little example of how you can interact with each component by adding such a listener.
         */
        convert.addActionListener(lambda -> {
               System.out.println("Performing the conversion!");
               /*
                * I don't quite know what you mean by converting a number into an "italian" string literal, but here's my interpretation of that:
                * Here's how you can get the text of the text field. Note: if the text is not a number, an exception is thrown!
                */
               int not_an_italian_number_yet = Integer.valueOf(number.getText());
               // Let's change the text of the "result" component.
               result.setText("And the resulting string literal is: \"" + (not_an_italian_number_yet + " *insert italian accent here*") + "\".");
               // That's already it!
        });
        // Finally, show the window to the user!
        jFrame.setVisible(true);
    }

    public static void main(final String[] arguments)
    {
        SwingUtilities.invokeLater(Example::new);
    }
}
...