implementing a class in class - java

I am trying to implement a class in a class in JAVA, like this
package test;
import java.awt.event.*;
import javax.swing.*;
/**
*
* #author jackandjill
*/
public class Summingup extends JFrame {
/**
* Creates new form Summingup
*/
public Summingup() {
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();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
input1_tb = new javax.swing.JTextField();
calculate_btn = new javax.swing.JButton();
result_lbl = new javax.swing.JLabel();
input2_tb = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Input 1");
jLabel2.setText("Input 2");
calculate_btn.setText("SUM");
result_lbl.setText("RESULT DISPLAYED HERE!");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(input1_tb))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(result_lbl))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(input2_tb)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(calculate_btn)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(calculate_btn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(input1_tb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(input2_tb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
.addComponent(result_lbl)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, 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()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, 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(Summingup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Summingup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Summingup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Summingup.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 Summingup().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton calculate_btn;
private javax.swing.JTextField input1_tb;
private javax.swing.JTextField input2_tb;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel result_lbl;
// End of variables declaration
}
class InvalidValueException implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
try
{
if(ae.getSource() ==calculate_btn)
{
String input_1 = input1_tb.getText();
String input_2 = input2_tb.getText();
checkBlanklnput(input_1,input_2);
validateInput(Integer.parseInt(input_1),Integer.parseInt(input_2));
result_lbl.setText(calculate(Integer.parseInt(input_1),Integer.parseInt(input_2)));
}
}
catch (NumberFormatException excep)
{
result_lbl.setText("Invalid number");
}
catch (InvalidInputException excep)
{
result_lbl.setText(excep.getMessage());
}
catch (BlankInputException excep)
{
result_lbl.setText(excep.getMessage());
}
}
public void checkBlanklnput(String input1,String input2) throws BlanklnputException
{
if (input1.length() == 0 ||input2.length() == 0) throw new BlanklnputException();
}
public void validateInput(int input1 , int input2) throws InvalidInputException
{
if (input1 + input2 > 100 )
throw new InvalidInputException();
}
public String calculate(int input1, int input2)
{
String res = "";
while (true)
{
res = Integer.toString(input1 + input2);
break;
}
return res;
}
}
class InvalidInputException extends Exception {
public InvalidInputException() {
super("Invalid number");
}
}
class BlankInputException extends Exception {
public BlankInputException() {
super("Input cannot be blank");
}
}
So this class is also throwing lot of exceptions and catching them. But the only problem is the JForm controls are not being recognised in the InvalidValueException class.
Not sure how to open those controls to this class.
Another issue that I am facing is my validateInput is checking for maximum sum but I want to check for IF any alphabets other than numbers are entered in the textboxes.
This is what my GUI looks like

You might compare your implementation to the working example shown here. It uses JFormattedTextField to enforce numeric input, as well as a PropertyChangeListener & FocusListener to update the sum.
As an aside, you should study layouts before relying too much on a GUI editor. See also Nested Classes.
Addendum: BlankInputException was misspelled, and your (oddly named) ActionListener was unused. You should be able to initialize it using a custom code property.
calculate_btn.addActionListener(new InvalidValueException());

Related

Swing JFrame GUI window is empty when run

I've built a Higher/Lower game, using the Swing library. When I run the code I don't get any errors or warnings. The problem appears when I try running the code, the window is empty, not the way it should be.
I use NetBeans to program.There are 2 different files in my project, here is the code...
HiLoGUI.java:
import java.awt.Dimension;
import javax.swing.*;
public class HiLoGUI extends JFrame {
private JTextField txtGuess;
private JLabel outputLabel;
private int theNumber;
public void newGame() {
theNumber = (int)(Math.random() * 100 + 1);
}
public void checkGuess() {
String guessText = txtGuess.getText();
String message = "";
int guess = Integer.parseInt(guessText);
if (guess < theNumber) {
message = guess + " is too low. Try again.";
}
else if (guess > theNumber) {
message = guess + " is too high. Try again.";
}
else {
message = guess + " is correct. You win!";
}
outputLabel.setText(message);
}
public static void main(String[] args) {
HiLoGUI theGame = new HiLoGUI();
theGame.newGame();
theGame.setSize(new Dimension(450,300));
theGame.setVisible(true);
}
}
The window should look like this:
NetBeans screenshot
EDIT:
The other files code:
public class HiLoJFrame extends javax.swing.JFrame {
/**
* Creates new form HiLoJFrame
*/
public HiLoJFrame() {
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();
titleLabel = new javax.swing.JLabel();
chooseLabel = new javax.swing.JLabel();
txtGuess = new javax.swing.JTextField();
guessButton = new javax.swing.JButton();
outputLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setName("HiLoGame"); // NOI18N
titleLabel.setFont(new java.awt.Font("SansSerif", 1, 24)); // NOI18N
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
titleLabel.setText("High/Lower Game");
titleLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
chooseLabel.setFont(new java.awt.Font("SansSerif", 0, 15)); // NOI18N
chooseLabel.setText("Guess a name between 1 to 100");
txtGuess.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtGuessActionPerformed(evt);
}
});
guessButton.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
guessButton.setText("Guess");
guessButton.setCursor(new java.awt.Cursor(java.awt.Cursor.MOVE_CURSOR));
guessButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
guessButtonActionPerformed(evt);
}
});
outputLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
outputLabel.setText("Enter a number and press Guess");
outputLabel.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(50, Short.MAX_VALUE)
.addComponent(chooseLabel)
.addGap(18, 18, 18)
.addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(136, 136, 136)
.addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(78, 78, 78)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(titleLabel)
.addComponent(outputLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(75, 75, 75)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtGuess, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chooseLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(guessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(53, 53, 53)
.addComponent(outputLabel)
.addGap(35, 35, 35))
);
titleLabel.getAccessibleContext().setAccessibleDescription("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 422, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 346, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
getAccessibleContext().setAccessibleName("HiLoGame");
pack();
}// </editor-fold>
private void txtGuessActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
HiLoGUI hilogui = new HiLoGUI();
hilogui.checkGuess();
}
/**
* #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(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HiLoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new HiLoJFrame().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JLabel chooseLabel;
private javax.swing.JButton guessButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel outputLabel;
private javax.swing.JLabel titleLabel;
private javax.swing.JTextField txtGuess;
// End of variables declaration
}
EDIT2:
I've changed the main class of HiLoGUI.java
I was creating a wrong object.
New main:
public static void main(String[] args) {
HiLoJFrame theGame = new HiLoJFrame();
theGame.newGame();
theGame.setSize(new Dimension(450,300));
theGame.setVisible(true);
}
Now it claims that I need to create that method (newGame) in the JFrame file.
You are calling a method from the wrong class, according to the Swing docs, it is not needed to create a new JFrame object, so setting its visibility is enough. Check this out: How To Call JFrame from another Java class

Java - Printing out User Input as the user is typing it? [duplicate]

as part of my java learning I made a jForm using netbeans which contains three jTextFields for the user to enter some numbers and then the sum of those numbres is displayed in another jTextField. This is, of course, extremely easy, but I want to be able to do this without any buttons. I don't know how to "update" the sum everytime any of the 3 textfields is modified. Can anyone help me?
Here's my code (the form was done with netbeans in the design mode):
package sumfields;
public class Frame extends javax.swing.JFrame {
public Frame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
n1 = new javax.swing.JTextField();
n2 = new javax.swing.JTextField();
n3 = new javax.swing.JTextField();
sum = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("n1");
jLabel2.setText("n2");
jLabel3.setText("n3");
jLabel5.setText("result");
jButton1.setText("Opperate");
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()
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)))
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(10, 10, 10)
.addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)
.addComponent(jLabel5))
.addContainerGap(38, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int r=Integer.parseInt(n1.getText())+Integer.parseInt(n2.getText())+Integer.parseInt(n3.getText());
sum.setText(""+r);
}
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(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.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 Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField n1;
private javax.swing.JTextField n2;
private javax.swing.JTextField n3;
private javax.swing.JTextField sum;
// End of variables declaration
}
As #Reimeus suggested, you need to add Document Listener to each of your text fields. Since you're performing the addition in your jButton1ActionPerformed() method, I made the notification of the listeners call this method whenever there's a change to your text fields.
Note: Based on the comments, I've updated my code to include only one DocumentListener and also added a DocumentFilter to accept only numeric input. I also removed the button that was present in the original code to perform the summation
Here's your updated code:
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class Frame extends javax.swing.JFrame {
public Frame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
n1 = new javax.swing.JTextField();
n2 = new javax.swing.JTextField();
n3 = new javax.swing.JTextField();
sum = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
DocumentListener documentListener = new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
performSummation(null);
}
#Override
public void insertUpdate(DocumentEvent e) {
performSummation(null);
}
#Override
public void changedUpdate(DocumentEvent e) {
}
};
DocumentFilter numericFilter = new DocumentFilter(){
#Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
fb.insertString(offset, string.replaceAll("[^\\d]", ""), attr);
}
#Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs)
throws BadLocationException {
fb.replace(offset, length, text.replaceAll("[^\\d]", ""), attrs);
}
};
((AbstractDocument) n1.getDocument()).setDocumentFilter(numericFilter);
((AbstractDocument) n2.getDocument()).setDocumentFilter(numericFilter);
((AbstractDocument) n3.getDocument()).setDocumentFilter(numericFilter);
n1.getDocument().addDocumentListener(documentListener);
n2.getDocument().addDocumentListener(documentListener);
n3.getDocument().addDocumentListener(documentListener);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("n1");
jLabel2.setText("n2");
jLabel3.setText("n3");
jLabel5.setText("result");
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(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)))
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(10, 10, 10)
.addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addContainerGap(38, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void performSummation(java.awt.event.ActionEvent evt) {
int total = 0;
if(n1.getText().trim().length() > 0){
try{
total += Integer.parseInt(n1.getText());
}catch(NumberFormatException nbx){
}
}
if(n2.getText().trim().length() > 0){
try{
total += Integer.parseInt(n2.getText());
}catch(NumberFormatException nbx){
}
}
if(n3.getText().trim().length() > 0){
try{
total += Integer.parseInt(n3.getText());
}catch(NumberFormatException nbx){
}
}
sum.setText(""+total);
}
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(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.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 Frame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField n1;
private javax.swing.JTextField n2;
private javax.swing.JTextField n3;
private javax.swing.JTextField sum;
// End of variables declaration
}
A couple of pointers:
Never trust the input that comes from the user. There's a possibility that the user might enter an incorrect value (say something that is not an Integer). As such it is always a good idea to validate your input and check whether the input can be actually parsed. Keeping this in mind, I'ved updated your jButton1ActionPerformed() method
The other alternative is to use a Formatted Text Fields
What you are looking for is a DocumentListener.
Register a listener with each of your JTextFields n1, n2 and n3 and call your method jButton1ActionPerformed to update the result field.
This alternative approach uses a PropertyChangeListener and a FocusListener to update() a sum of values using JFormattedTextField.
You can use a focus listener or you can use a action listener to the input JTextField

Linebreak in text inputted through GUI

I'm trying to build a program that, through a GUI, receives input text with linebreaks, splits it at lines, then at spaces, and for each string does something "special". The problems are 2:
I can't get linebreaks into the input field;
I don't know how to get the linebreaks into the output.
How do I do that? My code is:
/*
* 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.
*/
/**
*
* #author michelegorini
*/
import java.util.Scanner;
public class HakkaTranslator extends javax.swing.JFrame {
/**
* Creates new form HakkaTranslator
*/
public HakkaTranslator() {
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() {
inputField = new javax.swing.JTextField();
translateButton = new javax.swing.JButton();
pinyinField = new javax.swing.JLabel();
hakkaCharField = new javax.swing.JLabel();
mandCharField = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
translateButton.setText("Translate");
translateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
translateButtonActionPerformed(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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(hakkaCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(mandCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(translateButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(inputField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pinyinField, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {hakkaCharField, inputField, mandCharField, pinyinField});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(translateButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(pinyinField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(inputField, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(hakkaCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(mandCharField))
.addContainerGap(177, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {hakkaCharField, inputField, mandCharField, pinyinField});
pack();
}// </editor-fold>
private void translateButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Scanner kLFeed = new Scanner(inputField.getText()).useDelimiter("\n");
Scanner kSp;
do{
kSp = new Scanner(kLFeed.next());
while(kSp.hasNext()){
translate(kSp.next());
}
translate("<br/>");
} while(kLFeed.hasNext());
}
private void translate(String word) {
pinyinField.setText(pinyinField.getText() + word);
}
/**
* #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(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HakkaTranslator.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 HakkaTranslator().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel hakkaCharField;
private javax.swing.JTextField inputField;
private javax.swing.JLabel mandCharField;
private javax.swing.JLabel pinyinField;
private javax.swing.JButton translateButton;
// End of variables declaration
}
at the moment.
Update:
Taking the answer and comments into account, I came to:
/*
* 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.
*/
/**
*
* #author michelegorini
*/
import java.util.Scanner;
public class HakkaTranslator extends javax.swing.JFrame {
/**
* Creates new form HakkaTranslator
*/
public HakkaTranslator() {
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() {
inputField = new javax.swing.JTextArea();
translateButton = new javax.swing.JButton();
pinyinField = new javax.swing.JLabel();
hakkaCharField = new javax.swing.JLabel();
mandCharField = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
translateButton.setText("Translate");
translateButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
inpText = inputField.getText();
String[] lines = inpText.split(System.lineSeparator());
String[][] words = new String[lines.length][20];
for(int i=0;i<lines.length;i++){
words[i] = lines[i].split(" ");
}
for(int i=0;i<lines.length;i++){
for(int j = 0;j<words[i].length;j++){
translate(words[i][j]);
}
translate(System.lineSeparator());
}
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(hakkaCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(mandCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(translateButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(inputField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pinyinField, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {hakkaCharField, inputField, mandCharField, pinyinField});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(translateButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(pinyinField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(inputField, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(hakkaCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(mandCharField))
.addContainerGap(177, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {hakkaCharField, inputField, mandCharField, pinyinField});
pack();
}// </editor-fold>//GEN-END:initComponents
private void translate(String word) {
pinyinField.setText(pinyinField.getText() + word + " ");
}
/**
* #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(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HakkaTranslator.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 HakkaTranslator().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel hakkaCharField;
private javax.swing.JTextArea inputField;
private javax.swing.JLabel mandCharField;
private javax.swing.JLabel pinyinField;
private javax.swing.JButton translateButton;
// End of variables declaration//GEN-END:variables
String inpText;
}
One problem persists: even with System.lineSeparator(), the linebreaks in the output just won't appear. How do I solve that? And how do I avoid having javax.swing every time?
This is an example of how to read the text of a text area to a string.
public class GetterText extends JFrame {
JTextArea ta = new JTextArea();
String taText;
GetterText() {
JButton getText = new JButton("GetText");
getText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
taText = ta.getText();
System.out.println(taText);
}
});
getContentPane().add(getText, BorderLayout.LINE_START);
getContentPane().add(new JScrollPane(ta));
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new GetterText();
}
}
You can use taText.split(" ") to split around spaces and taText.split("\\n") to split around lines.

Using the append to print out to a textArea from a list

So, from my previous question I decided to go ahead and use the list as recommended (Thank you for that).
I've got a single class now that uses a list. This list is updated through the button. When a user presses on the button, values within the textfield are parsed to double and saved into the list. I am trying to create a method to be placed into the button that will print out the list.
import java.util.ArrayList;
public class foodDept extends javax.swing.JFrame {
ArrayList<MyShoppingCart> list = new ArrayList<MyShoppingCart>();
public foodDept() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
appleLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
cartArea = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
appleField = new javax.swing.JTextField();
bananaField = new javax.swing.JTextField();
addTocart = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
appleLabel.setText("Apple ($1.99):");
cartArea.setColumns(20);
cartArea.setRows(5);
jScrollPane1.setViewportView(cartArea);
cartArea.setEditable(false);
jLabel1.setText("Banana ($0.99):");
addTocart.setText("Add to Cart");
addTocart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addTocartActionPerformed(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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(appleLabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(appleField)
.addGap(44, 44, 44))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addTocart)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(bananaField, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(appleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(appleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bananaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
.addComponent(addTocart))
.addComponent(jScrollPane1))
.addContainerGap())
);
pack();
}// </editor-fold>
**// HEEEEEEERRRRRRRRRRRREEEEEEEEEEEEEEEEEEEEEE
void printList() {
cartArea.setText("");
for (int i = 0; i < list.length; i++){
cartArea.append(list[i].toString());
}//******** ^ THIS IS THE METHOD IM TALKING ABOUT (printList)^*******
}**
**private void addTocartActionPerformed(java.awt.event.ActionEvent evt) {
double a = Double.parseDouble(appleField.getText());
list.add(new MyShoppingCart(a));
double b = Double.parseDouble(bananaField.getText());
list.add(new MyShoppingCart(b));
appleField.setText("");
bananaField.setText("");
printList();
} //where the values are parsed**
/**
* #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(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(foodDept.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(foodDept.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 foodDept().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton addTocart;
private javax.swing.JTextField appleField;
private javax.swing.JLabel appleLabel;
private javax.swing.JTextField bananaField;
private javax.swing.JTextArea cartArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
You try to use List as an Array, but it's wrong.
Use next:
for (int i = 0; i < list.size(); i++){
cartArea.append(list.get(i).toString());
}
list.size() like a array.length
and list.get(i) as array[i]
Read tutorial for List.

action when component state changed

I have a series of radio buttons generated as an array and displayed in a jPanel.
I want a series of checkboxes in a second panel to be enbled when the radio buttons are in output state but not in the input (input or output are the radio choices).
I want to call the checking state method whenever any of the radiobuttons states change but don't know how to do this as they are created in an array.
Currently the method is called only when the radio button panel is actually clicked.
package my.ArduinoGUI;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
public class ArduinoGUI extends javax.swing.JFrame {
public ArduinoGUI() {
initCustomComponents();
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() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
digitalPinPanel = new javax.swing.JPanel(new GridLayout(0, 3));
jPanel3 = new javax.swing.JPanel(new GridLayout(0, 1));
jPanel2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Outputs"));
jPanel1.setName("Outputs"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 209, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 106, Short.MAX_VALUE)
);
digitalPinPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Digital Pin State"));
digitalPinPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
digitalPinPanelMouseReleased(evt);
}
});
digitalPinLabelArray = new javax.swing.JLabel[digitalPinTotal];
digitalPinRadioButtonArray = new javax.swing.JRadioButton[digitalPinTotal][2];
digitalPinGroupArray = new javax.swing.ButtonGroup[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinGroupArray[x] = new javax.swing.ButtonGroup(); // populate button group
digitalPinLabelArray[x] = new javax.swing.JLabel(); // populate label array
digitalPinLabelArray[x].setText("Pin " + (x +2));
digitalPinPanel.add(digitalPinLabelArray[x]); // add label to panel
for(int y = 0; y < 2; y++){
digitalPinRadioButtonArray[x][y] = new javax.swing.JRadioButton(); // populate radio button array
if (y == 0) {digitalPinRadioButtonArray[x][y].setText("Input");}
if (y == 1) {digitalPinRadioButtonArray[x][y].setText("Output"); digitalPinRadioButtonArray[x][y].setSelected(true);
}
digitalPinGroupArray[x].add(digitalPinRadioButtonArray[x][y]); // assign radio buttons to group
digitalPinPanel.add(digitalPinRadioButtonArray[x][y]); // add buttons to panel
}
}
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Generated Boxes"));
digitalPinOutputArray = new javax.swing.JCheckBox[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinOutputArray[x] = new javax.swing.JCheckBox();
digitalPinOutputArray[x].setText("Output Pin " + (x+2));
jPanel3.add(digitalPinOutputArray[x]);
}
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Analog Pin State"));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 126, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
digitalPinPanel.getAccessibleContext().setAccessibleName("DigitalPins");
pack();
}// </editor-fold>
private void digitalPinPanelMouseReleased(java.awt.event.MouseEvent evt) {
// if output selected enable checkbox otherwise disable it
for (int x = 0; x < digitalPinTotal; x++) {
if (digitalPinRadioButtonArray[x][0].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(false);
}
if (digitalPinRadioButtonArray[x][1].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(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 ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.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 ArduinoGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel digitalPinPanel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration
private int digitalPinTotal = 12;
private int analogPinTotal = 8;
private javax.swing.JCheckBox[] digitalPinOutputArray;
private javax.swing.JRadioButton[][] digitalPinRadioButtonArray;
private javax.swing.ButtonGroup[] digitalPinGroupArray;
private javax.swing.JLabel[] digitalPinLabelArray;
private void initCustomComponents() {
//throw new UnsupportedOperationException("Not yet implemented");
// create checkbox array
}
}
digitalPinRadioButtonArray[x][y].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Output"))
{
digitalPinOutputArray[2].setSelected(true);
}
}
});
try this

Categories

Resources