JFrame при запуске программы форма не появляется - Java
Формулировка задачи:
Добрый день, начал осваивать Яву, и тут же наткнулся на первые грабли.
Создал приложение по этому пособию https://netbeans.org/kb/docs/java/gui-functionality_ru.html. Запускаю NumberAddition.jar и форма не появляется, только сообщение hello world:
Вот код главного класса:
А вот код формы:
Видимо эту форму надо как то вызвать из главного класса, но я не знаю как. В дельфи помню делал Form1.show() и все работало. Подскажите что может быть за ерунда? Стоит Netbeans 8.0.2.
Исходники прикладываю.
NumberAddition.zip
java -jar NumberAddition.jar Hello, World!
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package numberaddition;
/**
*
* @author skripov.in
*/
public class main {
/**
* @param args the command line arguments
*/
public static void main(String args[]){
System.out.println("Hello, World!");
}
}/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package numberaddition;
/**
*
* @author skripov.in
*/
public class NumberAdditionUI extends javax.swing.JFrame {
/**
* Creates new form NumberAdditionUI
*/
public NumberAdditionUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setText("jButton1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NumberAdditionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NumberAdditionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NumberAdditionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NumberAdditionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NumberAdditionUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}Решение задачи: «JFrame при запуске программы форма не появляется»
textual
Листинг программы
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package numberaddition;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
/**
*
* @author skripov.in
*/
public class Requester {
/**
* Метод читает из потока данные и преобразует в строку
* @param in - входной поток
* @param encoding - кодировка данных
* @return - данные в виде строки
*/
private String readStreamToString(InputStream in, String encoding) throws IOException {
StringBuffer b = new StringBuffer();
InputStreamReader r = new InputStreamReader(in, encoding);
int c;
while ((c = r.read()) != -1) {
b.append((char)c);
}
return b.toString();
}
public void postExample(String url, QueryString query) throws IOException {
//устанавливаем соединение
URLConnection conn = new URL(url).openConnection();
//мы будем писать POST данные в out stream
conn.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "ASCII");
out.write(query.toString());
out.write("\r\n");
out.flush();
out.close();
//читаем то, что отдал нам сервер
String html = readStreamToString(conn.getInputStream(), "UTF-8");
//выводим информацию в консоль
System.out.println("URL:" + url);
System.out.println("Html:\n" + html);
}
public String getExample(String url, QueryString query) throws IOException {
//устанавливаем соединение
URLConnection conn = new URL(url + "?" + query).openConnection();
//заполним header request парамеры, можно и не заполнять
conn.setRequestProperty("Referer", "http://google.com/http.example.html");
conn.setRequestProperty("Cookie", "a=1");
//можно установить и другие парамеры, такие как User-Agent
//читаем то, что отдал нам сервер
String html = readStreamToString(conn.getInputStream(), "UTF-8");
//выводим информацию в консоль
// System.out.println("URL:" + url);
// System.out.println("Html:\n" + html);
return html;
}
public String send() throws IOException {
QueryString q = new QueryString()
.add("login","admin")
.add("password", "pass");
Requester e = new Requester();
return e.getExample("http://juravskiy.ru/", q);
}
public static void main(String[] args) throws IOException {
QueryString q = new QueryString()
.add("login","admin")
.add("password", "pass");
Requester e = new Requester();
e.getExample("http://juravskiy.ru/", q);
e.postExample("http://juravskiy.ru/", q);
}
}