Глядя на ваш пример, несколько вещей привлекли мое внимание.
Основная проблема в примере - отсутствие точки входа.Без точки входа вы не сможете запустить свой код.Чтобы определить действительную точку входа в 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);
}
}