trouble with creating JTable to display data [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am doing this payroll project for school.
The idea is for the user to input the employee's name, work hour, hourly rate, and select department from the ComboBox.
There will display 3 buttons, "Add More", "Display Result", and "exit".
"Add More" button will store the input into several arryalist and set the textfield to blank to allow more input.
"Display Result" will generate a JTable at the bottom JPanel to display the employee's name, department, and weekly salary.
I am running into the problem of nothing shows up after hitting the "Display Result" button. Maybe I have misunderstand the purpose of the button event, but I am really confused right now. Please help!
Here is a photobucket directURL PrtSc of the UI, hope it helps.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class PayrollFrame extends JFrame
{
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame()
{
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setLayout(new GridLayout(3,1));
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel);
add(buttonPanel);
add(outputPanel);
setVisible(true);
}
private void buildInputPanel()
{
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel()
{
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel()
{
outputPanel = new JPanel();
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][2]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="Add More")
{
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
}
else if(e.getActionCommand()=="Display Result")
{
printData();
}
else if(e.getActionCommand()=="Exit")
{
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString)
{
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if(tempHour<=40)
{
salary.add(Double.toString(tempHour * tempRate));
}
else
{
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}

Let's start with...
if (e.getActionCommand() == "Add More") {
Is not how you compare Strings in Java, you need to use the equals method instead, something like...
if ("Add More".equals(e.getActionCommand())) {
for example
Next you do...
add(inputPanel);
add(buttonPanel);
add(outputPanel);
which, when using a BorderLayout, adds each of the components to the default position within the BorderLayout, you need to provide position constraints for each component, otherwise strange things begin to happen, for example...
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
add(outputPanel, BorderLayout.SOUTH);
I just realised that you're using a GridLayout, personally, I think you'll get a better result from BorderLayout, but that's me
And then you create a new instance of resultTable and outputPanel, but you never add outputPanel to anything...
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData()
{
for(int i=0; i<name.size(); i++)
{
data[i][0]=name.get(i);
data[i][1]=department.get(i);
data[i][2]=salary.get(i);
}
resultTable = new JTable(data, columnNames);
outputPanel = new JPanel();
outputPanel.add(resultTable);
}
A better idea would be to create resultTable, wrap in a JScrollPane and add it to your screen.
When you want to "print" the data, create a new TableModel and apply it to the JTable
For example...
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
Take a look at How to Use Tables and How to Use Scroll Panes for more details
Example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class PayrollFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
PayrollFrame frame = new PayrollFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private JLabel nameMessageLabel, hourMessageLabel, rateMessageLabel, boxMessageLabel;
private JTextField nameTextField, hourTextField, rateTextField;
private JPanel inputPanel, buttonPanel, outputPanel, inputPanel1, inputPanel2, inputPanel3, inputPanel4;
private JComboBox<String> departmentBox;
private JButton addButton, displayButton, exitButton;
private JTable resultTable;
private String[] columnNames = {"Employee name", "Department", "Weekly Salary"};
private Object[][] data;
private int WINDOW_WIDTH = 400;
private int WINDOW_HEIGHT = 500;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> hour = new ArrayList<String>();
ArrayList<String> rate = new ArrayList<String>();
ArrayList<String> department = new ArrayList<String>();
ArrayList<String> salary = new ArrayList<String>();
private String[] departments = {"IT", "Marketing", "Human Resource", "Sales", "Customer Service", "Financial"};
/*default constructor*/
public PayrollFrame() {
super("Payroll");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildInputPanel();
buildButtonPanel();
buildOutputPanel();
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel);
add(outputPanel, BorderLayout.SOUTH);
setVisible(true);
}
private void buildInputPanel() {
nameMessageLabel = new JLabel("Employee Name: ");
hourMessageLabel = new JLabel("Work Hour: ");
rateMessageLabel = new JLabel("Hourly Rate: ");
boxMessageLabel = new JLabel("Department: ");
nameTextField = new JTextField(10);
hourTextField = new JTextField(10);
rateTextField = new JTextField(10);
departmentBox = new JComboBox<String>(departments);
inputPanel = new JPanel();
inputPanel1 = new JPanel();
inputPanel2 = new JPanel();
inputPanel3 = new JPanel();
inputPanel4 = new JPanel();
inputPanel1.add(nameMessageLabel);
inputPanel1.add(nameTextField);
inputPanel2.add(hourMessageLabel);
inputPanel2.add(hourTextField);
inputPanel3.add(rateMessageLabel);
inputPanel3.add(rateTextField);
inputPanel4.add(boxMessageLabel);
inputPanel4.add(departmentBox);
inputPanel.add(inputPanel1);
inputPanel.add(inputPanel2);
inputPanel.add(inputPanel3);
inputPanel.add(inputPanel4);
}
private void buildButtonPanel() {
addButton = new JButton("Add More");
addButton.addActionListener(new ButtonAction());
displayButton = new JButton("Display Result");
displayButton.addActionListener(new ButtonAction());
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonAction());
buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
buttonPanel.add(exitButton);
}
private void buildOutputPanel() {
outputPanel = new JPanel(new BorderLayout());
resultTable = new JTable();
outputPanel.add(new JScrollPane(resultTable));
}
/*Copy ArrayList into 2D array to display in JTable format*/
private void printData() {
for (int i = 0; i < name.size(); i++) {
data[i][0] = name.get(i);
data[i][2] = department.get(i);
data[i][2] = salary.get(i);
}
TableModel model = new DefaultTableModel(data, columnNames);
resultTable.setModel(model);
}
/*Function of 3 buttons*/
private class ButtonAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if ("Add More".equals(e.getActionCommand())) {
name.add(nameTextField.getText());
hour.add(hourTextField.getText());
rate.add(rateTextField.getText());
department.add((String) departmentBox.getSelectedItem());
calculateSalary(hourTextField.getText(), rateTextField.getText());
nameTextField.setText("");
hourTextField.setText("");
rateTextField.setText("");
} else if ("Display Result".equals(e.getActionCommand())) {
printData();
} else if ("Exit".equals(e.getActionCommand())) {
System.exit(0);
}
}
/*Calculate the weekly salary*/
private void calculateSalary(String hourString, String rateString) {
int tempHour = Integer.parseInt(hourString);
double tempRate = Double.parseDouble(rateString);
if (tempHour <= 40) {
salary.add(Double.toString(tempHour * tempRate));
} else {
salary.add(Double.toString(40 * tempRate + (tempHour - 40) * (tempRate * 1.5))); //all hour after 40 will pay 1.5
}
}
}
}

Thanks for #MadProgrammer 's help! His reply helps me to fix many problems I have, and really tried to explain things to me. After consulting with my instructor, I have successfully compile and run my program by editing the printData method.
private void printData()
{
DefaultTableModel model = new DefaultTableModel(columnNames,name.size());
resultTable.setModel(model);
for(int i=0; i<name.size(); i++)
{
resultTable.setValueAt(name.get(i),i,0);
resultTable.setValueAt(department.get(i),i,1);
resultTable.setValueAt(salary.get(i),i,2);
}
}

Related

miglayout with jtable with issue

I have used miglayout in swing applicaion.I have encounted one issue like jtable cant appear in whole frame it show only left side some area.
i want to show untill at right side end of jframe edge
My implemantaion code is below
package test;
import java.awt.EventQueue;
import java.util.Arrays;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
public class ProductPanel2 extends JPanel {
private JLabel lblProd;
private JButton butAdd;
private JButton butRemove;
private JButton butEdit;
private JScrollPane scroll;
private JTable table;
private static final long serialVersionUID = 1L;
public JList<String> lst_Options;
private JScrollPane scr_Data;
private JComboBox<ComboItem> cmb_Suppliers;
//Generar de inmediato
private JButton btn_NewUpdate;
private JButton btn_Delete;
private JButton btn_Copy;
private JTable tbl_Settings;
private JLabel lbl_SelectedOption;
DefaultListModel<String> modeloOpciones;
public ProductPanel2() {
initComponents();
}
private void initComponents() {
lblProd = new JLabel("Product List: ");
btn_NewUpdate = new JButton("Add");
btn_Delete = new JButton("Remove");
lbl_SelectedOption = new JLabel("Tipo de datos");
JLabel lbl_Opciones = new JLabel("Opciones");
lst_Options = new JList<String>();
modeloOpciones = new DefaultListModel<String>();
btn_Delete = new JButton("Eliminar");
btn_NewUpdate = new JButton("Nuevo");
scr_Data = new JScrollPane();
cmb_Suppliers = new JComboBox<ComboItem>();
modeloOpciones.addElement("Proveedores");
modeloOpciones.addElement("Productos");
modeloOpciones.addElement("Partidas");
lst_Options.setModel(modeloOpciones);
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
JPanel filterPanel=new JPanel();
setLayout(new MigLayout("debug", "[96px][][94.00][grow][149.00px][2px][161px]", "[16px][240px,grow][12px][29px]"));
//add(lbl_SelectedOption, "cell 1 0,alignx left,sgx");
add(lst_Options, "cell 0 1 1 5,grow");
filterPanel.add(scr_Data,"wrap, sg buttons");
// filterPanel.add(cmb_Suppliers, "");
add(filterPanel,"span 2 3, grow, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);
add(lbl_Opciones, "cell 0 0,growx,aligny top");
add(btn_Delete, "cell 6 3,alignx right,aligny bottom");
add(btn_NewUpdate, "cell 4 3,alignx right,aligny bottom");
refreshCombo(cmb_Suppliers);
}
private void refreshCombo(JComboBox<ComboItem> combo) {
combo.removeAllItems();
try {
combo.addItem(new ComboItem("0","ashjish"));
combo.addItem(new ComboItem("2","ashjish"));
combo.addItem(new ComboItem("3","ashjish"));
} catch (Exception e) {
//log.logToFile("refreshCombo: " + e.getClass().getName() + ": " + e.getMessage(), 1);
e.printStackTrace();
}
}
private JTable createTable() {
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
int rows = 30;
int cols = columnNames.length;
String[][] data = new String[rows][cols];
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
data[i][j] = "R"+i+" C"+j;
}
}
JTable table = new JTable(data, columnNames);
return table;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
ProductPanel2 pane = new ProductPanel2();
frame.setContentPane(pane);
frame.setSize(1000,1000);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
i dont want space betweeb combo and jtable whuich in mention at screenshot
package test;
import java.awt.EventQueue;
import java.util.Arrays;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
public class ProductPanel2 extends JPanel {
private JLabel lblProd;
private JButton butAdd;
private JButton butRemove;
private JButton butEdit;
private JScrollPane scroll;
private JTable table;
private static final long serialVersionUID = 1L;
public JList<String> lst_Options;
private JScrollPane scr_Data;
private JComboBox<ComboItem> cmb_Suppliers;
//Generar de inmediato
private JButton btn_NewUpdate;
private JButton btn_Delete;
private JButton btn_Copy;
private JTable tbl_Settings;
private JLabel lbl_SelectedOption;
private JPanel filterPanel;
private JLabel lbl_cmb_supplier;
private JButton btn_search;
public ProductPanel2() {
initComponents();
}
private void initComponents() {
lblProd = new JLabel("Product List: ");
lbl_cmb_supplier = new JLabel("Proveedor");
btn_NewUpdate = new JButton("Add");
btn_Delete = new JButton("Remove");
lbl_SelectedOption = new JLabel("Tipo de datos");
JLabel lbl_Opciones = new JLabel("Opciones");
cmb_Suppliers = new JComboBox<ComboItem>();
btn_Delete = new JButton("Eliminar");
btn_search = new JButton("Search");
btn_NewUpdate = new JButton("Nuevo");
scr_Data = new JScrollPane();
JComboBox<String> cmb_Suppliers = new JComboBox<String>();
JButton btn_New = new JButton("Nuevo");
JButton btn_Delete = new JButton("Cancelar");
JButton btn_PDF = new JButton("Crea PDF");
JButton btn_Send = new JButton("Envia por correo");
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
tbl_Settings.setPreferredScrollableViewportSize(tbl_Settings.getPreferredSize());
filterPanel = new JPanel();
/*setLayout(new MigLayout("","[right]"));
add(lbl_Opciones, "growx,aligny, top, wrap");
filterPanel.add(lbl_cmb_supplier, "split 2, wrap");
filterPanel.add(cmb_Suppliers, "wrap");
filterPanel.add(btn_search, "grow, spany, wrap");
add(filterPanel, "growx 5,split 2, flowy, top, sgx");
add(scr_Data, "width 100%, growx, push, span, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);*/
setLayout(new MigLayout("debug", "[122px][129px][23px][45px][148px,grow]", "[][100px,grow][]"));
add(lbl_Opciones, "growx, wrap");
filterPanel.add(lbl_cmb_supplier);
filterPanel.add(cmb_Suppliers);
filterPanel.add(btn_search, "grow, spany, wrap");
add(filterPanel, "wrap");
add(scr_Data, "width 100%, growx, push, span, wrap");
add(btn_New);
add(btn_PDF);
add(btn_Send);
add(btn_Delete);
refreshCombo(cmb_Suppliers);
}
private void refreshCombo(JComboBox<String> combo) {
combo.removeAllItems();
try {
} catch (Exception e) {
//log.logToFile("refreshCombo: " + e.getClass().getName() + ": " + e.getMessage(), 1);
e.printStackTrace();
}
}
private JTable createTable() {
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
int rows = 30;
int cols = columnNames.length;
String[][] data = new String[rows][cols];
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
data[i][j] = "R"+i+" C"+j;
}
}
JTable table = new JTable(data, columnNames);
return table;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
ProductPanel2 pane = new ProductPanel2();
frame.setContentPane(pane);
frame.setSize(1000,1000);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
You should re-think, how you are using the MigLayout! Please consider reading the quickstart guide: http://www.miglayout.com/QuickStart.pdf
Also your variable naming needs some work, it is very unclear, which variable is for what.
In order to solve your problem, do this:
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
// I have created a new Dimension-object. Those dimensions are FIXED! You might want to put a new dimension in, that is relative to the window size.
scr_Data.setPreferredSize(new Dimension(800, 800));
JPanel filterPanel=new JPanel();
Change this line (where you are setting absolute widths and heights for rows and columns!):
setLayout(new MigLayout("debug", "[96px][][94.00][grow][149.00px][2px][161px]", "[16px][240px,grow][12px][29px]"));
To this:
setLayout(new MigLayout());
Remove all the cells you have added, because you have mixed them with other layout-parts, that are not cells:
add(lst_Options, "grow");
filterPanel.add(scr_Data,"wrap");
// filterPanel.add(cmb_Suppliers, "");
add(filterPanel,"width 100%, growx, push, span, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);
add(lbl_Opciones, "growx,aligny top");
add(btn_Delete, "alignx right,aligny bottom");
add(btn_NewUpdate, "alignx right,aligny bottom");
Looks like this:
PS: I did not know that this would work:
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
The usual way is:
String[] columnNames = {"Name 1","Name 2","Name 3","Name 4","Name 5"};
I've learned something!
EDIT:
I've learned, that split() works by using regular expression, so you have to be careful, how to use it!
This will return an empty field and NOT "aaa" and "bbb":
"aaa.bbb".split(".");
Update:
I have updated my answer, this is the code in the initComponents()-method. I again urge you to read more about the MigLayout and stop mixing cell-components like this add(lst_Options, "cell 0 1,grow"); with non-cell components. This is messy and hard to understand / fix. I removed those cells in my answer and added alignments for the buttons. Now everything works as expected.
private void initComponents() {
lblProd = new JLabel("Product List: ");
btn_NewUpdate = new JButton("Add");
btn_Delete = new JButton("Remove");
lbl_SelectedOption = new JLabel("Tipo de datos");
JLabel lbl_Opciones = new JLabel("Opciones");
lst_Options = new JList<String>();
modeloOpciones = new DefaultListModel<String>();
btn_Delete = new JButton("Eliminar");
btn_NewUpdate = new JButton("Nuevo");
scr_Data = new JScrollPane();
cmb_Suppliers = new JComboBox<String>();
modeloOpciones.addElement("Proveedores");
modeloOpciones.addElement("Productos");
modeloOpciones.addElement("Partidas");
lst_Options.setModel(modeloOpciones);
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
tbl_Settings.setPreferredScrollableViewportSize(tbl_Settings.getPreferredSize());
setLayout(new MigLayout("","[right]"));
add(lbl_Opciones, "growx,aligny, top, wrap");
add(lst_Options, "grow");
add(scr_Data, "width 100%, growx, push, span, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);
btn_Delete.setHorizontalAlignment(SwingConstants.RIGHT);
btn_NewUpdate.setHorizontalAlignment(SwingConstants.RIGHT);
add(btn_Delete, "bottom, span 2");
add(btn_NewUpdate, "bottom");
refreshCombo(cmb_Suppliers);
}
Looks like this:

java.lang.illegalargumentexception adding a window to a container

I keep receiving this error
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.*;
import java.awt.Container.*;
public class main extends JFrame implements ActionListener
{
JButton CustomerOrder;
JButton SoftwareProducts;
JButton BooksProducts;
JButton AddBooks;
JButton StaffMember;
JButton LoginView;
static ArrayList<Software> softwareList = new ArrayList<Software>();
CardLayout c1 = new CardLayout();
JPanel mainPanel;
SoftwareProducts addsoftware;
CustomerOrder customerorder;
BooksProducts addProduct;
AddBooks addBook;
SoftwareProducts sf = new SoftwareProducts();
//Press submit;
public static void main(String[] args)
{
new main();
JFrame frame = new JFrame("Selling Product");
frame.setLocationRelativeTo(null);
//frame.getContentPane().add(main, BorderLayout.CENTER);
//new CustomerOrder();
//EmailFrame email=new EmailFrame();
//CustomerOrder co = new CustomerOrder();
//LoginView login = new LoginView();
}
public main(){
super();
// getContentPane().setBackground(Color.green);
setSize(700,800);
setLayout(new FlowLayout());
/*CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "softwareProducts");
*/
//CustomerOrder co = new CustomerOrder();
//add(co);
SoftwareProducts = new JButton("SoftwareProducts");
SoftwareProducts.setSize(150,40);
SoftwareProducts.setLocation(20,50);
CustomerOrder = new JButton("CustomerOrder");
CustomerOrder.setSize(160,40);
CustomerOrder.setLocation(150,50);
BooksProducts = new JButton("BooksProducts");
BooksProducts.setSize(200,40);
BooksProducts.setLocation(310,50);
AddBooks = new JButton("AddBook");
AddBooks.setSize(200,40);
AddBooks.setLocation(310,50);
StaffMember = new JButton("StaffMember");
StaffMember.setSize(200,40);
StaffMember.setLocation(310,50);
LoginView = new JButton("LoginView");
LoginView.setSize(150,40);
LoginView.setLocation(20,50);
SoftwareProducts.addActionListener(this);
add(SoftwareProducts);
CustomerOrder.addActionListener(this);
add(CustomerOrder);
BooksProducts.addActionListener(this);
add(BooksProducts);
AddBooks.addActionListener(this);
add(AddBooks);
StaffMember.addActionListener(this);
add(StaffMember);
mainPanel = new JPanel();
mainPanel.setBackground(Color.BLUE);
mainPanel.setPreferredSize(new Dimension(600,500));
mainPanel.setLayout(c1);
addsoftware = new SoftwareProducts();
mainPanel.add(addsoftware,"addsoftware");
customerorder = new CustomerOrder(); ////// I am getting the error
from this part of code
mainPanel.add(customerorder,"customerorder");///// I am getting the
error from this part of code
addProduct = new BooksProducts();
mainPanel.add(addProduct,"addProduct");
addBook = new AddBooks();
mainPanel.add(addBook,"addBook");
/* mainPanel.add(SoftwareProducts);
mainPanel = new JPanel(new CardLayout());
mainPanel.add(SoftwareProducts);
getContentPane().add(mainPanel);
addProduct = new BooksProducts();
mainPanel.add(addProduct,"addProduct");
*/
add(mainPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == SoftwareProducts)
{
c1.show(mainPanel,"addsoftware");
this.setTitle("SoftwareProducts");
//System.out.println("Softwares");
}
if(e.getSource() == CustomerOrder)
{
c1.show(mainPanel,"customerorder");
this.setTitle("CustomerOrder");
//System.out.println("Custmers");
}
if(e.getSource() == BooksProducts)
{
c1.show(mainPanel,"addProduct");
this.setTitle("BooksProducts");
}
if(e.getSource() == AddBooks)
{
c1.show(mainPanel,"addBook");
this.setTitle("AddBooks");
}
if(e.getSource() == LoginView)
{
c1.show(mainPanel,"LogIN");
this.setTitle("LOGIN");
}
}
/* public void actionPerformed(ActionEvent e)
{
if(e.getSource() == press)
{
System.out.println("addProducts");
}
}*/
}
and my customerOrder class
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.*;
import java.io.*;
public class CustomerOrder extends JFrame
implements ActionListener
{
//JButton asd = new JButton("BUTTON");
//JTextField productID;
//JTextField productName;
//JTextField productCost;
//JTextField productPYear;
//JTextField productPHouse;
JButton showOrder;
DefaultListModel<String> model = new DefaultListModel<>();
JList <String>orderList = new JList(model);
JTable softwareTabel = new JTable();
//DefaultTableModel tableModel = new DefaultTableModel(0, 1);
public CustomerOrder()
{
//super();
// JLabel toLabel=new JLabel("Product ID: ");
//JTextField to=new JTextField();
setLayout(new FlowLayout());
/*
productName = new JTextField(12);
add(productName);
productCost = new JTextField(12);
add(productCost);
productPYear = new JTextField(12);
add(productPYear);
productPHouse = new JTextField(12);
add(productPHouse);
*/
showOrder = new JButton("SHOW ORDER");
showOrder.setSize(25,40);
showOrder.addActionListener(this);
add(showOrder);
}
public void actionPerformed(ActionEvent e)
{
//Object[] colNames={"Product ID","Processor","RAm"};
if(e.getSource() == showOrder)
{
model.removeAllElements();
/* GridLayout exLayout = new GridLayout(3, 3);
JLabel ram,processor;
ram = new JLabel("RAM");
processor = new JLabel("Processor");
String softwaredata[] = {"ID","RAM","Processor","Product ID","Product Name","Product Year","Product Year","Product PublishHouse"};
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 3));
add(ram);
add(processor);
JTable table = new JTable();*/
//DeafultTableModel dm = new DeafultTableModel(0,0);
//String header[] = new String[] {"RAM", "Processor","ProductID","Product Name","Product Year","Product Publish House"};
//dm.setColumnIdentifiers(header);
//Object[][] software = new Object[8][3];
//model.addRow(orderList.toArray());
int x = 0;
while (x < main.softwareList.size())
{
//./model.addElement(main.softwareList.get(x).getproductYear());
model.addElement(""+main.softwareList.get(x).getproductID());
model.addElement(""+main.softwareList.get(x).getRam());
model.addElement(""+ main.softwareList.get(x).getProcessor());
model.addElement(""+ main.softwareList.get(x).getproductID());
model.addElement(main.softwareList.get(x).getproductName());
model.addElement(""+ main.softwareList.get(x).getproductYear());
model.addElement(main.softwareList.get(x).getproductPublishHouse());
//model.addElement(main.softwareList.get(x).getproductID());*/
x++;
//System.out.println("as");
}
/* ArrayList<String> table1 = new ArrayList();
ArrayList<ArrayList<String>> table2 = new ArrayList();
table1.add("Product ID");
table1.add("RAM");
table1.add("Processor");
table1.add("Product Name");
table1.add("Product Year");
table1.add("Product PHouse");
Object[] software = table1.toArray();
String[] [] softwarest = new String[table1.size()][];
int i = 0;
for (List<String> next : table2){
softwarest[i++] = next.toArray(new String[next.size()]);
}
JTable newTable = new JTable(softwarest,software);
JFrame frame = new JFrame();
frame.getContentPane().add(new JScrollPane(newTable));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
*/
//table.add(model);
// add(orderList);
//Object[] column = {"RAM:", "Processor:"};
//Object[][] data = {{"RAM:", "Processor:"}};
//JTable table = new JTable();
//table.setShowGrid(false);
//table.setTableHeader(null);
}
}
}
When i run this code i get the following exception from the main class in customerorder = new CustomerOrder;
mainPanel.add(customerorder,"customerorder")
customorder is an instance of CustomerOrder, which extends from JFrame; public class CustomerOrder extends JFrame
As the error states illegalargumentexception adding a window to a container; it is illegal to add a window to another window, it simply doesn't make sense.
This is one of the reasons we discourage extending from top level containers like JFrame directly.
Either make the CustomerOrder visible like any normal frame (although that might lead you into other issues) or better yet, base your CustomerOrder component of a JPanel
public class CustomerOrder extends JPanel {
//...
}
This way you can add it to what ever container you need to.
Idk if this logic is correct, but in just playing around to try and figure out the reason it doesn't make sense for myself I concluded that:
extending JFrame causes only one object to be created and why it tries to add the JFrame frame; object to itself which causes the exception...
extending JPanel allows the JFrame frame; <-- object to divide into a Container & a Component which allows you to
frame.add(this) ..
frame.add(this) is the component invoked by JPanel method .add()
if this is wrong plz correct..

component must be showing on the screen to determine its location when changing JCOMBOX

I am receiving this error when i change items in the Jcombobox, nothing breaks it just shows this error, is there anyway to just throw it so it doesn't show up. everything still works fine, but if you wish to have a look at the code. i will post below.
Error message:
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:2056)
at java.awt.Component.getLocationOnScreen(Component.java:2030)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:395)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:393)
at sun.lwawt.macosx.LWCToolkit$CallableWrapper.run(LWCToolkit.java:538)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:301)
And my code which i don't know which section to show so its all their.
import javax.swing.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
public class TouchOn extends JDialog {
private JPanel mainPanel;
public ArrayList Reader(String Txtfile) {
try {
ArrayList<String> Trains = new ArrayList<String>();
int count = 0;
String testing = "";
File file = new File(Txtfile);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
count += count;
if(!line.contains("*")){
Trains.add(line + "\n");
}
stringBuffer.append("\n");
}
fileReader.close();
//Arrays.asList(Trains).stream().forEach(s -> System.out.println(s));
return Trains;
} catch (IOException e) {
e.printStackTrace();
}
//return toString();
return null;
}
public TouchOn()
{
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
public void setPanels()
{
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
JTextField sYear = new JTextField("2015");
String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
JTextField touchOnTimeFieldhour = new JTextField();
JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]));
JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
apply.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if(belgrave.isSelected()){
String trainline = belgrave.getText();
}
if(glenwaverly.isSelected()){
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10,10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}
Don't create multiple JComboBoxes and then swap visibility. Instead use one JComboBox and create multiple combo box models, such as by using DefaultComboBoxModel<String>, and then swap out the model that it holds by using its setModel(...) method. Problem solved.
Note that using a variation on your code -- I'm not able to reproduce your problem:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestFoo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndDisplayGui();
}
});
}
public static void createAndDisplayGui() {
final JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton button = new JButton(new AbstractAction("Press Me") {
#Override
public void actionPerformed(ActionEvent evt) {
TouchOn2 touchOn2 = new TouchOn2(frame);
touchOn2.setVisible(true);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class TouchOn2 extends JDialog {
private JPanel mainPanel;
#SuppressWarnings({ "rawtypes", "unused" })
public ArrayList Reader(String Txtfile) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add("Data String Number " + (i + 1));
}
// return toString();
// !! return null;
return list;
}
public TouchOn2(Window owner) {
super(owner);
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
#SuppressWarnings("unchecked")
public void setPanels() {
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
final JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
final JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
final JTextField sYear = new JTextField("2015");
final String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
final JTextField touchOnTimeFieldhour = new JTextField();
final JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
final JComboBox<String> cb = new JComboBox<>(
stations.toArray(new String[stations.size()]));
final JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
final JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
apply.addActionListener(new ActionListener() {
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent e) {
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy")
.format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if (belgrave.isSelected()) {
// !! ***** note you're shadowing variables here!!!! ****
String trainline = belgrave.getText();
}
if (glenwaverly.isSelected()) {
// !! and here too
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10, 10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}

How to pass an object argument to a method called in actionPerformed?

I am writing a stock control system program for a school project. This is the last thing I need to do, but seeing as I am a relative Java noob, I kindly request your assistance.
I have a DisplayRecord class, which is created by taking String input from a "search" JTextField in the Search class, finding the Object (Product p) it's linked to, and passing it to the displayRecord method. This part works perfectly.
I want to take that Product p and pass it to the EditProduct class or the DeleteRecord class (depending on the JButton pressed) so the user can then edit the Name, Quantity or Cost of that same Product. Here are my DisplayRecord, EditProduct and DeleteRecord classes. I have no idea what to do.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
public class DisplayRecord extends JFrame implements ActionListener {
final private StockList stocks;
final private ArrayList<Product> list;
JFrame showWindow;
private JPanel top, bot;
private JPanel barcodePanel1 = new JPanel();
private JPanel barcodePanel2 = new JPanel();
private JPanel namePanel1 = new JPanel();
private JPanel namePanel2 = new JPanel();
private JPanel descPanel1 = new JPanel();
private JPanel descPanel2 = new JPanel();
private JPanel compPanel1 = new JPanel();
private JPanel compPanel2 = new JPanel();
private JPanel ratingPanel1 = new JPanel();
private JPanel ratingPanel2 = new JPanel();
private JPanel costPanel1 = new JPanel();
private JPanel costPanel2 = new JPanel();
private JPanel quantityPanel1 = new JPanel();
private JPanel quantityPanel2 = new JPanel();
private JLabel barcodeLabel = new JLabel();
private JLabel nameLabel = new JLabel();
private JLabel descLabel = new JLabel();
private JLabel compLabel = new JLabel();
private JLabel ratingLabel = new JLabel();
private JLabel costLabel = new JLabel();
private JLabel quantityLabel = new JLabel();
private GridLayout displayLayout;
JButton edit = new JButton("Edit");
JButton backToMenu = new JButton("Back to Menu");
JButton delete = new JButton("Delete");
public DisplayRecord() {
stocks = new StockList();
list = stocks.getList();
try {
stocks.load();
} catch (IOException ex) {
System.out.println("Cannot load file");
}
}
public void displayRecord(Product p) {
this.setTitle("Displaying one record");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 350));
top = new JPanel();
displayLayout = new GridLayout(7, 2, 2, 2);
top.setLayout(displayLayout);
top.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 5));
bot = new JPanel();
bot.setLayout(new BoxLayout(bot, BoxLayout.LINE_AXIS));
bot.add(Box.createHorizontalGlue());
bot.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 5));
barcodeLabel.setText("Barcode: ");
nameLabel.setText("Name: ");
descLabel.setText("Description: ");
compLabel.setText("Developer: ");
ratingLabel.setText("EU Rating: ");
costLabel.setText("Cost: ");
quantityLabel.setText("Quantity in Stock: ");
JLabel barcodeField = new JLabel(Long.toString(p.getBarcode()));
JLabel nameField = new JLabel(p.getName());
JLabel descField = new JLabel(p.getDesc());
JLabel compField = new JLabel(p.getCompany());
JLabel ratingField = new JLabel(p.getRating());
JLabel costField = new JLabel(Double.toString(p.getCost()));
JLabel quantityField = new JLabel(Integer.toString(p.getQuantity()));
barcodePanel1.add(barcodeLabel);
barcodePanel1.setBorder(BorderFactory.createLineBorder(Color.black));
barcodePanel2.add(barcodeField); barcodePanel2.setBorder(BorderFactory.createLineBorder(Color.black));
namePanel1.add(nameLabel);
namePanel1.setBorder(BorderFactory.createLineBorder(Color.black));
namePanel2.add(nameField);
namePanel2.setBorder(BorderFactory.createLineBorder(Color.black));
descPanel1.add(descLabel);
descPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
descPanel2.add(descField);
descPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
compPanel1.add(compLabel);
compPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
compPanel2.add(compField);
compPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
ratingPanel1.add(ratingLabel);
ratingPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
ratingPanel2.add(ratingField);
ratingPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
costPanel1.add(costLabel);
costPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
costPanel2.add(costField);
costPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
quantityPanel1.add(quantityLabel);
quantityPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
quantityPanel2.add(quantityField);
quantityPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
top.add(barcodePanel1);
top.add(barcodePanel2);
top.add(namePanel1);
top.add(namePanel2);
top.add(descPanel1);
top.add(descPanel2);
top.add(compPanel1);
top.add(compPanel2);
top.add(ratingPanel1);
top.add(ratingPanel2);
top.add(costPanel1);
top.add(costPanel2);
top.add(quantityPanel1);
top.add(quantityPanel2);
edit.addActionListener(this);
delete.addActionListener(this);
backToMenu.addActionListener(this);
bot.add(edit);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(delete);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(backToMenu);
this.add(top);
this.add(bot, BorderLayout.SOUTH);
this.setLocationRelativeTo(null);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) { // here is where I'd LIKE to pass Product p as parameter but obviously that's not a thing
if (e.getSource() == edit) {
// EditProduct ed = new EditProduct(); <- hypothetical!
// ed.editProduct(p);
} else if (e.getSource() == delete) {
// DeleteRecord del = new DeleteRecord(); <- hypothetical!
// del.deleteRecord(p);
} else if (e.getSource() == backToMenu) {
new CreateDisplay();
this.dispose();
}
}
}
My EditProduct class:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class EditProduct extends JFrame implements FocusListener, ActionListener {
final private StockList stocks;
final private ArrayList<Product> list;
JPanel top, bot;
JLabel nameLabel, costLabel, quantityLabel = new JLabel();
JTextField nameField, costField, quantityField = new JTextField();
JButton save, quit = new JButton();
private GridLayout topLayout;
public EditProduct() {
stocks = new StockList();
list = stocks.getList();
}
public void editProduct(Product p) {
this.setTitle("Editing a Product");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 250));
top = new JPanel();
topLayout = new GridLayout(3, 2, 5, 5);
top.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 5));
top.setLayout(topLayout);
bot = new JPanel();
bot.setLayout(new BoxLayout(bot, BoxLayout.LINE_AXIS));
bot.add(Box.createHorizontalGlue());
bot.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 5));
nameLabel.setText("Name: ");
costLabel.setText("Cost: ");
quantityLabel.setText("Quantity: ");
top.add(nameLabel);
top.add(costLabel);
top.add(quantityLabel);
nameField = new JTextField(p.getName());
costField = new JTextField(String.valueOf(p.getCost()));
quantityField = new JTextField(p.getQuantity());
nameField.addFocusListener(this);
costField.addFocusListener(this);
quantityField.addFocusListener(this);
save.setText("Save");
save.addActionListener(this);
quit.setText("Quit");
quit.addActionListener(this);
bot.add(save);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(quit);
this.add(top);
this.add(bot, BorderLayout.SOUTH);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
#Override
public void focusGained(FocusEvent e) {
if (e.getSource() == nameField) {
nameField.setText("");
} else if (e.getSource() == costField) {
costField.setText("");
} else if (e.getSource() == quantityField) {
quantityField.setText("");
}
}
#Override
public void focusLost(FocusEvent fe) {
//do nothing
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == save) {
String newName = nameField.getText();
double newCost = Double.parseDouble(costField.getText());
int newQty = Integer.parseInt(quantityField.getText());
stocks.editProduct(newName, newCost, newQty);
this.dispose();
JOptionPane.showMessageDialog(null, "Changes have been saved!", "Saved!", JOptionPane.PLAIN_MESSAGE);
} else if (e.getSource() == quit) {
}
}
}
Aaand the DeleteRecord class:
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class DeleteRecord {
private StockList stocks;
private ArrayList<Product> list;
public DeleteRecord() {
stocks = new StockList();
list = stocks.getList();
}
public DeleteRecord(Product p) {
String title = "Are you sure you want to delete " + p.getName() + "?";
if (JOptionPane.showConfirmDialog(null, title, "Deleting...", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
stocks.deleteRecord(p);
} else {
new CreateDisplay();
}
}
}
I'm sorry for the massive post and text wall but I honestly have no idea where my problem is or how to work around this problem (and I'm also new to StackOverflow). Can anyone help me?
It seems to me that DisplayRecord can only display one Product at a time. If that is indeed the case, you can store that Product in a field and then access it from actionPerfomed().

JButton + radiobox + checkbox

I'd like this program I have to have some kind of "sum" button which will add in the column "Description" summarised information about the movie. Lets say I have "die hard" as a title, age 7 from radiobutton, and horror selected from the checkbox. Pressin the button would put "Die hard, 7, horror" under the column. I have no idea how to aproach this case.
package naplety.Swing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.JCheckBox;
public class SamodzielnaListaOsob extends JFrame implements ActionListener {
JButton dodaj, erease;
JTextField film;
DefaultListModel<String> listFilm;
DefaultTableModel tableFilm;
public SamodzielnaListaOsob(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JTextField film = new JTextField("Wpisz tytul filmu", 10);
film.setBorder(BorderFactory.createTitledBorder("Film"));
JPanel p1 = new JPanel();
p1.add(film);
JButton dodaj = new JButton("Add to list");
dodaj.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
listFilm.addElement(nowyFilm);
film.setText("");
}
}
});
JButton erease = new JButton("Clear");
erease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
film.setText("");
}
});
JButton dodajDoTabeli = new JButton("Add to table");
dodajDoTabeli.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
int ile = tableFilm.getRowCount();
tableFilm.addRow(new Object[] { ile + 1, nowyFilm });
}
}
});
JRadioButton sevenbutton = new JRadioButton("7");
JRadioButton twbutton = new JRadioButton("12");
JRadioButton sixbutton = new JRadioButton("16");
JRadioButton eightbutton = new JRadioButton("18");
ButtonGroup bg1 = new ButtonGroup();
bg1.add(sevenbutton);
bg1.add(twbutton);
bg1.add(sixbutton);
bg1.add(eightbutton);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(4, 0));
radioPanel.add(sevenbutton);
radioPanel.add(twbutton);
radioPanel.add(sixbutton);
radioPanel.add(eightbutton);
radioPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Age"));
radioPanel.setSize(200, 200);
JCheckBox Horror = new JCheckBox("Horror");
JCheckBox Komedia = new JCheckBox("Comedy");
JCheckBox Thriller = new JCheckBox("Thriller");
JCheckBoxMenuItem listac = new JCheckBoxMenuItem();
listac.add(Horror);
listac.add(Komedia);
listac.add(Thriller);
JPanel listaChceck = new JPanel();
listaChceck.add(Horror);
listaChceck.add(Komedia);
listaChceck.add(Thriller);
listaChceck.setLayout(new GridLayout(3, 0));
JPanel p2 = new JPanel();
p2.add(dodaj);
p2.add(erease);
p2.add(dodajDoTabeli);
p2.add(radioPanel);
p2.add(listaChceck);
listFilm = new DefaultListModel<String>();
listFilm.addElement("Achacy");
listFilm.addElement("Bonifacy");
listFilm.addElement("Cezary");
JList<String> lista = new JList<String>(listFilm);
JScrollPane sl = new JScrollPane(lista);
sl.setPreferredSize(new Dimension(150, 150));
sl.setBorder(BorderFactory.createTitledBorder("List"));
String[] kolumnyTabeli = { "Nr", "Movie", "Description" };
tableFilm = new DefaultTableModel(kolumnyTabeli, 0) {
};
JTable tabela = new JTable(tableFilm);
JScrollPane st = new JScrollPane(tabela);
st.setPreferredSize(new Dimension(300, 150));
st.setBorder(BorderFactory.createTitledBorder("Table"));
JPanel p3 = new JPanel();
p3.add(sl);
p3.add(st);
setPreferredSize(new Dimension(900, 900));
setVisible(true);
p1.add(p2);
p2.add(p3);
setContentPane(p1);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SamodzielnaListaOsob("List of movies");
}
});
}
}
You need to declare your variables either before you try to access them, or declare them global, which I did. I prefer this way.
Use .pack() on your frame to when you start the program, something actually shows.
Learn to use LayoutManagers for a better look.
Use arrays of RadioButtons and CheckBoxes so its easier to loop through them. I has to manually write a bunch of if statements, which would not be necessary if I could loop through them.
To get is a RadioButton or CheckBox is selected, use .isSelected()
.setVisible(true) after you add all your components.
Here's is your refactored code. I did nothing else to it, but fix the issue posted in your question. It now adds the info the desciption, when you hit the Add Film button.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class SamodzielnaListaOsob extends JFrame {
JButton dodaj, erease;
JTextField film;
DefaultListModel<String> listFilm;
DefaultTableModel tableFilm;
JList<String> lista = null;
JRadioButton sevenbutton = new JRadioButton("7");
JRadioButton twbutton = new JRadioButton("12");
JRadioButton sixbutton = new JRadioButton("16");
JRadioButton eightbutton = new JRadioButton("18");
JCheckBox Horror = new JCheckBox("Horror");
JCheckBox Komedia = new JCheckBox("Comedy");
JCheckBox Thriller = new JCheckBox("Thriller");
ButtonGroup bg1 = new ButtonGroup();
public SamodzielnaListaOsob(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JTextField film = new JTextField("Wpisz tytul filmu", 10);
film.setBorder(BorderFactory.createTitledBorder("Film"));
JPanel p1 = new JPanel();
p1.add(film);
JButton dodaj = new JButton("Add to list");
dodaj.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
listFilm.addElement(nowyFilm);
film.setText("");
}
}
});
JButton erease = new JButton("Clear");
erease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
film.setText("");
}
});
JButton dodajDoTabeli = new JButton("Add to table");
dodajDoTabeli.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
int ile = tableFilm.getRowCount();
String title = lista.getSelectedValue();
int age;
if (sixbutton.isSelected()) {
age = 16;
} else if (sevenbutton.isSelected()) {
age = 7;
} else if (eightbutton.isSelected()) {
age = 18;
} else {
age = 12;
}
String genres = "";
if (Horror.isSelected()) {
genres += "Horror, ";
}
if (Komedia.isSelected()) {
genres += "Komedia, ";
}
if (Thriller.isSelected()) {
genres += "Thriller";
}
String desc = title + ", " + age + ", " + genres;
tableFilm.addRow(new Object[]{ile + 1, nowyFilm, desc});
}
}
});
bg1.add(sevenbutton);
bg1.add(twbutton);
bg1.add(sixbutton);
bg1.add(eightbutton);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(4, 0));
radioPanel.add(sevenbutton);
radioPanel.add(twbutton);
radioPanel.add(sixbutton);
radioPanel.add(eightbutton);
radioPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Age"));
radioPanel.setSize(200, 200);
JCheckBoxMenuItem listac = new JCheckBoxMenuItem();
listac.add(Horror);
listac.add(Komedia);
listac.add(Thriller);
JPanel listaChceck = new JPanel();
listaChceck.add(Horror);
listaChceck.add(Komedia);
listaChceck.add(Thriller);
listaChceck.setLayout(new GridLayout(3, 0));
JPanel p2 = new JPanel();
p2.add(dodaj);
p2.add(erease);
p2.add(dodajDoTabeli);
p2.add(radioPanel);
p2.add(listaChceck);
listFilm = new DefaultListModel<String>();
listFilm.addElement("Achacy");
listFilm.addElement("Bonifacy");
listFilm.addElement("Cezary");
lista = new JList<String>(listFilm);
JScrollPane sl = new JScrollPane(lista);
sl.setPreferredSize(new Dimension(150, 150));
sl.setBorder(BorderFactory.createTitledBorder("List"));
String[] kolumnyTabeli = {"Nr", "Movie", "Description"};
tableFilm = new DefaultTableModel(kolumnyTabeli, 0) {
};
JTable tabela = new JTable(tableFilm);
JScrollPane st = new JScrollPane(tabela);
st.setPreferredSize(new Dimension(300, 150));
st.setBorder(BorderFactory.createTitledBorder("Table"));
JPanel p3 = new JPanel();
p3.add(sl);
p3.add(st);
p1.add(p2);
p2.add(p3);
setContentPane(p1);
pack();
setPreferredSize(new Dimension(900, 900));
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SamodzielnaListaOsob("List of movies");
}
});
}
}
Radio buttons and Check Buttons don't work like textfields. In a textfield, the useful values are picked up from the "text" member (example: getText()). A radioButton instead defines a set of fixed choices (well, you can make them dynamic, but it doesn't worth it, there are better components for that kind of work) like "yes" and "no". Usually, when you pickup some rabiobutton, you use the isChecked() method (returns boolean, it may be isChecked(), I don't remember) to react in one way or another. Example:
String age = 0;
if(sevenbutton.isSelected()){
age = 7;
}
Nonetheless, I think you can get the value from the text in the sevenbutton using getText(), but you're gonna need to check which radiobutton is checked anyway. A checkButton works in a pretty similar way, but for non-exclusive choices, so you need to use the isSelected() method, or similar, anyway.
Your method should look like:
private void addMovie(){
String age = "0";
String gender = "";
//Evaluate radioButtons
if(sevenbutton.isSelected()){
age = 7;
}
//Evaluate checkbuttons
if(Horror.isSelected()){
gender = gender+" horror";
}
String movie = film+" "+age+" "+gender;
//do anything else
}

Categories

Resources