Setting input box next to text (Java) - java

So I am trying to get my text input box for my fish sandwich next to the text for it. It keeps pushing down next to the hamburger input box. I cannot seem to get it next to it. Here is the code.
here is a screenshot
/*
* 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 foodproject2;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
/**
*
* #author Travis
*/
public class Menu1 extends javax.swing.JFrame {
private Container contents;
private JLabel name, courseNum, welcome, prompt, chickP, fishP, burgerP;
private JLabel chargeSand, chargeService, totalBill;
private JTextField numChick, numFish, numBurger;
private JButton compute;
public Menu1()
{
super("Travis' Menu");
contents = getContentPane();
contents.setLayout(new FlowLayout());
name=new JLabel("Programmer: Travis Easton");
courseNum=new JLabel("ITSD424");
welcome=new JLabel("Welcome To Travis' Sandwich Shop");
prompt=new JLabel("Enter number of Sandwiches for each; 0 if none");
chickP=new JLabel("Chicken Sandwiches # $4.99 each");
chickP.setForeground(Color.BLACK);
numChick=new JTextField(3);
fishP=new JLabel("Salmon Sandwiches # $4.99 each ");
fishP.setForeground(Color.BLACK);
numFish=new JTextField(3);
burgerP=new JLabel("Hamburger # $4.99 each");
burgerP.setForeground(Color.BLACK);
numBurger=new JTextField(3);
chargeSand = new JLabel("Charge for Sandwiches = $");
chargeService = new JLabel("Charge for Service = $");
totalBill= new JLabel("Total Bill = $");
chargeSand = new JLabel("Sandwich cost");
chargeService = new JLabel("Tax");
totalBill = new JLabel("Total");
compute = new JButton("Bill Total");
contents.add(name);
contents.add(courseNum);
contents.add(welcome);
contents.add(prompt);
contents.add(chickP);
contents.add(numChick);
contents.add(fishP);
contents.add(burgerP);
contents.add(numFish);
contents.add(numBurger);
contents.add(chargeSand);
contents.add(chargeService);
contents.add(totalBill);
contents.add(chargeSand);
contents.add(chargeService);
contents.add(totalBill);
contents.add(compute);
ButtonHandler bh = new ButtonHandler();
compute.addActionListener(bh);
setSize(400,400);
setVisible(true);
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e) {
try
{
double one = Double.parseDouble(numChick.getText());
double two = Double.parseDouble(numFish.getText());
double three = Double.parseDouble(numBurger.getText());
// Calculations for determining total price of bill
double orderAmount = (one*4.99)+(two*4.99)+(three*4.99);
double serviceAmount = (orderAmount)*.15;
double totalAmount = (orderAmount+serviceAmount);
// Now to display the charges
chargeSand.setText(new Double(orderAmount).toString());
chargeService.setText(new Double(serviceAmount).toString());
totalBill.setText(new Double(totalAmount).toString());
}
catch(NumberFormatException ex)
{
numChick.setText("0");
numFish.setText("0");
numBurger.setText("0");
totalBill.setText("0");
}
}
}
/**
* Creates new form Menu
*/
{
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">//GEN-BEGIN:initComponents
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* #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(Menu1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu1.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 Menu1().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}

In you code, the string that you have passed into the fishP JLabel contains spaces at the end.
I think it should be:
fishP=new JLabel("Salmon Sandwiches # $4.99 each");
One more change:
contents.add(chickP);
contents.add(numChick);
contents.add(fishP);
contents.add(numFish);
contents.add(burgerP);
contents.add(numBurger);

When you add the content you are doing it in the wrong order:
contents.add(chickP);
contents.add(numChick);
contents.add(fishP);
contents.add(burgerP);
contents.add(numFish);
contents.add(numBurger);
Move numFish up.

Related

Why this actionEvent on a Java Swing menu item does not work?

I have created a basic JFrame using NetBeans form designer. I have reduced it to just a couple of menu items.
I intend to do something when user clicks on "Open", my understanding is that I have to add an "actionPerformed" through a listener, which can be done using NetBeans Designer.
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("ACTION PERFORMED");
}
But when I click on "Open" nothing happens I can not see the output message.
This is my main routine:
package test.dbviewer;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SealionDBViewer {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel ("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
JFrame databaseViewer = new DatabaseViewer();
databaseViewer.setVisible(true);
}
}
This is the reproducible code that NetBeans generate:
package test.dbviewer;
public class DatabaseViewer extends javax.swing.JFrame {
/**
* Creates new form DatabaseViewer
*/
public DatabaseViewer() {
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() {
jSplitPane1 = new javax.swing.JSplitPane();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuBar2 = new javax.swing.JMenuBar();
jMenu3 = new javax.swing.JMenu();
jMenu4 = new javax.swing.JMenu();
jMenuItem1.setText("jMenuItem1");
jMenuItem2.setText("jMenuItem2");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu3.setText("Open");
jMenu3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu3ActionPerformed(evt);
}
});
jMenuBar2.add(jMenu3);
jMenu4.setText("Exit");
jMenuBar2.add(jMenu4);
setJMenuBar(jMenuBar2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 267, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("ACTION PERFORMED");
}
/**
* #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(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.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 DatabaseViewer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar jMenuBar2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JSplitPane jSplitPane1;
// End of variables declaration
}

I can't initialize my array of objects outside of my event method

I want to make a program that will create a Array of objects that will store the number of times a user has clicked a button.
I ask the user what their id number is and then access their element of the array and update their button clicks.
The problem is that it won't let me set
surveyor[0] = new Surveyors();
surveyor[1] = new Surveyors(); unless I put the code in my attemptUpdateActionPerformed method, but I need to set it up outside of the method so it will not reset itself each time the button is clicked. There is a lot of extra stuff in here, but I think the main problem lies in the method. Sorry for the sloppiness.
package guildquality;
import java.util.Scanner;
public class NewJFrame extends javax.swing.JFrame {
Surveyors [] surveyor = new Surveyors[10];
Scanner scan = new Scanner(System.in);
public int id;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
surveyor[0] = new Surveyors();
surveyor[1] = new Surveyors();
id = 0;
}
/**
* 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() {
attemptUpdate = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
attemptUpdate.setText("Attempt");
attemptUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
attemptUpdateActionPerformed(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()
.addGap(21, 21, 21)
.addComponent(attemptUpdate)
.addContainerGap(308, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(173, Short.MAX_VALUE)
.addComponent(attemptUpdate)
.addGap(104, 104, 104))
);
pack();
}// </editor-fold>
private void attemptUpdateActionPerformed(java.awt.event.ActionEvent evt) {
System.out.print("what is your id?");
id = scan.nextInt();
surveyor[id].setAttempts();
System.out.print(surveyor[id].getAttempts());
// 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton attemptUpdate;
// End of variables declaration
}
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222)
at java.awt.Window.init(Window.java:497)
at java.awt.Window.<init>(Window.java:536)
at java.awt.Frame.<init>(Frame.java:420)
at java.awt.Frame.<init>(Frame.java:385)
at javax.swing.JFrame.<init>(JFrame.java:180)
at guildquality.NewJFrame.<init>(NewJFrame.java:19)
at guildquality.Surveyors.<init>(Surveyors.java:17)
at guildquality.NewJFrame.<init>(NewJFrame.java:20)
Put it in the main method. It will run once and before the eventhandler can run.
You should put code you want to initialize non-static class variable once in the constructor.
eg.
public NewJFrame() {
initComponents();
// More initialization here.
surveyor[0] = new Surveyors();
surveyor[1] = new Surveyors();
}

Using a Timer in Swing to display a picture for 5 seconds

I am trying to make a login picture for my application using Timer. The idea is, when the user opens the application, he will see a picture for 5 seconds, then the application will start.
I tried, as you can see in the method shoutoff():
/*
* 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 login;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
/**
*
* #author isslam
*/
public class login extends javax.swing.JFrame {
Timer time;
/**
* Creates new form login
*/
public login() {
initComponents();
setLocation(350, 200);
time = new Timer(5000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
time.setRepeats(false);
}
public void shoutoff(){
if (!time.isRunning()) {
time.start();
}
}
/**
* 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();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setLocationByPlatform(true);
setUndecorated(true);
setResizable(false);
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\isslam\\Desktop\\one_piece_marble_play_by_iviarker-d511vb0.jpg")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
);
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(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(login.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 login().setVisible(true);
new login().shoutoff();
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Start by creating the Timer once in the constructor. The Timer should, also, only make the CURRENT instance of login close
public login() {
//...
time = new Timer(5000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
timer.setRepeats(false);
}
In the shoutoff method, you start timer...
public void shoutoff(){
if (!time.isRunning()) {
timer.start();
}
}
Take a closer look at How to use Swing Timers for more details.
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
The idea is, when the user opens the application, he will see a picture for 5 seconds, then the application will start.
You should use a Splash Screen. The advantage of the splash screen is the image is displayed immediately as the whole Swing app doesn't need to be loaded.
Check out the section from the Swing tutorial on How to Create a Splash Screen for more information and a working example.

Open a console alongside a Swing GUI in java

I am building an application with a Swing GUI. If you would would open this program from the command line, Some text will print (info and error messages). The program is just a normal executable jar file, but for the people who want to see a console I want an option to open a console from the Swing GUI, which displays all these messages, outputted by System.out.print(). I have seen several applications which have such a function, but I don't know how to do this.
The basics are explained at https://blogs.oracle.com/nickstephen/entry/java_redirecting_system_out_and. That example uses logging to redirect stdout and stderr. A simple approach could be to first define an OutputStream that writes to the "console":
package outerr;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JTextArea;
public class PrintOutErrStream extends ByteArrayOutputStream {
final int maxTextAreaSize = 1000;
private JTextArea textArea;
public PrintOutErrStream(JTextArea textArea) {
this.textArea = textArea;
}
public void flush() throws IOException {
synchronized(this) {
super.flush();
String outputStr = this.toString();
super.reset();
if(textArea.getText().length() > maxTextAreaSize) {
textArea.replaceRange("", 0, 100);
}
textArea.append(outputStr);
}
}
}
Then this is the remaining part of a demo program:
package outerr;
import java.io.PrintStream;
public class StdOutErr extends javax.swing.JFrame {
/** Creates new form StdOutErr */
public StdOutErr() {
initComponents();
PrintOutErrStream poes = new PrintOutErrStream(this.jTextAreaOutErrLog);
System.setErr(new PrintStream(poes, true));
System.setOut(new PrintStream(poes, 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() {
java.awt.GridBagConstraints gridBagConstraints;
jButtonStdout = new javax.swing.JButton();
jButtonStderr = new javax.swing.JButton();
jPanelOutErrLog = new javax.swing.JPanel();
jScrollPaneOutErrLog = new javax.swing.JScrollPane();
jTextAreaOutErrLog = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
jButtonStdout.setText("stdout");
jButtonStdout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonStdoutActionPerformed(evt);
}
});
getContentPane().add(jButtonStdout);
jButtonStderr.setText("stderr");
jButtonStderr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonStderrActionPerformed(evt);
}
});
getContentPane().add(jButtonStderr);
jTextAreaOutErrLog.setColumns(20);
jTextAreaOutErrLog.setRows(5);
jScrollPaneOutErrLog.setViewportView(jTextAreaOutErrLog);
javax.swing.GroupLayout jPanelOutErrLogLayout = new javax.swing.GroupLayout(jPanelOutErrLog);
jPanelOutErrLog.setLayout(jPanelOutErrLogLayout);
jPanelOutErrLogLayout.setHorizontalGroup(
jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 835, Short.MAX_VALUE)
.addGroup(jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneOutErrLog, javax.swing.GroupLayout.DEFAULT_SIZE, 835, Short.MAX_VALUE))
);
jPanelOutErrLogLayout.setVerticalGroup(
jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 378, Short.MAX_VALUE)
.addGroup(jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneOutErrLog, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE))
);
getContentPane().add(jPanelOutErrLog);
pack();
}// </editor-fold>
private void jButtonStdoutActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("message via stdout");
}
private void jButtonStderrActionPerformed(java.awt.event.ActionEvent evt) {
System.err.println("message via stderr");
}
/**
* #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(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StdOutErr.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 StdOutErr().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonStderr;
private javax.swing.JButton jButtonStdout;
private javax.swing.JPanel jPanelOutErrLog;
private javax.swing.JScrollPane jScrollPaneOutErrLog;
private javax.swing.JTextArea jTextAreaOutErrLog;
// End of variables declaration
}

Setting Text in jTextField in netbeans

I know how to set text using JtextField in java. But for some weird reason. I am not able to manipulate the jtextfield in netbeans.
What I want is to manipulate the text from main(), the user will enter the string and that string should be shown in jTextField.
Here is the code:
import javax.swing.JOptionPane;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Sachin
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
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() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
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()
.addGap(134, 134, 134)
.addComponent(jButton1)
.addContainerGap(193, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addComponent(jButton1)
.addContainerGap(224, Short.MAX_VALUE))
);
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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
String inputValue = JOptionPane.showInputDialog("Please any enter any String");
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
You can do the following plumbing to store inputValue in the NewJFrame object.
private String input;
public NewJFrame(String input) {
this.input = input;
initComponents();
}
new NewJFrame(inputValue);
Then in the NetBeansIDE you can in the GUI editor set the custom creation code of the JTextField to new JTextField(input) or simply call setText.

Categories