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.
Related
I am using Netbeans. I set up a graphics program to do graphing. I overrode 3 JPanel paintComponent methods just to get started but these methods are not being called.
I have programs that work. My new override code looks the same. I've tried a plethora of things and have run out of ideas. I am using Borderlayout for the first time but that shouldn't cause a problem.
import java.awt.Graphics;
import java.awt.Graphics2D;
/*
* 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.
*/
public class MainForm extends javax.swing.JFrame
{
/**
* Creates new form NewJFrame
*/
public MainForm()
{
initComponents();
initProgram();
}
private void initProgram()
{
System.out.println("InitProgram");
}
/**
* 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()
{
pnlPrintPanel = new javax.swing.JPanel();
pnlGraphForm = new javax.swing.JPanel();
pnlGraph = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
pnlInputPanel = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation
(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pnlGraphForm.setBorder
(javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
pnlGraph.setBorder
(javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
jLabel2.setText("jLabel2");
javax.swing.GroupLayout pnlGraphLayout =
new javax.swing.GroupLayout(pnlGraph);
pnlGraph.setLayout(pnlGraphLayout);
pnlGraphLayout.setHorizontalGroup(
pnlGraphLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
pnlGraphLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(277, 277, 277))
);
pnlGraphLayout.setVerticalGroup(
pnlGraphLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphLayout.createSequentialGroup()
.addGap(101, 101, 101)
.addComponent(jLabel2)
.addContainerGap(204, Short.MAX_VALUE))
);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout pnlGraphFormLayout =
new javax.swing.GroupLayout(pnlGraphForm);
pnlGraphForm.setLayout(pnlGraphFormLayout);
pnlGraphFormLayout.setHorizontalGroup(
pnlGraphFormLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE,
59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pnlGraphFormLayout.setVerticalGroup(
pnlGraphFormLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlGraphFormLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pnlGraph, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap())
);
pnlGraph = new javax.swing.JPanel()
{
//#Override
//public void paint(Graphics g)
#Override
public void paintComponent(Graphics g)
{
System.out.println("In pnlGraph.paintComponent");
//super.paint(g);
/*
if (grapher == null)
{
return;
}
*/
super.paintComponent(g);
// grapher.drawSlate((Graphics2D)g);
pack();
}
};
pnlInputPanel.setBorder(
javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.RAISED));
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout pnlInputPanelLayout =
new javax.swing.GroupLayout(pnlInputPanel);
pnlInputPanel.setLayout(pnlInputPanelLayout);
pnlInputPanelLayout.setHorizontalGroup(
pnlInputPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlInputPanelLayout.createSequentialGroup()
.addGap(271, 271, 271)
.addComponent(jButton1)
.addContainerGap(297, Short.MAX_VALUE))
);
pnlInputPanelLayout.setVerticalGroup(
pnlInputPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlInputPanelLayout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
javax.swing.GroupLayout pnlPrintPanelLayout =
new javax.swing.GroupLayout(pnlPrintPanel);
pnlPrintPanel.setLayout(pnlPrintPanelLayout);
pnlPrintPanelLayout.setHorizontalGroup(
pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addComponent(pnlInputPanel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addComponent(pnlGraphForm,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pnlPrintPanelLayout.setVerticalGroup(
pnlPrintPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlPrintPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pnlGraphForm,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pnlInputPanel,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
);
pnlGraphForm = new javax.swing.JPanel()
{
//#Override
//public void paint(Graphics g)
#Override
public void paintComponent(Graphics g)
{
System.out.println("In pnlGraphForm.paintComponent");
//super.paint(g);
/*
if (grapher == null)
{
return;
}
*/
super.paintComponent(g);
// grapher.drawSlate((Graphics2D)g);
pack();
}
};
getContentPane().add(pnlPrintPanel, java.awt.BorderLayout.CENTER);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
System.out.println("BUTTON");
pnlGraphForm.paintComponents((Graphics2D)
pnlGraphForm.getGraphics());
}
/**
* #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(MainForm.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(
MainForm.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(
MainForm.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(
MainForm.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new MainForm().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.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel pnlGraph;
private javax.swing.JPanel pnlGraphForm;
private javax.swing.JPanel pnlInputPanel;
private javax.swing.JPanel pnlPrintPanel;
// End of variables declaration
}
At this stage, I expected to see the panel/method names printed but it isn't happening
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
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.
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
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());