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 :)
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 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;
}
}
I'm working on an assignment using Binary IO and Event Handling. It looks like this, I think I have most of the basic code down, and now its down to the hard stuff. How can I read text from my .bin file into the seperate text fields?
My fields currently are blank, but when read in they should look something like that and I should be able to parse through seperate sets of information with my two buttons on the bottom.
Here is what I have so far.
I have a RecordViewerUI JFrame form, a RecordViewerPanel JFrame panel, and a SalesAgent java class which holds all of my getters and setters/ constructor for my four variables.
Here is my panel. Sorry for the generated code.
Thanks in advance for any help anyone can offer.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RecordViewerPanel extends javax.swing.JPanel {
String filename = "sales.bin";
ArrayList<SalesAgent> customer = new ArrayList<>();
int curIndex = 0;
/**
* Creates new form RecordViewerPanel
*/
public RecordViewerPanel() throws IOException, ClassNotFoundException {
initComponents();
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(filename)));
ArrayList<SalesAgent> salesForce = new ArrayList<SalesAgent>();
String first = in.readUTF();
String last = in.readUTF();
double sales = in.readDouble();
Date date = (Date) (in.readObject());
} catch (FileNotFoundException ex) {
Logger.getLogger(RecordViewerPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void refreshUI() {
SalesAgent sale = (customer.get(curIndex));
firstTextField.setText(sale.getFirst());
lastTextField.setText(sale.getLast());
salesTextField.setText("$" + String.valueOf(sale.getSales()));
dateTextField.setText(String.valueOf(sale.getDate()));
recordPanel.repaint();
}
/**
* 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() {
filePanel = new javax.swing.JPanel();
fileLabel = new javax.swing.JLabel();
fileLabel1 = new javax.swing.JLabel();
recordPanel = new javax.swing.JPanel();
firstTextField = new javax.swing.JTextField();
lastTextField = new javax.swing.JTextField();
salesTextField = new javax.swing.JTextField();
dateTextField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
previousButton = new javax.swing.JButton();
nextButton = new javax.swing.JButton();
filePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
fileLabel.setBackground(new java.awt.Color(204, 204, 204));
fileLabel.setText("sales.bin");
fileLabel1.setBackground(new java.awt.Color(204, 204, 204));
fileLabel1.setText("Current file:");
javax.swing.GroupLayout filePanelLayout = new javax.swing.GroupLayout(filePanel);
filePanel.setLayout(filePanelLayout);
filePanelLayout.setHorizontalGroup(
filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(fileLabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(fileLabel1)
.addContainerGap(562, Short.MAX_VALUE)))
);
filePanelLayout.setVerticalGroup(
filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(fileLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
.addContainerGap())
.addGroup(filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(fileLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
.addContainerGap()))
);
recordPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
firstTextField.setText("jTextField1");
lastTextField.setText("jTextField1");
salesTextField.setText("jTextField1");
dateTextField.setText("jTextField1");
jLabel1.setText("First Last Sales Date");
previousButton.setText("<<");
previousButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousButtonActionPerformed(evt);
}
});
nextButton.setText(">>");
nextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout recordPanelLayout = new javax.swing.GroupLayout(recordPanel);
recordPanel.setLayout(recordPanelLayout);
recordPanelLayout.setHorizontalGroup(
recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(recordPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(recordPanelLayout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 203, Short.MAX_VALUE))
.addGroup(recordPanelLayout.createSequentialGroup()
.addComponent(firstTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(lastTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(salesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(dateTextField)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, recordPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(previousButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31))
);
recordPanelLayout.setVerticalGroup(
recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(recordPanelLayout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(firstTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lastTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(salesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(dateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
.addGroup(recordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(previousButton)
.addComponent(nextButton))
.addGap(27, 27, 27))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(filePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(recordPanel, 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(filePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(recordPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>
private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (curIndex > 0) {
curIndex--;
} else if (curIndex == 0) {
curIndex = 4;
}
customer.get(curIndex);
}
private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (curIndex < 4) {
curIndex++;
} else if (curIndex == 4) {
curIndex = 0;
}
customer.get(curIndex);
}
// Variables declaration - do not modify
private javax.swing.JTextField dateTextField;
private javax.swing.JLabel fileLabel;
private javax.swing.JLabel fileLabel1;
private javax.swing.JPanel filePanel;
private javax.swing.JTextField firstTextField;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField lastTextField;
private javax.swing.JButton nextButton;
private javax.swing.JButton previousButton;
private javax.swing.JPanel recordPanel;
private javax.swing.JTextField salesTextField;
// End of variables declaration
}
This is rather difficult to answer, as I have no understanding of the file format or the Customer class, but basically, you need to create a new Customer from the values you've read from the file, add it to the customer List and call refreshUI
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(filename)));
String first = in.readUTF();
String last = in.readUTF();
double sales = in.readDouble();
Date date = (Date) (in.readObject());
Customer cust = ...;
customer.add(cust);
} catch (FileNotFoundException ex) {
Logger.getLogger(RecordViewerPanel.class.getName()).log(Level.SEVERE, null, ex);
}
refreshUI();
I'm having trouble with my code. the logic of my code is, when it doesn't find the username I entered a confirmation box will appear, what really happen is when a entered username is found in a line
it doesn't launched the confirmation box "that's alright" but it continue searching throughout every line and initialize else {statement} btw, my else statement is the confirmation box.
a sample data.dat that my code writes
shawn | qwerty1234
cloe | password1234
jones | shittybrix
When I entered "shawn" it launches my if statement "that's alright"
but it continues searching throughout the string and the entered Username "shawn" became not equal to cloe and jones, it launches the else statement giving me two confirmation box respectively.
I want to avoid that error but I don't know how.
THE ERROR OCCURS IN REGISTER.JAVA
this is my code for login:
package login;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JOptionPane;
public class Login extends javax.swing.JFrame {
public Login() {
initComponents0();
}
#SuppressWarnings("unchecked")
private void initComponents0() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
uname = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
login = new javax.swing.JButton();
reset = new javax.swing.JButton();
pwd = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("Login Pane");
jLabel2.setText("User Name:");
jLabel3.setText("Password:");
login.setText("Login");
login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String un = uname.getText();
try {
try (BufferedReader br = new BufferedReader(new Filereader("data.dat"))) {
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.startsWith(un)) {
JOptionPane.showMessageDialog(null, "Hello: " + un, "Registration", JOptionPane.INFORMATION_MESSAGE);
} else {
int sel = JOptionPane.showConfirmDialog(null, "It seems that you haven't registered yet? \n Lunch Registration Pane?", "Admin", JOptionPane.INFORMATION_MESSAGE);
if (sel == JOptionPane.YES_OPTION) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Register().setVisible(true);
}
});
}
}
}
}
} catch (IOException | HeadlessException ez) {
JOptionPane.showMessageDialog(null, "A null file was created in order to \n avoid File Catch errors", "Admin", JOptionPane.INFORMATION_MESSAGE);
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file, true)) {
String data0 = "null";
String data1 = "null";
writer.write(data0 + " | " + data1 + "\n");
}
} catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
}
});
reset.setText("Reset Field");
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(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(uname, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(reset, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(pwd))))
.addContainerGap(30, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(uname, 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(jLabel3)
.addComponent(pwd, 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(login)
.addComponent(reset))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton login;
private javax.swing.JPasswordField pwd;
private javax.swing.JButton reset;
private javax.swing.JTextField uname;
// End of variables declaration
}
this it the registration code it launches when I clicked yes in the confirmation box
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package login;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
*
* #author Jfetizanan
*/
class Register extends javax.swing.JFrame {
/**
* Creates new form GUIREG
*/
public Register() {
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")
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
unamereg = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
pwdreg = new javax.swing.JTextField();
submit = new javax.swing.JButton();
resetreg = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("Registration Pane");
jLabel2.setText("User Name:");
jLabel3.setText("Password:");
submit.setText("Submit");
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Runned");
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file, true)) {
String data0 = unamereg.getText();
String data1 = pwdreg.getText();
writer.write(data0 + " | " + data1 + "\n");
}
JOptionPane.showMessageDialog(null, "Registered", "Registration", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
});
resetreg.setText("Reset Field");
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(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(unamereg))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pwdreg)
.addGroup(layout.createSequentialGroup()
.addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(resetreg, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap(42, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(unamereg, 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(jLabel3)
.addComponent(pwdreg, 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(submit)
.addComponent(resetreg))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField pwdreg;
private javax.swing.JButton resetreg;
private javax.swing.JButton submit;
private javax.swing.JTextField unamereg;
// End of variables declaration
}
Managed to find the issue through that big mess. In your if statement that pops up saying hello 'blah', you need to make it break out of the while loop, and move the else statement. Copy whats in the else statement just out of the while loop (just because it doesnt match the first guy, doesnt mean that it wont match a later one, so dont yell at them til the end). so have it like this:
BufferedReader br = new BufferedReader(
new InputStreamReader(fstream));
String strLine;
boolean registered = false;
while ((strLine = br.readLine()) != null) {
if (strLine.startsWith(un)) {
registered = true;
break;
}
}
if(registered) {
//blah
} else {
//blah
}
Also, you should change Lunch registration to Launch registration ;)
In response to your comment, it's due to this line:
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
You have that in both of your frames, it says to stop the JVM as soon as you close it. You want this for your login frame (if they close the login window, stop the program), but not for the registration window. For that, you just want javax.swing.WindowConstants.DISPOSE_ON_CLOSE, which says it will dispose of the frame upon closing it (good cleanup). If all frames are disposed, the JVM will end (assuming no other threads are running that is), so as long as Login stays open, it shouldn't exit.
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);
}
});
}