I am trying to do a simple Jform and call it from another class.
I want to use this Jframe in a server client application, but I don't know how to open the JFrame class from another class.
Like user has to chose
1- to open Jframe.
2- To Exit.
So What am I doing wrong?
Below are the codes:
Jframe Class named Calculas.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author user
*/
public class Calculas extends javax.swing.JFrame {
/**
* Creates new form Calculas
*/
public Calculas() {
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() {
a1Text = new javax.swing.JTextField();
a2Text = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
answer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60)
.addComponent(jLabel1)
.addGap(34, 34, 34)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int a;
a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
answer.setText("Answer" + a);
// TODO add your handling code here:
}
/**
* #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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculas.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 Calculas().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField a1Text;
private javax.swing.JTextField a2Text;
private javax.swing.JLabel answer;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Test Class named Test.java
public class Test extends JFrame {
public static void main(String args[])
{
Calculas CAL = new Calculas();
CAL.Calculus();
}
}
Forgive me if this is naive, as Im not anything of a Java programmer...
But isnt it just because you need to set visible?
Calculas CAL = new Calculas();
CAL.setVisible(true);
The constructor of Calculas doesn't show (setVisible) the frame.
If you want to interact with the Calculas class in this manner, you should also be calling CAL.setVisible(true)
Also, by convention, all Java instance variables, should start with a lower case character and use camelCase conventions
In it's current form of your code, you can call the main method of your Calculas class in Test class or move the code to the Test class.
Warning: Extending JFrame is not a good Idea.
First alternative: You don't need to extend JFrame in Test
public class Test{
public static void main(String args[])
{
Calculas.main(new String[0]);
}
}
You haven't mentioned in your question how you want to be able to chose close or open, in console or in another JFrame or something...
Second Alternative:
But If I were you I could do something like this: wrap the code for look and feel in a separate method and call this from Test' s main.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author user
*/
public class Calculas extends javax.swing.JFrame {
/**
* Creates new form Calculas
*/
public Calculas() {
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() {
a1Text = new javax.swing.JTextField();
a2Text = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
answer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60)
.addComponent(jLabel1)
.addGap(34, 34, 34)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int a;
a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
answer.setText("Answer" + a);
// TODO add your handling code here:
}
public static setNimbusFeel(){
/* 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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
// Variables declaration - do not modify
private javax.swing.JTextField a1Text;
private javax.swing.JTextField a2Text;
private javax.swing.JLabel answer;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
And test class like this:
public class Test{
public static void main(String args[])
{
Calculas cal=new Calculas();
//</editor-fold>
Calculas.setNimbusFeel();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Calculas().setVisible(true);
}
});
}
}
Like this:
Here's an example of a basic structure you can use:
import java.awt.*;
import javax.swing.*;
class MyGui {
private JFrame window = new JFrame("This is the title");
public MyGui() {
initComponents();
window.setBounds(100, 50, 600, 400); //location, size
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void initComponents() {
Container cp = window.getContentPane();
cp.setLayout(new FlowLayout() );
cp.add(new JLabel("Hello world") );
}
}
public class MyProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
And in separate files:
MyGui.java
import java.awt.*;
import javax.swing.*;
public class MyGui {
private JFrame window = new JFrame("This is the title");
public MyGui() {
initComponents();
window.setBounds(100, 50, 600, 400); //location, size
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void initComponents() {
Container cp = window.getContentPane();
cp.setLayout(new FlowLayout() );
cp.add(new JLabel("Hello world") );
}
}
MyProg.java
import javax.swing.*;
public class MyProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Calculas CAL = new Calculas();
CAL.Calculus();
maybe, CAL.Calculas(); I dont know java but I realized that, sorry about my english:)
Related
I'm currently having trouble (as the title states) appending text to a JTextArea from a separate class (or thread).
Here is my code, since I don't know what's causing the problem. (note that I'm using the Netbeans generated code for my GUI):
Chat Box GUI:
public class ChatBoxGUI extends javax.swing.JFrame
{
/**
* Creates new form ChatBoxGUI
* #return
*/
public javax.swing.JTextArea getTextArea()
{
return inputOutputTextArea;
}
public void setLabels(java.net.SocketAddress address, int port) {
this.addressLabel.setText("IP Address: " +address);
this.portLabel.setText("Port: " +Integer.toString(port));
}
public ChatBoxGUI() {
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() {
jPanel1 = new javax.swing.JPanel();
startServerButton = new javax.swing.JButton();
connectServerButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
addressLabel = new javax.swing.JLabel();
portLabel = new javax.swing.JLabel();
outputTextField = new javax.swing.JTextField();
stopButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
inputOutputTextArea = new javax.swing.JTextArea();
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
startServerButton.setText("Start Server");
startServerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startServerButtonActionPerformed(evt);
}
});
connectServerButton.setText("Connect to Server");
connectServerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
connectServerButtonActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
jLabel1.setText("Isaac's Chat Box");
addressLabel.setText("IP Address:");
portLabel.setText("Port: ");
stopButton.setText("Stop");
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(evt);
}
});
inputOutputTextArea.setEditable(false);
inputOutputTextArea.setColumns(20);
inputOutputTextArea.setRows(5);
jScrollPane2.setViewportView(inputOutputTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2)
.addComponent(outputTextField, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(startServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(connectServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(addressLabel))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(stopButton)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(portLabel)))
.addGap(0, 18, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startServerButton)
.addComponent(jLabel1)
.addComponent(stopButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(connectServerButton)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addressLabel)
.addComponent(portLabel)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(outputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void startServerButtonActionPerformed(java.awt.event.ActionEvent evt) {
CreateServerDialog createServerDialog = new CreateServerDialog(this, true);
createServerDialog.setVisible(true);
try {
Runnable serverClassRunnable = new ServerClass(createServerDialog.getPort());
Thread serverClassThread = new Thread(serverClassRunnable);
serverClassThread.start();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
private void connectServerButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatBoxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatBoxGUI.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 ChatBoxGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel addressLabel;
private javax.swing.JButton connectServerButton;
private javax.swing.JTextArea inputOutputTextArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField outputTextField;
private javax.swing.JLabel portLabel;
private javax.swing.JButton startServerButton;
private javax.swing.JButton stopButton;
// End of variables declaration
}
Create Server Dialog:
public class CreateServerDialog extends javax.swing.JDialog {
private int port; private boolean isValid = false; private java.awt.Frame parent;
public int getPort() {
return port;
}
/**
* Creates new form CreateServerDialog
*/
public CreateServerDialog(java.awt.Frame par, boolean modal) {
super(par, modal);
parent = par;
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() {
jLabel1 = new javax.swing.JLabel();
portInput = new javax.swing.JTextField();
okButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Enter Port:");
okButton.setText("Ok");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(okButton)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(portInput)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(portInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(okButton))
);
pack();
}// </editor-fold>
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
ErrorDialog errorDialog = new ErrorDialog(parent, true);
try {
port = Integer.parseInt(this.portInput.getText());
isValid = true;
} catch (NumberFormatException n) {
errorDialog.errorOccured(0);
isValid = false;
}
if (port <= 1024 || port > 65535) {
errorDialog.errorOccured(0);
isValid = false;
}
if (isValid == true) {
this.dispose();
}
}
/**
* #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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateServerDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
CreateServerDialog dialog = new CreateServerDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JButton okButton;
private javax.swing.JTextField portInput;
// End of variables declaration
}
Server Class:
import java.io.*;
import java.net.*;
public class ServerClass implements Runnable
{
private final ServerSocket serverSocket;
public ServerClass(int port) throws IOException
{
serverSocket = new ServerSocket(port);
}
public void run()
{
ChatBoxGUI chatBoxGUI = new ChatBoxGUI();
try {
chatBoxGUI.getTextArea().append("\nSearching for client connection. \nPort: " +serverSocket.getLocalPort()); //this is the code that isn't working
Socket server = serverSocket.accept();
System.out.println();
chatBoxGUI.setLabels(server.getLocalSocketAddress(), serverSocket.getLocalPort()); //this also isn't working - but that's not the focus of this question
DataOutputStream out = new DataOutputStream(server.getOutputStream());
DataInputStream in = new DataInputStream(server.getInputStream());
chatBoxGUI.getTextArea().append("\nClient found! Connected with: " +server.getRemoteSocketAddress());
//note: this part isn't finished - but it doesn't need to be for that code to work
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've tried to do research on the problem, and what I've found tells me that I have to use either invokeLater or invokeAndWait when running the code so that it runs in the EDT. And I have tried to implement this but it still doesn't seem to work:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
chatBoxGUI.getTextArea().append("\nSearching for client connection. \nPort: " +serverSocket.getLocalPort());
}
});
Similar output to the terminal works completely fine, so it's definitely an issue with appending the text.
Any help would be appreciated, and thanks in advance.
You have multiple instances of the ChatBoxGUI class, so you are not updating the text area that is visible on the desktop.
So first you create the ChatBoxGUI class. Then when you click on a button you create the ServerClass. In the ServerClass you create a second instance of the ChatBoxGUI.
Don't create the second instance of the ChatBoxGUI class!!!
Instead, if you want to access variables in the ChatBoxGUI class then you need to:
pass a reference of the ChatBoxGUI class to the ServerClass
save this reference as an instance variable in the ServerClass
access this variable when you want to add text to the text area.
Without a more complete example, all I can do is link you to this question that has an answer for a similar issue.
Or you could try changing your approach from:
public javax.swing.JTextArea getTextArea()
{
return inputOutputTextArea;
}
To:
public void setTextArea(String textToAppend)
{
inputOutputTextArea.append(textToAppend);
}
To begin with, I know that using multiple jframes is frowned upon, unfortunately i have gotten myself to deep into this project to start over. my issue is i cannot find a way to transfer data (user input) from one frame to another, i will provide the code i need to be transferred from frame 1 to another frame
this is my code for the name and email they have to input
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
here is the button code to go to the new frame
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
i am new to swing and i dont need someone to complete my program. i just need to know how to carry it over to a new text box on a new frame.
Doing this is fairly easy. All you need to do is to set a constructor in which you are passing your frame with the values you need over to your new frame.
For example, I have a LoginScreen.java and DoctorScreen.java. If my user successfully entered his details and logs in, I transfer an ArrayList of Doctors from one JFrame to another JFrame, or more precisely, from one java class to another by creating a new instance of that class
Example here
Passing an arraylist from LoginScreen.java to DoctorScreen.java
DoctorScreen dScreen = new DoctorScreen(frame, docList,d);
Now Taking those values passed from LoginScreen.java and setting them in DoctorScreen.java
public DoctorScreen(JFrame frame, ArrayList<Doctor> docList, Doctor d) {
// TODO Auto-generated constructor stub
dialog = new JFileChooser(System.getProperty("user.dir"));
this.frame = frame;
this.docList = docList;
this.d = d;
initialize();
}
Now, you can change the DoctorScreen Constructor to fit into whatever project you are trying to do.
The steps I would advise you to take is to create a Java file for handling your input, and the second Java file to display what you entered in the first file
EG:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String field1 = txtrEnterYourFull.getText();
String name = nameL.getText();
String field2 = txtroptionalEnterYour.getText();
Display display = new Display(name, field1, field2);//using this as example
}
}
Then in your display.java, call your constructor taking in these fields and display them either in a textfield/textarea or in a JLabel in your frame
String name, field1, field2;
public Display(String name, String field1, String field2){
this.name = name;
this.field1 = field1;
this.field2 - field2;
}
Please take note that these variables have already been declared and I am merely using this for demonstration purposes.
Frames are like any other class, so just use the same kind of strategies you use to pass data between any other classes. For example you can simply create setter methods in your second frame class and call them from the first frame.
Note: This is just something I threw together really fast in Netbeans so there is a lot of generated code. Also, this is strictly an example I'm not saying it's necessarily the best way to do this.
Here is a quick and dirty example of how you might pass data between two JFrame objects:
This is the code to pay attention to from Frame1:
private void sendToOtherFrameBtnActionPerformed(java.awt.event.ActionEvent evt) {
Frame2 otherFrame = new Frame2();
otherFrame.setTextFieldText(jTextField1.getText());
otherFrame.setTextAreaText(jTextArea1.getText());
otherFrame.setVisible(true);
}
Here is the full code for Frame1:
public class Frame1 extends javax.swing.JFrame {
/**
* Creates new form Frame1
*/
public Frame1() {
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();
jTextField1 = new javax.swing.JTextField();
sendToOtherFrameBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jTextArea1.setText("text area data");
jScrollPane1.setViewportView(jTextArea1);
jTextField1.setText("text field data");
sendToOtherFrameBtn.setText("Send To Other Frame");
sendToOtherFrameBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendToOtherFrameBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(99, 99, 99)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(sendToOtherFrameBtn)))
.addContainerGap(135, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(37, 37, 37)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
.addComponent(sendToOtherFrameBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31))
);
pack();
}// </editor-fold>
private void sendToOtherFrameBtnActionPerformed(java.awt.event.ActionEvent evt) {
Frame2 otherFrame = new Frame2();
otherFrame.setTextFieldText(jTextField1.getText());
otherFrame.setTextAreaText(jTextArea1.getText());
otherFrame.setVisible(true);
}
/**
* #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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame1.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 Frame1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton sendToOtherFrameBtn;
// End of variables declaration
}
Here is the important code from Frame2:
public void setTextFieldText(String txt){
jTextField1.setText(txt);
}
public void setTextAreaText(String txt){
jTextArea1.setText(txt);
}
Here is the full code for Frame2:
public class Frame2 extends javax.swing.JFrame {
/**
* Creates new form Frame2
*/
public Frame2() {
initComponents();
}
public void setTextFieldText(String txt){
jTextField1.setText(txt);
}
public void setTextAreaText(String txt){
jTextArea1.setText(txt);
}
/**
* 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();
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(111, 111, 111)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addComponent(jTextField1))
.addContainerGap(123, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(52, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(99, 99, 99))
);
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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Frame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame2.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 Frame2().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
I am trying to do a simple Jform and call it from another class.
I want to use this Jframe in a server client application, but I don't know how to open the JFrame class from another class.
Like user has to chose
1- to open Jframe.
2- To Exit.
So What am I doing wrong?
Below are the codes:
Jframe Class named Calculas.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author user
*/
public class Calculas extends javax.swing.JFrame {
/**
* Creates new form Calculas
*/
public Calculas() {
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() {
a1Text = new javax.swing.JTextField();
a2Text = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
answer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60)
.addComponent(jLabel1)
.addGap(34, 34, 34)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int a;
a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
answer.setText("Answer" + a);
// TODO add your handling code here:
}
/**
* #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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculas.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 Calculas().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField a1Text;
private javax.swing.JTextField a2Text;
private javax.swing.JLabel answer;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Test Class named Test.java
public class Test extends JFrame {
public static void main(String args[])
{
Calculas CAL = new Calculas();
CAL.Calculus();
}
}
Forgive me if this is naive, as Im not anything of a Java programmer...
But isnt it just because you need to set visible?
Calculas CAL = new Calculas();
CAL.setVisible(true);
The constructor of Calculas doesn't show (setVisible) the frame.
If you want to interact with the Calculas class in this manner, you should also be calling CAL.setVisible(true)
Also, by convention, all Java instance variables, should start with a lower case character and use camelCase conventions
In it's current form of your code, you can call the main method of your Calculas class in Test class or move the code to the Test class.
Warning: Extending JFrame is not a good Idea.
First alternative: You don't need to extend JFrame in Test
public class Test{
public static void main(String args[])
{
Calculas.main(new String[0]);
}
}
You haven't mentioned in your question how you want to be able to chose close or open, in console or in another JFrame or something...
Second Alternative:
But If I were you I could do something like this: wrap the code for look and feel in a separate method and call this from Test' s main.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author user
*/
public class Calculas extends javax.swing.JFrame {
/**
* Creates new form Calculas
*/
public Calculas() {
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() {
a1Text = new javax.swing.JTextField();
a2Text = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
answer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60)
.addComponent(jLabel1)
.addGap(34, 34, 34)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int a;
a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
answer.setText("Answer" + a);
// TODO add your handling code here:
}
public static setNimbusFeel(){
/* 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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
// Variables declaration - do not modify
private javax.swing.JTextField a1Text;
private javax.swing.JTextField a2Text;
private javax.swing.JLabel answer;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
And test class like this:
public class Test{
public static void main(String args[])
{
Calculas cal=new Calculas();
//</editor-fold>
Calculas.setNimbusFeel();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Calculas().setVisible(true);
}
});
}
}
Like this:
Here's an example of a basic structure you can use:
import java.awt.*;
import javax.swing.*;
class MyGui {
private JFrame window = new JFrame("This is the title");
public MyGui() {
initComponents();
window.setBounds(100, 50, 600, 400); //location, size
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void initComponents() {
Container cp = window.getContentPane();
cp.setLayout(new FlowLayout() );
cp.add(new JLabel("Hello world") );
}
}
public class MyProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
And in separate files:
MyGui.java
import java.awt.*;
import javax.swing.*;
public class MyGui {
private JFrame window = new JFrame("This is the title");
public MyGui() {
initComponents();
window.setBounds(100, 50, 600, 400); //location, size
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void initComponents() {
Container cp = window.getContentPane();
cp.setLayout(new FlowLayout() );
cp.add(new JLabel("Hello world") );
}
}
MyProg.java
import javax.swing.*;
public class MyProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Calculas CAL = new Calculas();
CAL.Calculus();
maybe, CAL.Calculas(); I dont know java but I realized that, sorry about my english:)
I'm having some problem in adding new elements to the combo box. The code is created by Netbeans Form Editor, because of this I only have access to modify the event listeners. The elements cant be predefined because the elements are in a database and constantly expanding. Currently the combo box has only one element and i would like it to update according to the values from the database. Thank you for your time folks.
package Interface;
/**
*
* #author Raam
*/
public class Welcome extends javax.swing.JFrame {
/**
* Creates new form Welcome
*/
public Welcome() {
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() {
jComboBox1 = new javax.swing.JComboBox();
jComboBox2 = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("addNewRecord");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Add New Record", "Class", "Section", "Student" }));
jComboBox1.setToolTipText("Add New Record");
jComboBox1.setName("AddNewRecord"); // NOI18N
jComboBox1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jComboBox1FocusGained(evt);
}
});
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Choose Class" }));
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jButton1.setText("Open Database");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addGroup(layout.createSequentialGroup()
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap(16, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jComboBox1FocusGained(java.awt.event.FocusEvent evt) {
jComboBox1.addElement(); //Tried this, not working
}
/**
* #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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Welcome.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 Welcome().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
// End of variables declaration
}
You have to add the ítem in the model:
DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBox1.getModel();
model.addElement("new ítem");
Can be done by going to properties of the combo box then to >> model. As the answer provided here https://stackoverflow.com/a/39689417/5737654
This question already has answers here:
How does the event dispatch thread work?
(4 answers)
Closed 8 years ago.
i don't know why the gui didn't appear
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anagramword;
/**
*
* #author teteh
*/
public class gui extends javax.swing.JFrame {
/**
* Creates new form gui
*/
public String textword;
public char[] temp;
static int size;
public gui() {
initComponents();
//setVisible(true);
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
word = new javax.swing.JTextField();
btnSubmit = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
hasil = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Masukkan Kata");
btnSubmit.setText("Acak");
btnSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSubmitActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel2.setText("Anagram Word");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(99, 99, 99))
.addGroup(layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jLabel1)
.addGap(62, 62, 62)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnSubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(word, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hasil, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(word, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnSubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(hasil, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(22, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Anagramword ana = new Anagramword();
textword=word.getText();
size = textword.length();
temp = textword.toCharArray();
if (size <= 2) {
System.out.println("Maaf Minimal 3 Huruf");
} else {
ana.acak(textword, size);
ana.runAnagram(size);
ana.display();
}
}
/**
* #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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new gui().setVisible(true);
}
});
//new gui().setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton btnSubmit;
private javax.swing.JLabel hasil;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField word;
// End of variables declaration
}
when i run the app the gui didn't appear but it said build successfull. i have the setVisible(true) but the gui never appear.help please i must miss something in the code or wrong using.
Maybe when you press the start button in netbeans it try to run another class... In your class gui try to right click -> Run As -> Java Application.
Otherwise Right Click on Project -> Run -> Main Class -> Browse.. and select anagramword.gui