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
Related
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 am building a product database and when I'm using the update database function my program crashes.
The issue is one string the program itself throws in.
I retrieve the data from the database text file and because I'm using numberformat.getCurrencyInstance and it throws in a dollar sign. So I threw in an exception String price = updatePriceTextField.getText().substring(1); so it would bypass the dollar sign in the beginning of the text field and send the information back to the textfile and save.
Now it brought up my current problem which is: when I enter a number bigger than 999 and I get to thousands, it brings in a comma: example: $3000.00 is now $3,000.00 and when i try to send that information back to the database it throws in an error and crashes.
Now I know I could just simply add in another substring to avoid, and solve the problem like that, but what if the price of the object lets say is: $300000000.00 the the program throws in 2 commas $300,000,000.00 and would crash again. So what sort of exception or command should I throw in to bypass these commas except substring.
Sorry for the long post, but I tried to explain the issue as well as I could.
import java.util.ArrayList;
/**
*
* #author 0103425014
*/
public class EditProduct extends javax.swing.JFrame {
ProductTextFile txtfile = new ProductTextFile();
ArrayList<Product> products = txtfile.getProducts();
/**
* Creates new form UpdateProduct
*/
public EditProduct() {
initComponents();
for (Product p : products)
updateComboBox.addItem(p.getCode() + " " + p.getDescription());
}
/**
* 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() {
updateComboBox = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
updateCodeTextField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
updateDesTextField = new javax.swing.JTextField();
updatePriceTextField = new javax.swing.JTextField();
buttonUpdate = new javax.swing.JButton();
buttonExit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
updateComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateComboBoxActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Select Product to edit:");
jLabel2.setText("Product Code:");
jLabel3.setText("Product Description:");
jLabel4.setText("Product Price:");
buttonUpdate.setText("UPDATE");
buttonUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonUpdateActionPerformed(evt);
}
});
buttonExit.setText("EXIT");
buttonExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonExitActionPerformed(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(76, 76, 76)
.addComponent(buttonUpdate)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonExit)
.addGap(104, 104, 104))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(updateCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(updateDesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(updatePriceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(updateComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jLabel1)))
.addGap(0, 126, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel1)
.addGap(33, 33, 33)
.addComponent(updateComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(updateCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(updateDesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(updatePriceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(60, 60, 60)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonUpdate)
.addComponent(buttonExit))
.addContainerGap(73, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void buttonExitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void buttonUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Product p = new Product();
p.setCode(updateCodeTextField.getText());
p.setDescription(updateDesTextField.getText());
String price = updatePriceTextField.getText().substring(1);
p.setPrice(Double.parseDouble(price));
txtfile.updateProduct(p);
UpdatedConfirm confirmed = new UpdatedConfirm();
confirmed.setVisible(true);
this.setVisible(false);
// txtfile.updateProduct();
}
private void updateComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int si = updateComboBox.getSelectedIndex();
Product sp = products.get(si);
updateCodeTextField.setText(sp.getCode());
updateDesTextField.setText(sp.getDescription());
updatePriceTextField.setText(sp.getFormattedPrice());
}
/**
* #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(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EditProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EditProduct.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 EditProduct().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonExit;
private javax.swing.JButton buttonUpdate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField updateCodeTextField;
private javax.swing.JComboBox updateComboBox;
private javax.swing.JTextField updateDesTextField;
private javax.swing.JTextField updatePriceTextField;
// End of variables declaration
}
Use a JFormattedTextField instead, this way you just use getValue and it will return you the unformatted value for the field.
See How to Use Formatted Text Fields for more details
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
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.
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:)