How to get ALL values from a Jtable and graph them? - java

I have a jtable set up that I've populated with values from a .csv file. I need to retrieve all of the values from the jtable and graph them, but am having trouble figuring it out. I'm using JFreeChart and have set up the graph but am absolutely stuck on how to populate the line graph with values from the JTable.
Code that I've tried, but isn't working and simply halts the application when I hit the graph button:
//instantiate the data series and the chart
int row = tableRadio.getRowCount();
int column = tableRadio.getColumnCount();
for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
series.add(r, c);
}
}
Entire Code:
//data used by all methods
DefaultTableModel tableModel;
//Global variables
XYSeries series; //series of data that will be added to the graph
XYSeriesCollection dataSet; //a collection object holds the series
JFreeChart chart; //chart to be placed on the panel
public MainWindow() {
initComponents();
//instantiate the DefaultTableModel
tableModel = (DefaultTableModel) tableRadio.getModel();
//instantiate the data series and the chart
series = new XYSeries("Random Numbers");
dataSet = new XYSeriesCollection(series);
chart = ChartFactory.createXYLineChart("Radio Astronomy Graphing", "Time", "Sensor Value", dataSet);
//display the graphing chart on the panel
panelGraph.add(new ChartPanel(chart), BorderLayout.CENTER);
panelGraph.revalidate();
//center the applications window upon start
this.setLocationRelativeTo(null);
}
/**
* 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() {
buttonLoad = new javax.swing.JButton();
buttonGraph = new javax.swing.JButton();
buttonSave = new javax.swing.JButton();
buttonAdd = new javax.swing.JButton();
buttonEdit = new javax.swing.JButton();
buttonRemove = new javax.swing.JButton();
labelValue = new javax.swing.JLabel();
tfMonth = new javax.swing.JTextField();
tfValue = new javax.swing.JTextField();
tfDay = new javax.swing.JTextField();
labelHour = new javax.swing.JLabel();
labelMin = new javax.swing.JLabel();
labelYear = new javax.swing.JLabel();
labelDay = new javax.swing.JLabel();
labelMonth = new javax.swing.JLabel();
tfYear = new javax.swing.JTextField();
tfHour = new javax.swing.JTextField();
tfMin = new javax.swing.JTextField();
panelGraph = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tableRadio = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonLoad.setText("Load File");
buttonLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonLoadActionPerformed(evt);
}
});
buttonGraph.setText("Graph Data");
buttonGraph.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonGraphActionPerformed(evt);
}
});
buttonSave.setText("Save");
buttonSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSaveActionPerformed(evt);
}
});
buttonAdd.setText("Add");
buttonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonAddActionPerformed(evt);
}
});
buttonEdit.setText("Edit");
buttonEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonEditActionPerformed(evt);
}
});
buttonRemove.setText("Remove");
buttonRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRemoveActionPerformed(evt);
}
});
labelValue.setText("Sensor Value:");
tfValue.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tfValueActionPerformed(evt);
}
});
labelHour.setText("Hour");
labelMin.setText("Minute");
labelYear.setText("Year");
labelDay.setText("Day");
labelMonth.setText("Month");
panelGraph.setLayout(new java.awt.BorderLayout());
tableRadio.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Date and Time", "Sensor Value"
}
) {
boolean[] canEdit = new boolean [] {
false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tableRadio);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(buttonLoad, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonSave, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonGraph, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(buttonAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(84, 84, 84)
.addComponent(labelMonth)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfMonth, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(labelDay)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfDay, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(buttonEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(buttonRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelValue)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfValue, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(labelHour)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfHour, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addComponent(labelMin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfMin, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelYear)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfYear, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(panelGraph, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 17, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelGraph, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonLoad)
.addComponent(buttonAdd)
.addComponent(labelMonth)
.addComponent(tfMonth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelDay)
.addComponent(tfDay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelYear)
.addComponent(tfYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonGraph)
.addComponent(buttonEdit)
.addComponent(tfHour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelHour)
.addComponent(labelMin)
.addComponent(tfMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonSave)
.addComponent(buttonRemove)
.addComponent(labelValue)
.addComponent(tfValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(35, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void buttonLoadActionPerformed(java.awt.event.ActionEvent evt) {
//Load file into table
//create JFileChooser
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
//create myFile and define the path
File myFile = fileChooser.getSelectedFile();
try{
//instantiate Scanner
Scanner inputStream = new Scanner(myFile);
for(int i=0; i < 12; i++){
inputStream.nextLine();
}
//split values into 2 arrays and insert into table
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
tableModel.insertRow(tableModel.getRowCount(), values);
}//end of while block
}//end of try block
catch(FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "File Not Found");
}//end of catch block
}
private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {
//add info from text fields and combo boxes to table
try {
//create variables to hold the contents of what user has typed in
int Month = Integer.parseInt(tfMonth.getText());
int Day = Integer.parseInt(tfDay.getText());
int Year = Integer.parseInt(tfYear.getText());
int Hour = Integer.parseInt(tfHour.getText());
int Min = Integer.parseInt(tfMin.getText());
double Value = Double.parseDouble(tfValue.getText());
//add the info to the table
tableModel.insertRow(tableModel.getRowCount(), new Object[]{Month + "/" + Day + "/" + Year + " " + Hour + ":" + Min, Value });
//clear the controls on the interface
tfMonth.setText("");
tfDay.setText("");
tfYear.setText("");
tfHour.setText("");
tfMin.setText("");
tfValue.setText("");
}//end of try block
catch(NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Please fill out all fields and enter only numbers");
}//end of catch block
}
private void buttonEditActionPerformed(java.awt.event.ActionEvent evt) {
//edit info based on row selected
//make sure a row is selected
if(tableRadio.getSelectedRow() >= 0){
//set the values in the table for all text fields
tableModel.setValueAt(tfMonth.getText() + "/" + tfDay.getText() + "/" + tfYear.getText() + " " + tfHour.getText() + ":" + tfMin.getText(), tableRadio.getSelectedRow(), 0);
tableModel.setValueAt(tfValue.getText(), tableRadio.getSelectedRow(), 1);
//clear the user interface controls after adding them to the table
tfMonth.setText("");
tfDay.setText("");
tfYear.setText("");
tfHour.setText("");
tfMin.setText("");
tfValue.setText("");
}//end of if block checking for selected row
else{
JOptionPane.showMessageDialog(this, "Please select a row.");
}//end of else block
}
private void buttonRemoveActionPerformed(java.awt.event.ActionEvent evt) {
//Delete the selected row
//Make sure a row is selected
if(tableRadio.getSelectedRow() >= 0){
//remove the row
tableModel.removeRow(tableRadio.getSelectedRow());
//clear the user interface controls after deleting a row
tfMonth.setText("");
tfDay.setText("");
tfYear.setText("");
tfHour.setText("");
tfMin.setText("");
tfValue.setText("");
}//end of if block
else{
JOptionPane.showMessageDialog(this, "Please select a row.");
}//end of else block
}
private void buttonGraphActionPerformed(java.awt.event.ActionEvent evt) {
//instantiate the data series and the chart
int row = tableRadio.getRowCount();
int column = tableRadio.getColumnCount();
for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
series.add(r, c);
}
}
}
private void tfValueActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {
try {
// capture the whole screen
BufferedImage radioGraph = new Robot().createScreenCapture(
new Rectangle( panelGraph.getX(), panelGraph.getY(), panelGraph.getWidth(), panelGraph.getHeight() ) );
//Save as PNG
File file = new File("radioGraph.png");
ImageIO.write(radioGraph, "png", file);
JOptionPane.showMessageDialog(this, "radioGraph.png added to project folder");
}
catch(AWTException e) {
JOptionPane.showMessageDialog(this, "Error");
}
catch(IOException e){
JOptionPane.showMessageDialog(this, "Error");
}
}
/**
* #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(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainWindow.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 MainWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonAdd;
private javax.swing.JButton buttonEdit;
private javax.swing.JButton buttonGraph;
private javax.swing.JButton buttonLoad;
private javax.swing.JButton buttonRemove;
private javax.swing.JButton buttonSave;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelDay;
private javax.swing.JLabel labelHour;
private javax.swing.JLabel labelMin;
private javax.swing.JLabel labelMonth;
private javax.swing.JLabel labelValue;
private javax.swing.JLabel labelYear;
private javax.swing.JPanel panelGraph;
private javax.swing.JTable tableRadio;
private javax.swing.JTextField tfDay;
private javax.swing.JTextField tfHour;
private javax.swing.JTextField tfMin;
private javax.swing.JTextField tfMonth;
private javax.swing.JTextField tfValue;
private javax.swing.JTextField tfYear;
// End of variables declaration
Any Ideas on what might work for me? I've never had to get data from a table and graph it so this is all new to me. Please let me know if I've messed up somewhere.

series.add(r, c);
That won't do anything. You are just getting the indexes of your loop.
You want something like:
series.add( tableRadio.getValueAt(r, c) );
Of course the getValueAt(...) method just returns an Object so you will need to convert the Object to the data type needed for the series Object.
Also if you need two parameter for the series Object, then you will obviously need two getValueAt(...) statements. Maybe you only have two columns, so you only need a single loop on the rows and then you get the value from column 0 and column 1? Only you know the data you have in your table.

Related

Radio Button In Java

I just want to ask if I can change the text in radio button.
For example:
here in the picture if I put a number, it will show the number factors at the radio button. ( the factor 1 will just show in Jlabel and the rest of the factor will show at the Radio button) the problem part at the private void checkbtnActionPerformed(java.awt.event.ActionEvent evt) I already tried to use .setText() but I think this will not work for radio button or button group. Is there another way to do that
public class primefactor extends javax.swing.JFrame {
/**
* Creates new form primefactor
*/
public primefactor() {
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() {
numfactorgr = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
checkbtn = new javax.swing.JButton();
cleatbtn = new javax.swing.JButton();
inspectbtn = new javax.swing.JButton();
num1 = new javax.swing.JLabel();
numdis = new javax.swing.JLabel();
numtxt = new javax.swing.JTextField();
primeyn = new javax.swing.JLabel();
numfactors1 = new javax.swing.JRadioButton();
numfactors2 = new javax.swing.JRadioButton();
numfactors3 = new javax.swing.JRadioButton();
numfactors4 = new javax.swing.JRadioButton();
numfactors = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("NUMBER::");
jLabel2.setText("FACTORS::");
jLabel3.setText("PRIME:");
checkbtn.setText("CHECK");
checkbtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkbtnActionPerformed(evt);
}
});
cleatbtn.setText("CLEAR");
cleatbtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cleatbtnActionPerformed(evt);
}
});
inspectbtn.setText("INSPECT");
inspectbtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
inspectbtnActionPerformed(evt);
}
});
numdis.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
numtxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
numtxtActionPerformed(evt);
}
});
numfactorgr.add(numfactors1);
numfactorgr.add(numfactors2);
numfactorgr.add(numfactors3);
numfactorgr.add(numfactors4);
numfactors.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
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(checkbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 138, Short.MAX_VALUE)
.addComponent(cleatbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(num1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(numdis, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(numfactors, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(inspectbtn))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(primeyn)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numtxt))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(numfactors1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numfactors2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numfactors3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numfactors4)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(numtxt, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(numdis)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(inspectbtn)
.addComponent(num1)
.addComponent(numfactors)))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(primeyn))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 3, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(numfactors1)
.addComponent(numfactors2)
.addComponent(numfactors3)
.addComponent(numfactors4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(checkbtn)
.addComponent(cleatbtn))
.addContainerGap())
);
pack();
}// </editor-fold>
private void numtxtActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void checkbtnActionPerformed(java.awt.event.ActionEvent evt) {
String str = numtxt.getText();
int num = Integer.parseInt(str);
int flag = 0;
numdis.setText(str);
num1.setText("1");
for (int i=2;i<num;i++){
if (num%i ==0){
flag =1;
num1.setText("1");
numfactors.setText( numfactors.getText()+i+" "); // at this part it will display the radio button with the number factors. (but I use first the jlabel numfactors to show the number factors)
}
}
if (flag == 0){
primeyn.setText("Yes");
}
else{
primeyn.setText(primeyn.getText()+"No");
}
}
private void cleatbtnActionPerformed(java.awt.event.ActionEvent evt) {
numtxt.setText("");
num1.setText("");
numdis.setText("");
numfactors.setText("");
primeyn.setText("");
}
private void inspectbtnActionPerformed(java.awt.event.ActionEvent evt) {
// 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(primefactor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(primefactor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(primefactor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(primefactor.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 primefactor().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton checkbtn;
private javax.swing.JButton cleatbtn;
private javax.swing.JButton inspectbtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel num1;
private javax.swing.JLabel numdis;
private javax.swing.ButtonGroup numfactorgr;
private javax.swing.JLabel numfactors;
private javax.swing.JRadioButton numfactors1;
private javax.swing.JRadioButton numfactors2;
private javax.swing.JRadioButton numfactors3;
private javax.swing.JRadioButton numfactors4;
private javax.swing.JTextField numtxt;
private javax.swing.JLabel primeyn;
// End of variables declaration
}

Junit Testing for GUI

I have following Simple Utility Calculator
Now i want to apply some Junit Testing here.
I don't know how to perform a Junit testing on Gui.
So kindly help me out.
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.
*/
package calculator;
import java.io.*;
import java.text.DecimalFormat;
/**
*
* #author owner
*/
public class Calculator_Utility extends javax.swing.JFrame {
/**
* Creates new form Calculator_Utility
*/
public Calculator_Utility() {
initComponents();UsePowerKw.setText("4.0");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void setComponentsName(){
AddButton.setName("Add");
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
CostPerKW = new javax.swing.JLabel();
SelectAppliance = new javax.swing.JLabel();
PowerUsage = new javax.swing.JLabel();
NumberHoursUse = new javax.swing.JLabel();
TotalCostApp = new javax.swing.JLabel();
AddButton = new javax.swing.JButton();
CostPerKwTextField = new javax.swing.JTextField();
UsePowerKw = new javax.swing.JTextField();
HourUse = new javax.swing.JTextField();
CostApp = new javax.swing.JTextField();
AllTotal = new javax.swing.JLabel();
AllTotalApp = new javax.swing.JTextField();
SelectApp = new javax.swing.JComboBox<>();
Showfield = new javax.swing.JTextField();
GallonWater = new javax.swing.JLabel();
GallonWat = new javax.swing.JTextField();
Export = new javax.swing.JButton();
CostGallon = new javax.swing.JLabel();
CostGall = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
CostPerKW.setText("Cost Per KW Hour:");
SelectAppliance.setText("Select Appliance:");
PowerUsage.setText("Power Usage In KW Hours:");
NumberHoursUse.setText("Number of Hours use per day:");
TotalCostApp.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
TotalCostApp.setText("Total Cost For Appliance");
AddButton.setText("ADD");
AddButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AddButtonActionPerformed(evt);
}
});
CostPerKwTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CostPerKwTextFieldActionPerformed(evt);
}
});
UsePowerKw.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UsePowerKwActionPerformed(evt);
}
});
AllTotal.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
AllTotal.setText("Total of All Appliances");
SelectApp.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Refrigerator", "Washer", "Dryer", "Freezer", "Air Conditioner" }));
SelectApp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SelectAppActionPerformed(evt);
}
});
GallonWater.setText("Gallon of Water:");
Export.setText("Export");
Export.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExportActionPerformed(evt);
}
});
CostGallon.setText("Cost Per Gallon:");
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(NumberHoursUse)
.addComponent(SelectAppliance)
.addComponent(PowerUsage)
.addComponent(CostPerKW))
.addComponent(CostGallon, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(GallonWater, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(4, 4, 4))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(AllTotal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CostPerKwTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(UsePowerKw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(HourUse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SelectApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AllTotalApp, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(GallonWat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CostGall, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(Showfield, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(Export)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(TotalCostApp)
.addGap(4, 4, 4)
.addComponent(CostApp, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(AddButton)
.addGap(24, 24, 24))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {AllTotalApp, CostApp, CostGall, CostPerKwTextField, GallonWat, HourUse, SelectApp, UsePowerKw});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostPerKW)
.addComponent(CostPerKwTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SelectAppliance)
.addComponent(SelectApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PowerUsage)
.addComponent(UsePowerKw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(NumberHoursUse)
.addComponent(HourUse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(GallonWat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(GallonWater)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostGallon)
.addComponent(CostGall, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CostApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(TotalCostApp))
.addComponent(AddButton))
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AllTotalApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(AllTotal))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Showfield, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Export))
.addContainerGap())
);
pack();
}// </editor-fold>
//Declare Variables and intialize the variables
private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {
double answer;
double total = 0;
String s = SelectApp.getSelectedItem().toString();
//Check if user select "Washer" from drop down box, calculate usage with Gallon
if (s=="Washer") {
//DecimalFormat df= new DecimalFormat("#.##");
number1 = (int)((Double.parseDouble(CostPerKwTextField.getText())));
number2 = (int)((Double.parseDouble(UsePowerKw.getText())));
number3 = (int)((Double.parseDouble(HourUse.getText())));
number4 = (int)((Double.parseDouble(GallonWat.getText())));
answer = number1*number2*number3;
total =+ answer;
CostApp.setText(String.valueOf(answer + "\n"));
Showfield.setText(String.valueOf("The appliance run a total of " + answer + "\n"));
}
//if user select any appliances other than washer calculate usage
else
number1 = (int)((Double.parseDouble(CostPerKwTextField.getText())));
number2 = (int)((Double.parseDouble(UsePowerKw.getText())));
number3 = (int)((Double.parseDouble(HourUse.getText())));
answer = number1*number2*number3;
total =+ answer;
//Calculated amount is put into field
CostApp.setText(String.valueOf(answer + "\n"));
Showfield.setText(String.valueOf("The appliance run a total of " + answer + "\n"));
// TODO add your handling code here:
}
//Action listener/Events for JCombo. Pre-defined Power Usage for Each Appliacnes
private void SelectAppActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String s=SelectApp.getSelectedItem().toString();
double r=4;
double w=7;
double x=12;
double y=16;
double z=24;
if (s=="Refrigerator"){
UsePowerKw.setText(String.valueOf(r));
}
else if (s=="Washer") {UsePowerKw.setText(String.valueOf(w));}
else if (s=="Dryer") {UsePowerKw.setText(String.valueOf(x));}
else if (s=="Freezer") {UsePowerKw.setText(String.valueOf(y));}
else UsePowerKw.setText(String.valueOf(z));
}
private void UsePowerKwActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//If jComboBox1 = "Refrigerator" then set jTextField4 = 22
}
//Action Listener/Event creates Data.txt with output
private void ExportActionPerformed(java.awt.event.ActionEvent evt) {
File file = new File("Data.txt");
try (Writer writer = new BufferedWriter(new FileWriter(file))) {
String contents = Showfield.getText();
//"The quick brown fox" +
//System.getProperty("line.separator") +
//"jumps over the lazy dog.";
writer.write(contents);
} catch (IOException e) {
e.printStackTrace();
}
}
private void CostPerKwTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// 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(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculator_Utility.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 Calculator_Utility().setVisible(true);
}
});
}
public double number1, number2, number3, number4;
// Variables declaration - do not modify
private javax.swing.JButton AddButton;
private javax.swing.JLabel AllTotal;
private javax.swing.JTextField AllTotalApp;
private javax.swing.JTextField CostApp;
private javax.swing.JTextField CostGall;
private javax.swing.JLabel CostGallon;
private javax.swing.JLabel CostPerKW;
private javax.swing.JTextField CostPerKwTextField;
private javax.swing.JButton Export;
private javax.swing.JTextField GallonWat;
private javax.swing.JLabel GallonWater;
private javax.swing.JTextField HourUse;
private javax.swing.JLabel NumberHoursUse;
private javax.swing.JLabel PowerUsage;
private javax.swing.JComboBox<String> SelectApp;
private javax.swing.JLabel SelectAppliance;
private javax.swing.JTextField Showfield;
private javax.swing.JLabel TotalCostApp;
private javax.swing.JTextField UsePowerKw;
// End of variables declaration
}
Any testCase you can apply like proper working , (actual== expected Result) etc.
You can't test the GUI with JUnit. You can only test the methods.
For example you have a JButton with an actionListener witch calls the method calculate(1, 1):
JButton showDialogButton = new JButton("Text Button");
showDialogButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
calculate(1, 1);
}
});
private int calculate(int n1, int n2){
return n1 + n2;
}
Now, You cant test the JButton but you can test the method "calculate". We know that calculate(1, 1) will return us 2 so we test it:
assertEquals(2, calculate(1, 1));
This means, that you cannot "press the button with JUnit" but you can test the action the button does.

Why does my program freeze/crash when i try to run it?

This is not a complete program but im wondering why it freezez when i press the "JButton". I am Currently working on a dice game and so far its going fine but i cant understand why it wont run at the moment. Thanks for the help in beforehand :)
PS. The problem started after i added the while loop in the method diceLogic.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dicegame_leonardasp;
/**
*
* #author LeoAsp
*/
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.util.Random;
import javafx.scene.control.Cell;
public class DiceGameGui extends javax.swing.JFrame {
//Instansvariabel
//Skapa instans av Randomklassen
Random rand = new Random();
public DiceGameGui() {
initComponents();
}
public String doMessage() {
String message = "";
return message;
}
public String doReDice() {
String image = "";
int randNum = rand.nextInt(6 - 1) + 1;
if (randNum == 1) {
image = "one.gif";
} else if (randNum == 2) {
image = "two.gif";
} else if (randNum == 3) {
image = "three.gif";
} else if (randNum == 4) {
image = "four.gif";
} else if (randNum == 5) {
image = "five.gif";
} else if (randNum == 6) {
image = "six.gif";
} else {
dispose();
}
return image;
}
public void diceLogic(int players, int dice) {
jDiceResult.removeAll();
jDiceResult.setLayout(new java.awt.GridLayout(6, 5));
JLabel playersArray[][] = new JLabel[players][dice];
int j;
int i;
for (i = 0; i <= players; i++) {
for (j = 0; j < dice; j++) {
playersArray[i][j] = new JLabel();
playersArray[i][j].setIcon(new ImageIcon(doReDice()));
playersArray[i][j].setPreferredSize(new Dimension(60, 50));
// playersArray[i][j].setPreferredSize(new Dimension(20, 20));
//playersArray[i][j].setMinimumSize(new Dimension(20, 20));
//playersArray[i][j].setMaximumSize(new Dimension(20, 20));
jDiceResult.add(playersArray[i][j]);
jDiceResult.revalidate();
jDiceResult.repaint();
}
while (j <= 6) {
jDiceResult.add(javax.swing.Box.createGlue());
}
}
}
/**
* 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();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jBoxPlayers = new javax.swing.JComboBox();
jBoxDice = new javax.swing.JComboBox();
jBtnRoll = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jDiceResult = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
jLabel1.setText("Players:");
jLabel2.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
jLabel2.setText("Dice:");
jLabel3.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
jBoxPlayers.setFont(new java.awt.Font("Menlo", 1, 14)); // NOI18N
jBoxPlayers.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
"1", "2", "3", "4", "5"
}));
jBoxPlayers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBoxPlayersActionPerformed(evt);
}
});
jBoxDice.setFont(new java.awt.Font("Menlo", 1, 14)); // NOI18N
jBoxDice.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
"1", "2", "3", "4", "5", "6"
}));
jBoxDice.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBoxDiceActionPerformed(evt);
}
});
jBtnRoll.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
jBtnRoll.setText("Roll the Dice");
jBtnRoll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtnRollActionPerformed(evt);
}
});
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setFont(new java.awt.Font("Menlo", 0, 14)); // NOI18N
jButton1.setText("Show Highscore");
jDiceResult.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jDiceResult.setPreferredSize(new java.awt.Dimension(250, 300));
javax.swing.GroupLayout jDiceResultLayout = new javax.swing.GroupLayout(jDiceResult);
jDiceResult.setLayout(jDiceResultLayout);
jDiceResultLayout.setHorizontalGroup(
jDiceResultLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 246, Short.MAX_VALUE)
);
jDiceResultLayout.setVerticalGroup(
jDiceResultLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 296, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jBoxPlayers, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(91, 91, 91)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3))
.addComponent(jBoxDice, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jBtnRoll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDiceResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jBoxPlayers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jBoxDice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jBtnRoll, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jDiceResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
} // </editor-fold>
private void jBoxPlayersActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jBoxDiceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jBtnRollActionPerformed(java.awt.event.ActionEvent evt) {
int dice = Integer.parseInt(jBoxDice.getSelectedItem().toString());
int players = Integer.parseInt(jBoxPlayers.getSelectedItem().toString());
diceLogic(players, dice);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
//<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(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DiceGameGui.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 DiceGameGui().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox jBoxDice;
private javax.swing.JComboBox jBoxPlayers;
private javax.swing.JButton jBtnRoll;
private javax.swing.JButton jButton1;
private javax.swing.JPanel jDiceResult;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
This is the problem:
while (j <= 6) {
jDiceResult.add(javax.swing.Box.createGlue());
}
With this line, you create a infinite loop, because you check whether j<=6 but don't change the value of j, so j<=6 is always true.
I guess you want to change while to if.
I guess:
while (j <= 6) {
jDiceResult.add(javax.swing.Box.createGlue());
}
I think may be it should be:
if (j <= 6) {
jDiceResult.add(javax.swing.Box.createGlue());
}

action when component state changed

I have a series of radio buttons generated as an array and displayed in a jPanel.
I want a series of checkboxes in a second panel to be enbled when the radio buttons are in output state but not in the input (input or output are the radio choices).
I want to call the checking state method whenever any of the radiobuttons states change but don't know how to do this as they are created in an array.
Currently the method is called only when the radio button panel is actually clicked.
package my.ArduinoGUI;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
public class ArduinoGUI extends javax.swing.JFrame {
public ArduinoGUI() {
initCustomComponents();
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
digitalPinPanel = new javax.swing.JPanel(new GridLayout(0, 3));
jPanel3 = new javax.swing.JPanel(new GridLayout(0, 1));
jPanel2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Outputs"));
jPanel1.setName("Outputs"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 209, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 106, Short.MAX_VALUE)
);
digitalPinPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Digital Pin State"));
digitalPinPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
digitalPinPanelMouseReleased(evt);
}
});
digitalPinLabelArray = new javax.swing.JLabel[digitalPinTotal];
digitalPinRadioButtonArray = new javax.swing.JRadioButton[digitalPinTotal][2];
digitalPinGroupArray = new javax.swing.ButtonGroup[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinGroupArray[x] = new javax.swing.ButtonGroup(); // populate button group
digitalPinLabelArray[x] = new javax.swing.JLabel(); // populate label array
digitalPinLabelArray[x].setText("Pin " + (x +2));
digitalPinPanel.add(digitalPinLabelArray[x]); // add label to panel
for(int y = 0; y < 2; y++){
digitalPinRadioButtonArray[x][y] = new javax.swing.JRadioButton(); // populate radio button array
if (y == 0) {digitalPinRadioButtonArray[x][y].setText("Input");}
if (y == 1) {digitalPinRadioButtonArray[x][y].setText("Output"); digitalPinRadioButtonArray[x][y].setSelected(true);
}
digitalPinGroupArray[x].add(digitalPinRadioButtonArray[x][y]); // assign radio buttons to group
digitalPinPanel.add(digitalPinRadioButtonArray[x][y]); // add buttons to panel
}
}
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Generated Boxes"));
digitalPinOutputArray = new javax.swing.JCheckBox[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinOutputArray[x] = new javax.swing.JCheckBox();
digitalPinOutputArray[x].setText("Output Pin " + (x+2));
jPanel3.add(digitalPinOutputArray[x]);
}
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Analog Pin State"));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 126, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
digitalPinPanel.getAccessibleContext().setAccessibleName("DigitalPins");
pack();
}// </editor-fold>
private void digitalPinPanelMouseReleased(java.awt.event.MouseEvent evt) {
// if output selected enable checkbox otherwise disable it
for (int x = 0; x < digitalPinTotal; x++) {
if (digitalPinRadioButtonArray[x][0].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(false);
}
if (digitalPinRadioButtonArray[x][1].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(true);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ArduinoGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel digitalPinPanel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration
private int digitalPinTotal = 12;
private int analogPinTotal = 8;
private javax.swing.JCheckBox[] digitalPinOutputArray;
private javax.swing.JRadioButton[][] digitalPinRadioButtonArray;
private javax.swing.ButtonGroup[] digitalPinGroupArray;
private javax.swing.JLabel[] digitalPinLabelArray;
private void initCustomComponents() {
//throw new UnsupportedOperationException("Not yet implemented");
// create checkbox array
}
}
digitalPinRadioButtonArray[x][y].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Output"))
{
digitalPinOutputArray[2].setSelected(true);
}
}
});
try this

populating a jcombobox with database information

I know I am missing something simple, I think in getting the combobox to access the array.
package my.freelancebillingapp;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import javax.swing.*;
public class billingInfoUI extends javax.swing.JFrame {
public billingInfoUI() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
hoursWorked = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
flatRate = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
workType = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
jList2 = new javax.swing.JList();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Billing Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.ABOVE_BOTTOM, new java.awt.Font("Bleeding Cowboys", 0, 48))); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 457, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
hoursWorked.setHorizontalAlignment(javax.swing.JTextField.CENTER);
hoursWorked.setText("Hours Worked");
hoursWorked.setBorder(null);
jLabel1.setText("Or");
flatRate.setHorizontalAlignment(javax.swing.JTextField.CENTER);
flatRate.setText("Flat Rate");
flatRate.setBorder(null);
workType.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Work Type", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
workType.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Web Design", "Graphic Design", "Consulting" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
workType.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(workType);
jList2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Any Extras?", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
jList2.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Blog", "Forum", "Templating", "Rush Delivery" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(jList2);
jButton1.setText("Save");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jButton2.setText("Invoice");
jButton3.setText("Close");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton3MouseClicked(evt);
}
});
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jComboBox1.setModel(customers);
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))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(89, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(hoursWorked, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addComponent(jLabel1)
.addGap(1, 1, 1))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(flatRate, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(79, 79, 79))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(62, 62, 62)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(79, 79, 79)
.addComponent(jButton3)
.addGap(52, 52, 52))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(134, Short.MAX_VALUE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(107, 107, 107))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(hoursWorked, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(flatRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton1))
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
new FreelanceBillingUI().setVisible(true);
setVisible(false);
}
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
String hoursWorkedtxt = hoursWorked.getText();
String flatRatetxt = flatRate.getText();
workType.getSelectedValue();
workType.toString();
Object workTypetxt = workType.getSelectedValue();
if(hoursWorkedtxt.contains("H")){
hoursWorkedtxt = "0";
}else{
flatRatetxt = "0";
}
}
public class CustomerData {
private static final String JDBC_CONNECTION_URL = "jdbc:mysql://localhost/test";
private static final String DATABASE_USER = "root";
private static final String DATABASE_PASSWORD = "root";
private static final String SQL_FETCH_CUSTOMERS = "SELECT custName FROM customers";
private Connection connection = null;
public CustomerData(){
initConnection();
}
private void initConnection() {
try {
//load the mysql driver
Class.forName("com.mysql.jdbc.Driver");
//create the database connection
connection = DriverManager.getConnection(JDBC_CONNECTION_URL, DATABASE_USER, DATABASE_PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeConnection(){
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
connection = null;
}
}
}
public ArrayList fetchCustomerData(){
if (connection != null){
Statement statement = null;
try {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SQL_FETCH_CUSTOMERS);
return convertResultSetToCustomersArray(resultSet);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("NO VALID DATABASE CONNECTION, CAN'T FETCH CUSTOMER DATA!");
}
return new ArrayList();
}
private ArrayList convertResultSetToCustomersArray(ResultSet results) throws SQLException{
ArrayList customers = new ArrayList();
while (results.next()){
customers.add(results.getString("custName"));
}
return customers;
}
}
private void initData(){
CustomerData customerData = new CustomerData();
ArrayList custArrayList = customerData.fetchCustomerData();
customers = (String[]) custArrayList.toArray(new String[0]);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new billingInfoUI().setVisible(true);
}
});
}
private String[] customers = null;
private javax.swing.JTextField flatRate;
private javax.swing.JTextField hoursWorked;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JList jList2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JList workType;
}
There is too much code there to look at 90% of it is NOT related to adding data in a combo box. You have a dozen other components which clutter the code so we can't see what actually happening with the comobo box.
It you really need help then post a SSCCE.
That is, create a simple frame and load hard coded data into the combo box.
Then create a simple program to read data from the database and use System.out.println(...) to display each value.
Once you've mastered the two basic steps, then put the two programs together to load a combobox dynamically from a database.
Finally add the rest of you components to the frame.
Break you problem down into small, manageable steps and you will be able to debug it easier.
A few points:
Wading through your code, I don't see a call to initData being made anywhere. Without that call, you wont call your database code. Without the database call, you wont get the data.
JComboBox does not have a setModel method that takes an array. You can wrap your array in a DefaultComboBoxModel and set that on the model.
It is good to keep in mind that blocking calls like database access should not be made in the AWT painting thread, and neither should calls that update the GUI be made outside of the AWT thread. You should look into creating your GUI and grabbing your data in separate threads, and making use of SwingUtlities.invokeLater or similar tools to update your GUI.

Categories

Resources