I want to add checkboxes to a jpanel, which is on a jFrame. The UI was made on netbeans and i have copied the code to work on its functionality on eclipse.
I cant get my checkboxes come over the Jpanel.
The code
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.border.Border;
public class QueryBuilderUI extends javax.swing.JFrame {
QueryBuilderMethods objQBM = new QueryBuilderMethods();
DefaultComboBoxModel<String> repoModel = new DefaultComboBoxModel<String>();
public QueryBuilderUI() {
getRepositoryListing();
initComponents();
}
private void getRepositoryListing()
{
repoModel = new QueryBuilderMethods().getAllRepositoryName();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jTextField1 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Choose Repository");
jComboBox1.setModel(repoModel);
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox1ItemStateChanged(evt);
}
});
jLabel2.setText("Choose Table");
//jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox2ItemStateChanged(evt);
}
});
jLabel3.setText("Choose Columns");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
Border border = BorderFactory.createTitledBorder("Select Columns");
jPanel1.setBorder(border);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 459, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 124, Short.MAX_VALUE)
);
jTextField1.setText("jTextField1");
jLabel4.setText("Generated Query");
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)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(57, 57, 57)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(65, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jComboBox1, 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(jLabel2)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(92, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if(evt.getStateChange()== ItemEvent.SELECTED){
Object item = evt.getItem();
DefaultComboBoxModel<String> modelTable = objQBM.getAllTablesForRepo(item.toString());
jComboBox2.setModel(modelTable);
}
}
private void jComboBox2ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if(evt.getStateChange()== ItemEvent.SELECTED){
Object item = evt.getItem();
String RepoName = jComboBox1.getSelectedItem().toString();
List<String> columnNames = objQBM.getAllColumnsForTable(item.toString());
addCheckBox(columnNames);
}
}
private void addCheckBox(List<String> columnNames)
{
int numberCheckBox = columnNames.size();
JCheckBox[] checkBoxList = new JCheckBox[numberCheckBox];
for(int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("hi"+i);
jPanel1.add(checkBoxList[i]);
}
jPanel1.revalidate();
}
public static void main(String args[]) {
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
new QueryBuilderUI().setVisible(true);
// }
// });
}
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
the UI Looks like this
The checkboxes needs to be created dynamically according to what is selected on jComboBox2.
Your jPanel1 JPanel is being constrained by its layout, GroupLayout, which does not take kindly to the addition of new components without significant additions to code that are difficult to make, since GroupLayout was not built to be used for hand coding but rather for GUI-builder coding. I suggest that you build your GUI with much more coder-friendly layouts, or better still, combinations of nested JPanels each using a simpler layout, ones that are much more conducive to the addition of new components, and then your problems will be more easily solved.
You could even still use GroupLayout for the main of your GUI if you desire, but just not for jPanel1. I suggest that you consider using GridLayout or GridBagLayout to add a grid of JCheckBoxes. Or even FlowLayout. For example the following code uses the default JPanel's FlowLayout:
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.border.Border;
public class QueryBuilderUI extends javax.swing.JFrame {
protected static final int PREF_W = 400;
protected static final int PREF_H = 200;
QueryBuilderMethods objQBM = new QueryBuilderMethods();
DefaultComboBoxModel<String> repoModel = new DefaultComboBoxModel<String>();
public QueryBuilderUI() {
getRepositoryListing();
initComponents();
}
private void getRepositoryListing() {
repoModel = new QueryBuilderMethods().getAllRepositoryName();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel() {
#Override
// !! so the JPanel has some size. This is a shameless kludge *****
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
jTextField1 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Choose Repository");
jComboBox1.setModel(repoModel);
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox1ItemStateChanged(evt);
}
});
jLabel2.setText("Choose Table");
// jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
// "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox2ItemStateChanged(evt);
}
});
jLabel3.setText("Choose Columns");
// *************** Note Changes Below ****************
// !! javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
// !! jPanel1);
// !! jPanel1.setLayout(jPanel1Layout);
// !! jPanel1 now uses JPanel's default FlowLayout
Border border = BorderFactory.createTitledBorder("Select Columns");
jPanel1.setBorder(border);
jTextField1.setText("jTextField1");
jLabel4.setText("Generated Query");
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)
.addComponent(
jLabel1)
.addComponent(
jLabel2))
.addGap(57, 57, 57)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(
jComboBox1,
javax.swing.GroupLayout.PREFERRED_SIZE,
106,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(
jComboBox2,
javax.swing.GroupLayout.PREFERRED_SIZE,
106,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(
jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(
jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE,
412,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(65, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addGroup(
layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jComboBox1,
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(jLabel2)
.addComponent(jComboBox2,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(92, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if (evt.getStateChange() == ItemEvent.SELECTED) {
Object item = evt.getItem();
DefaultComboBoxModel<String> modelTable = objQBM
.getAllTablesForRepo(item.toString());
jComboBox2.setModel(modelTable);
}
}
private void jComboBox2ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if (evt.getStateChange() == ItemEvent.SELECTED) {
Object item = evt.getItem();
String RepoName = jComboBox1.getSelectedItem().toString();
List<String> columnNames = objQBM.getAllColumnsForTable(item
.toString());
addCheckBox(columnNames);
}
}
private void addCheckBox(List<String> columnNames) {
int numberCheckBox = columnNames.size();
JCheckBox[] checkBoxList = new JCheckBox[numberCheckBox];
System.out.println("numberCheckBox = " + numberCheckBox);
for (int i = 0; i < numberCheckBox; i++) {
checkBoxList[i] = new JCheckBox("hi" + i);
jPanel1.add(checkBoxList[i]);
}
jPanel1.revalidate();
jPanel1.repaint();
System.out.println("check boxes added");
}
public static void main(String args[]) {
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
new QueryBuilderUI().setVisible(true);
// }
// });
}
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
// mock code added so that the above code will compile and run
// because you didn't give us this code
class QueryBuilderMethods {
public DefaultComboBoxModel<String> getAllRepositoryName() {
DefaultComboBoxModel<String> cModel = new DefaultComboBoxModel<>();
for (String item : new String[] { "one", "two", "three", "four", "five" }) {
cModel.addElement(item);
}
return cModel;
}
public List<String> getAllColumnsForTable(String string) {
List<String> columns = new ArrayList<>();
for (String item : new String[] { "col 1", "col 2", "col 3", "col 4" }) {
columns.add(item);
}
return columns;
}
public DefaultComboBoxModel<String> getAllTablesForRepo(String string) {
DefaultComboBoxModel<String> cModel = new DefaultComboBoxModel<>();
for (String item : new String[] { "repo one", "repo two", "repo three",
"repo four", "repo five" }) {
cModel.addElement(item);
}
return cModel;
}
}
Related
This is what the textfield looks like before clicking the check button:
This is what happens after clicking check. This only happens with a string that is longer than the textfield.
This is the code from netbeans:
package filevalidator;
import java.awt.Color;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
/**
*
* #author Kosar
*/
public class Validator extends javax.swing.JFrame {
static String path1 = null;
static String path2 = null;
/**
* Creates new form Validator
*/
public Validator() {
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();
file1path = new javax.swing.JTextField();
select1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
file2path = new javax.swing.JTextField();
select2 = new javax.swing.JButton();
hash1 = new javax.swing.JLabel();
hash2 = new javax.swing.JLabel();
result = new javax.swing.JLabel();
checkBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel1.setText("Original File:");
file1path.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
file1path.setAutoscrolls(false);
select1.setText("Select");
select1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
select1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel2.setText("Second File:");
file2path.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
file2path.setAutoscrolls(false);
file2path.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
select2.setText("Select");
select2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
select2ActionPerformed(evt);
}
});
hash1.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
hash1.setForeground(java.awt.Color.blue);
hash1.setText(" ");
hash2.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
hash2.setForeground(java.awt.Color.blue);
hash2.setText(" ");
result.setFont(new java.awt.Font("Trebuchet MS", 1, 20)); // NOI18N
result.setText(" ");
checkBtn.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
checkBtn.setText("Check");
checkBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkBtnActionPerformed(evt);
}
});
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)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(32, 32, 32)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(result, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(151, 151, 151)
.addComponent(hash2, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE))
.addComponent(hash1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(30, 30, 30))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(file1path, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(file2path))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(select1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(checkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(331, 331, 331))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(59, 59, 59)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(file1path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select1))
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(file2path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(select2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(hash1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hash2)
.addGap(13, 13, 13)
.addComponent(result)
.addGap(5, 5, 5)
.addComponent(checkBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
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()
.addGap(27, 27, 27)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(34, 34, 34)
.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();
setLocationRelativeTo(null);
}// </editor-fold>
private void select1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select file");
if (chooser.showOpenDialog(select1) == JFileChooser.APPROVE_OPTION) {
path1 = chooser.getSelectedFile().getAbsolutePath();
}
file1path.setText(path1);
file1path.setBackground(Color.white);
}
private void select2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select file");
if (chooser.showOpenDialog(select2) == JFileChooser.APPROVE_OPTION) {
path2 = chooser.getSelectedFile().getAbsolutePath();
}
file2path.setText(path2);
file2path.setBackground(Color.white);
}
private void checkBtnActionPerformed(java.awt.event.ActionEvent evt) {
try {
HashMD5 hasher = new HashMD5();
try {
hash1.setText(hasher.hash(path1));
hash2.setText(hasher.hash(path2));
} catch (NoSuchAlgorithmException | IOException ex) {
}
if ( hash1.getText().equals(hash2.getText())) {
result.setForeground(Color.GREEN);
result.setText("Hashes are the same. File has not been modified.");
}
else {
result.setForeground(Color.RED);
result.setText("Hashes are not the same. File has been modified.");
}
} catch (NullPointerException e) {
if (file1path.getText() == null) {
file1path.setBackground(Color.red);
}
else if (file2path.getText() == null) {
file2path.setBackground(Color.red);
}
else {
file1path.setBackground(Color.red);
file2path.setBackground(Color.red);
}
}
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JButton checkBtn;
private javax.swing.JTextField file1path;
private javax.swing.JTextField file2path;
private javax.swing.JLabel hash1;
private javax.swing.JLabel hash2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel result;
private javax.swing.JButton select1;
private javax.swing.JButton select2;
// End of variables declaration
}
You can handle it by using TextField and its method to set columns i.e. "setColumns(int numOfCols)"
import java.awt.FlowLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class TextFieldExample extends JFrame {
JFrame frame = new JFrame();
public TextFieldExample()
{
frame = new JFrame("Test");
Container container = frame.getContentPane();
JTextField fld1 = new JTextField("Java C++ C");
JTextField fld2 = new JTextField("");
JTextField fld3 = new JTextField("");
fld1.setColumns(5); //Now, it will not be resized.
fld2.setColumns(7); //Now, it will not be resized.
fld3.setColumns(9); //Now, it will not be resized.
container.setLayout(new FlowLayout());
container.add(fld1);
container.add(fld2);
container.add(fld3);
frame.setVisible(true);
frame.setSize(150,150);
}
public static void main(String[] args) {
TextFieldExample obj = new TextFieldExample();
}
}
I want to add a photo from a chosen image File to a jPanel but, the following code doesn't seem to work :
private void browsePhotoButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
String[] fileSuffixes = ImageIO.getReaderFileSuffixes();
for(String fileSuffix:fileSuffixes){
FileFilter filter = new FileNameExtensionFilter(fileSuffix + " files", fileSuffix);
fileChooser.addChoosableFileFilter(filter);
}
int selection = fileChooser.showOpenDialog(EmployeeInternalFrame.this);
if(selection == JFileChooser.APPROVE_OPTION){
File fileBeingOpened = fileChooser.getSelectedFile();
setPhotoFile(fileBeingOpened);
setImageURL(getPhotoFile().getAbsolutePath());
photoPanel.removeAll();
Icon icon = new ImageIcon(getImageURL());
JLabel label = new JLabel(icon, SwingConstants.LEFT);
photoPanel.add(label);
photoPanel.repaint();
}
}
Which part am I missing ? Thank you for all of your help.
[EDIT]
This is the Class where the above code implemented :
/*
* 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 forms;
import dataobjects.Employee;
import datamodels.EmployeeTableModel;
import datacontrollers.EmployeeController;
import java.io.File;
import java.awt.Image;
import java.awt.Label;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.filechooser.FileFilter;
import javax.swing.SwingConstants;
import javax.swing.JFileChooser;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.Icon;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
/**
*
* #author Benignus
*/
public class EmployeeInternalFrame extends javax.swing.JInternalFrame{
private EmployeeTableModel employeeTableModel;
private String imageURL;
private EmployeeController employeeController;
private File photoFile;
private Image photoImage;
/**
* Creates new form EmployeeInternalFrame
*/
public EmployeeInternalFrame() {
initComponents();
employeeTableModel = new EmployeeTableModel();
employeeTable.setModel(employeeTableModel);
employeeController = new EmployeeController(this);
employeeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
#Override
public void valueChanged(ListSelectionEvent e) {
int row = employeeTable.getSelectedRow();
if(row != -1){
Employee employee = employeeTableModel.getAtIndex(row);
ssnText.setText(employee.getSsn());
nameText.setText(employee.getName());
positionComboBox.setSelectedItem(employee.getPosition());
basePayText.setText(String.valueOf(employee.getBasePay()));
banText.setText(employee.getBan());
imageURL = employee.getPhoto();
}
}
});
refreshTable();
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL){
this.imageURL = imageURL;
}
public EmployeeTableModel getEmployeeTableModel() {
return employeeTableModel;
}
public JButton getBackButton() {
return backButton;
}
public JTextField getBanText() {
return banText;
}
public JTextField getBasePayText() {
return basePayText;
}
public JButton getBrowsePhotoButton() {
return browsePhotoButton;
}
public JTable getEmployeeTable() {
return employeeTable;
}
public JButton getInputButton() {
return inputButton;
}
public JTextField getNameText() {
return nameText;
}
public JPanel getPhotoPanel() {
return photoPanel;
}
public JComboBox getPositionComboBox() {
return positionComboBox;
}
public JComboBox getSearchByComboBox() {
return searchByComboBox;
}
public JTextField getSearchText() {
return searchText;
}
public JTextField getSsnText() {
return ssnText;
}
private void refreshTable(){
employeeController.selectAll();
}
public File getPhotoFile() {
return photoFile;
}
public void setPhotoFile(File photoFile) {
this.photoFile = photoFile;
}
public Image getPhotoImage() {
return photoImage;
}
public void setPhotoImage(Image photoImage) {
this.photoImage = photoImage;
}
/**
* 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() {
photoPanel = new javax.swing.JPanel();
browsePhotoButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
employeeTable = new javax.swing.JTable();
positionComboBox = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
ssnText = new javax.swing.JTextField();
nameText = new javax.swing.JTextField();
inputButton = new javax.swing.JButton();
backButton = new javax.swing.JButton();
basePayText = new javax.swing.JTextField();
banText = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
searchText = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
searchByComboBox = new javax.swing.JComboBox();
photoPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout photoPanelLayout = new javax.swing.GroupLayout(photoPanel);
photoPanel.setLayout(photoPanelLayout);
photoPanelLayout.setHorizontalGroup(
photoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 111, Short.MAX_VALUE)
);
photoPanelLayout.setVerticalGroup(
photoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 149, Short.MAX_VALUE)
);
browsePhotoButton.setText("Browse Photo");
browsePhotoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browsePhotoButtonActionPerformed(evt);
}
});
employeeTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(employeeTable);
positionComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel1.setText("SSN");
jLabel2.setText("Name");
jLabel3.setText("Position");
jLabel4.setText("Base Pay");
inputButton.setText("Input");
inputButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
inputButtonActionPerformed(evt);
}
});
backButton.setText("Back");
jLabel5.setText("BAN");
jLabel7.setText("Search By :");
searchByComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
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()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(banText, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel4))
.addGap(6, 6, 6))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(basePayText)
.addComponent(ssnText, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
.addComponent(nameText, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
.addComponent(positionComboBox, 0, 170, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(photoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(browsePhotoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(inputButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(5, 5, 5)
.addComponent(searchByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, 150, 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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(photoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(9, 9, 9)
.addComponent(browsePhotoButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(26, 26, 26)
.addComponent(jLabel2)
.addGap(63, 63, 63)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(basePayText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(ssnText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addComponent(nameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(positionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(banText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(17, 17, 17)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(inputButton)
.addComponent(backButton))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(searchByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(15, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void browsePhotoButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
String[] fileSuffixes = ImageIO.getReaderFileSuffixes();
for(String fileSuffix:fileSuffixes){
FileFilter filter = new FileNameExtensionFilter(fileSuffix + " files", fileSuffix);
fileChooser.addChoosableFileFilter(filter);
}
int selection = fileChooser.showOpenDialog(EmployeeInternalFrame.this);
if(selection == JFileChooser.APPROVE_OPTION){
File fileBeingOpened = fileChooser.getSelectedFile();
setPhotoFile(fileBeingOpened);
setImageURL(getPhotoFile().getAbsolutePath());
photoPanel.removeAll();
Icon icon = new ImageIcon(getImageURL());
JLabel label = new JLabel(icon, SwingConstants.LEFT);
photoPanel.add(label);
photoPanel.repaint();
JOptionPane.showMessageDialog(this, getImageURL());
}
}
private void inputButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(inputButton.getText().equalsIgnoreCase("Input")){
}
else if(inputButton.getText().equalsIgnoreCase("Save")){
}
else if(inputButton.getText().equalsIgnoreCase("Update")){
}
}
// Variables declaration - do not modify
private javax.swing.JButton backButton;
private javax.swing.JTextField banText;
private javax.swing.JTextField basePayText;
private javax.swing.JButton browsePhotoButton;
private javax.swing.JTable employeeTable;
private javax.swing.JButton inputButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField nameText;
private javax.swing.JPanel photoPanel;
private javax.swing.JComboBox positionComboBox;
private javax.swing.JComboBox searchByComboBox;
private javax.swing.JTextField searchText;
private javax.swing.JTextField ssnText;
// End of variables declaration
}
The documentation of ImageIcon(String filename) states that:
Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify:
new ImageIcon("images/myImage.gif")
The description is initialized to the filename string.
So, what I think your problem is with the path that you have given as parameters which has \ in the path.
I "think" the problem is with the use of GroupLayout, it's generally a
pain in the ... Code ... Personally, I'd use a different layout, even
with the form editor and add a place holder label for the phot, which
you can use to set the icon – MadProgrammer yesterday
I changed the panel's layout into Card Layout, and it's fine now, thank you everyone :)
I am trying to build a java project using Netbeans IDE 7.1.
I somehow can't see or view the GUI window that I have created.
Please kindly advise.
In my class:
package rmiSimpleCalc;
public class RMISimpleCalculatorMain {
public static void main(String[] args) {
MainCalculator calc = new MainCalculator();
calc.setVisible(true);
}
}
the MainCalculator is the GUI window I would like to run. It somehow wont't display.
There is NO error message in my console tough..
Here is the MainCalculator code:
package rmiSimpleCalc;
import java.rmi.*;
public class MainCalculator extends javax.swing.JPanel {
public MainCalculator() {
initComponents();
ComboBoxOperator.addItem("+");
ComboBoxOperator.addItem("-");
ComboBoxOperator.addItem("/");
ComboBoxOperator.addItem("*");
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
txtFirstDigit = new javax.swing.JTextField();
txtSecondDigit = new javax.swing.JTextField();
btnCalculate = new javax.swing.JButton();
lblFirstDigit = new javax.swing.JLabel();
lblSecondDigit = new javax.swing.JLabel();
ComboBoxOperator = new javax.swing.JComboBox();
lblOperator = new javax.swing.JLabel();
lblResult = new javax.swing.JLabel();
lblHeader = new javax.swing.JLabel();
btnConfigureServer = new javax.swing.JButton();
txtResult = new javax.swing.JTextField();
btnCalculate.setText("Calculate");
btnCalculate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCalculateActionPerformed(evt);
}
});
lblFirstDigit.setText("First Digit");
lblSecondDigit.setText("Second Digit");
ComboBoxOperator.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
lblOperator.setText("Operator");
lblResult.setText("Result");
lblHeader.setText("RMI Simple Calculator");
btnConfigureServer.setText("Configure Server");
btnConfigureServer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConfigureServerActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.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)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblFirstDigit, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblSecondDigit, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblOperator, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblResult, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblHeader)
.addGroup(layout.createSequentialGroup()
.addComponent(ComboBoxOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnCalculate))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtSecondDigit)
.addComponent(txtFirstDigit, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(txtResult, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnConfigureServer)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(lblHeader)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtFirstDigit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblFirstDigit))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtSecondDigit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblSecondDigit))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ComboBoxOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblOperator)
.addComponent(btnCalculate))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblResult)
.addComponent(txtResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnConfigureServer)
.addContainerGap(24, Short.MAX_VALUE))
);
}
private void btnConfigureServerActionPerformed(java.awt.event.ActionEvent evt) {
}
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
double firstdigit;
double seconddigit;
String operator;
firstdigit = Double.valueOf(txtFirstDigit.getText());
seconddigit = Double.valueOf(txtSecondDigit.getText());
operator = ComboBoxOperator.getSelectedItem().toString();
try
{
CoreInterface coreobj = (CoreInterface) Naming.lookup("localhost/Core");
double result = (coreobj.calc(firstdigit,seconddigit,operator));
txtResult.setText(Double.toString(result));
}
catch(Exception e)
{
txtResult.setText("e");
}
}
private javax.swing.JComboBox ComboBoxOperator;
private javax.swing.JButton btnCalculate;
private javax.swing.JButton btnConfigureServer;
private javax.swing.JLabel lblFirstDigit;
private javax.swing.JLabel lblHeader;
private javax.swing.JLabel lblOperator;
private javax.swing.JLabel lblResult;
private javax.swing.JLabel lblSecondDigit;
private javax.swing.JTextField txtFirstDigit;
private javax.swing.JTextField txtResult;
private javax.swing.JTextField txtSecondDigit;
// End of variables declaration
}
Any advise is appreciated.
The MainCalculator class is a JPanel. A JPanel can't just be displayed like that, it has to be part of a Window. Add it to a JFrame and call setVisible(true) on the JFrame.
Also, #npinti's advice is very good: execute GUI-related code in the EDT thread.
The issue is most likely in this section:
public static void main(String[] args) {
MainCalculator calc = new MainCalculator();
calc.setVisible(true);
}
You need to make any GUI related tasks within the Event Dispatcher Thread (EDT).
Try something like so:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
MainCalculator calc = new MainCalculator();
calc.setVisible(true);
}
});
}
EDIT:
Of course I find an answer 2 min after I post a question.
How to completely remove an icon from JDialog?
But follow-up; anyone knows the way to make consistent icon state when changing resizable property?
PS. I can't answer my own question for 8 more hours.
ORIGINAL QUESTION:
To put it short, here is an stripped down example code which has a problem.
When I click on "Details" (WinXP x32 java 1.6) jPanel2 changes visibility state and together with jPanel2 for some reason the dialog icon is removed. Quite curious.
Anyone knows why the icon is hidden together with JPanel?
Code is generated by NetBeans 7.1, only slightly adapted to be self-contained.
Thanks in advance for help!
import java.awt.Frame;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class TestHide extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
public TestHide(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
jPanel2.setVisible(false);
pack();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblIcon = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
taShortMsg = new javax.swing.JTextArea();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jSeparator2 = new javax.swing.JSeparator();
jPanel4 = new javax.swing.JPanel();
jSeparator3 = new javax.swing.JSeparator();
jScrollPane2 = new javax.swing.JScrollPane();
taDetails = new javax.swing.JTextArea();
btnOk = new javax.swing.JButton();
btnTgDetails = new javax.swing.JToggleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
lblIcon.setText(""); // NOI18N
jScrollPane1.setBorder(null);
taShortMsg.setBackground(getBackground());
taShortMsg.setColumns(20);
taShortMsg.setEditable(false);
taShortMsg.setFont(lblIcon.getFont());
taShortMsg.setLineWrap(true);
taShortMsg.setRows(5);
taShortMsg.setBorder(null);
taShortMsg.setCursor(getCursor());
taShortMsg.setOpaque(false);
jScrollPane1.setViewportView(taShortMsg);
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().addComponent(lblIcon).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE).addContainerGap()));
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
jPanel1Layout
.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup().addComponent(lblIcon).addContainerGap(54, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING))));
jPanel2.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentHidden(java.awt.event.ComponentEvent evt) {
jPanel2ComponentHidden(evt);
}
public void componentShown(java.awt.event.ComponentEvent evt) {
jPanel2ComponentShown(evt);
}
});
jLabel3.setText("jLabel3"); // NOI18N
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
jPanel3Layout.createSequentialGroup().addContainerGap().addComponent(jSeparator1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jSeparator2).addContainerGap()));
jPanel3Layout
.setVerticalGroup(jPanel3Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
jPanel3Layout
.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(
jPanel3Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 10,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 10,
javax.swing.GroupLayout.PREFERRED_SIZE))).addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE));
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
jPanel4Layout.createSequentialGroup().addContainerGap().addComponent(jSeparator3).addContainerGap()));
jPanel4Layout.setVerticalGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel4Layout.createSequentialGroup().addContainerGap().addComponent(jSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE)));
jScrollPane2.setBorder(null);
taDetails.setColumns(20);
taDetails.setEditable(false);
taDetails.setFont(lblIcon.getFont());
taDetails.setRows(5);
jScrollPane2.setViewportView(taDetails);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addComponent(jScrollPane2).addContainerGap())
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
jPanel2Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE)));
btnOk.setText("OK"); // NOI18N
btnOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOkActionPerformed(evt);
}
});
btnTgDetails.setText("Details"); // NOI18N
btnTgDetails.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTgDetailsActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(
layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE).addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnTgDetails, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap())
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
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)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(btnTgDetails)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(btnOk).addContainerGap()))));
pack();
}
private void btnTgDetailsActionPerformed(java.awt.event.ActionEvent evt) {
if (jPanel2.isVisible()) {
btnTgDetails.setText("Details>>");
} else {
btnTgDetails.setText("Details<<");
}
jPanel2.setVisible(!jPanel2.isVisible());
this.validate();
this.pack();
}
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
}
private void jPanel2ComponentHidden(java.awt.event.ComponentEvent evt) {
setResizable(false);
}
private void jPanel2ComponentShown(java.awt.event.ComponentEvent evt) {
setResizable(true);
}
public static void main(String args[]) {
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(TestHide.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestHide.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestHide.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestHide.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
showMessageDialog(null, "I am title", "Small message...", "long\n\nlong\nmessage", JOptionPane.INFORMATION_MESSAGE);
}
public static void showMessageDialog(Frame parent, String title, String shortMessage, String longMessage, int type) {
TestHide md = new TestHide(parent, true);
Icon icon = null;
switch (type) {
case JOptionPane.ERROR_MESSAGE:
icon = UIManager.getIcon("OptionPane.errorIcon");
break;
case JOptionPane.INFORMATION_MESSAGE:
icon = UIManager.getIcon("OptionPane.informationIcon");
break;
case JOptionPane.WARNING_MESSAGE:
icon = UIManager.getIcon("OptionPane.warningIcon");
break;
}
md.setTitle(title);
md.lblIcon.setIcon(icon);
md.taShortMsg.setText(shortMessage);
if (longMessage == null) {
md.btnTgDetails.setVisible(false);
} else {
md.taDetails.setText(longMessage);
md.taDetails.setCaretPosition(0);
}
md.pack();
md.setVisible(true);
}
private javax.swing.JButton btnOk;
private javax.swing.JToggleButton btnTgDetails;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JLabel lblIcon;
private javax.swing.JTextArea taDetails;
private javax.swing.JTextArea taShortMsg;
}
If you put the following statement in a constructor like
public TestHide(java.awt.Frame parent, boolean modal) {
super(parent, modal);
setIconImage(Toolkit.getDefaultToolkit().getImage("images\\white_title.png"));
initComponents();
jPanel2.setVisible(false);
pack(); }
then the icon on title bar appear constantly.
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.