miglayout with jtable with issue - java

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:

Related

How can we compare two Strings and get duplicates values

I created a window with a button and 3 fields, 1st, 2nd field is the text, and in the 3rd field, it is necessary to write down words that are repeated in 1st & 2nd fields. How to make it?
JFrame frame = new JFrame("new Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Label lbTextLabel = new Label("1:");
lbTextLabel.setBounds(50, 10, 120, 20);
Label lbTextLabel2 = new Label("2:");
lbTextLabel2.setBounds(50, 50, 120, 20);
Label lbTextLabel3 = new Label("3:");
lbTextLabel3.setBounds(50, 90, 120, 20);
JTextArea TextArea = new JTextArea("Welcome to javatpoint");
TextArea.setBounds(50,30, 120,20);
JTextArea TextArea2 = new JTextArea("Welcome to javatpoint 2");
TextArea2.setBounds(50,70, 127,20);
JTextArea TextArea3 = new JTextArea("");
TextArea3.setBounds(50,110, 127,20);
JButton button =new JButton("Click Here");
button.setBounds(140,130,95,30);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
Tell me that the below code does what you want and I will add explanations.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Identify {
private JTextArea oneTextArea;
private JTextArea twoTextArea;
private JTextArea threeTextArea;
private void createAndDisplayGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
JButton button = new JButton("Click Me");
button.setMnemonic(KeyEvent.VK_C);
button.addActionListener(this::findCommonWords);
buttonsPanel.add(button);
return buttonsPanel;
}
private JPanel createMainPanel() {
JPanel mainPanel = new JPanel(new GridLayout(0, 2, 10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JLabel oneLabel = new JLabel(" 1:");
oneLabel.setDisplayedMnemonic(KeyEvent.VK_1);
mainPanel.add(oneLabel);
oneTextArea = new JTextArea("Apple Mango Orange");
mainPanel.add(oneTextArea);
oneLabel.setLabelFor(oneTextArea);
JLabel twoLabel = new JLabel(" 2:");
twoLabel.setDisplayedMnemonic(KeyEvent.VK_2);
mainPanel.add(twoLabel);
twoTextArea = new JTextArea("Mango Orange Banana");
mainPanel.add(twoTextArea);
twoLabel.setLabelFor(twoTextArea);
JLabel threeLabel = new JLabel(" 3:");
threeLabel.setDisplayedMnemonic(KeyEvent.VK_3);
mainPanel.add(threeLabel);
threeTextArea = new JTextArea(1, 10);
mainPanel.add(threeTextArea);
threeLabel.setLabelFor(threeTextArea);
return mainPanel;
}
private void findCommonWords(ActionEvent event) {
String text1 = oneTextArea.getText();
String text2 = twoTextArea.getText();
String[] words1 = text1.split(" ");
String[] words2 = text2.split(" ");
List<String> list1;
List<String> list2;
if (words1.length > words2.length) {
list1 = new ArrayList<>(Arrays.asList(words1));
list2 = new ArrayList<>(Arrays.asList(words2));
}
else {
list1 = new ArrayList<>(Arrays.asList(words2));
list2 = new ArrayList<>(Arrays.asList(words1));
}
list1.retainAll(list2);
threeTextArea.setText(list1.stream().collect(Collectors.joining(" ")));
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new Identify().createAndDisplayGui());
}
}
This is what it looks like when I run it (before clicking on the button).
You have to split both textarea word and check if first textarea word is matched with second textarea word, If match print it in third textarea.
Here down is example:
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
class CompareWord{
public static void main(String[] args) {
JFrame f;
JLabel lbTextLabelt1, lbTextLabel2, lbTextLabel3;
JTextArea TextArea, TextArea2, TextArea3;
JButton button;
f = new JFrame("new Frame");
lbTextLabelt1 = new JLabel("1:");
lbTextLabelt1.setBounds(50, 10, 120, 20);
lbTextLabel2 = new JLabel("2:");
lbTextLabel2.setBounds(50, 70, 120, 20);
lbTextLabel3 = new JLabel("3:");
lbTextLabel3.setBounds(50, 140, 120, 20);
TextArea = new JTextArea("Welcome to javatpoint");
TextArea.setBounds(50,30, 120,30);
TextArea2 = new JTextArea("Welcome to javatpoint");
TextArea2.setBounds(50,90, 127,30);
TextArea3 = new JTextArea("");
TextArea3.setBounds(50,160, 127,30);
button = new JButton("Click Here");
button.setBounds(120,200,95,30);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String str1 = TextArea.getText(); // 🍎 🥭 🍊;
String str2 = TextArea2.getText(); // 🥭 🍊 🍌
String str3 = "";
String arrStr1[] = str1.split("//s+");
String arrStr2[] = str2.split("//s+");
List<String> wordsOfFirstStr = Arrays.asList(str1.split(" "));
for (String wordsOfSecondStr : str2.split(" ")) {
if(wordsOfFirstStr.contains(wordsOfSecondStr))
{
str3 += wordsOfSecondStr + " ";
}
}
TextArea3.setText(str3);
}
});
f.add(lbTextLabelt1);
f.add(lbTextLabel2);
f.add(lbTextLabel3);
f.add(TextArea);
f.add(TextArea2);
f.add(TextArea3);
f.add(button);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

trouble with creating JTable to display data [closed]

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);
}
}

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
}

Create dynamic table to add new entry with button

I am trying to build a register, so that when a button is clicked, a new entry appears on a table. Ideally, I am looking to build a table on the left side of the screen, with two rows and new column appears when the button is clicked. I want the table to have a fixed size, but it should be scrollable after a certain amount of entries. So far, I have created and formatted the JButton objects that I want to be clicked for a new entry to appear. I also know that I should use a JTable to pursue this.
How should I go about making this dynamic table?
Code So Far:
private void addRegister(JPanel pane) {
JPanel everythingPane = new JPanel();
JPanel pluPane = new JPanel();
Dimension button = new Dimension(200,150);
JTable pluTable = new JTable();
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.Y_AXIS));
//JPanel buttonPane = new JPanel (new FlowLayout (FlowLayout.LEFT));
JPanel subPane1 = new JPanel();
subPane1.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane2 = new JPanel();
subPane2.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane3 = new JPanel();
subPane3.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane4 = new JPanel();
subPane4.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane5 = new JPanel();
subPane5.setAlignmentX(LEFT_ALIGNMENT);
JPanel alignmentLayer = new JPanel();
JButton frappuccino = new JButton("Frappuccino");
JButton icedCoffee = new JButton("Iced Coffee");
frappuccino.setPreferredSize(button);
icedCoffee.setPreferredSize(button);
JButton arizona = new JButton("Arizona Green Tea");
JButton izze = new JButton("Izze");
arizona.setPreferredSize(button);
izze.setPreferredSize(button);
JButton snapple = new JButton("Snapple");
JButton gatorade = new JButton("Gatorade");
snapple.setPreferredSize(button);
gatorade.setPreferredSize(button);
JButton water = new JButton("Water");
JButton appleJuice = new JButton("Apple Juice");
water.setPreferredSize(button);
appleJuice.setPreferredSize(button);
JButton orangeJuice = new JButton("Orange Juice");
JButton mentos = new JButton("Mentos");
orangeJuice.setPreferredSize(button);
mentos.setPreferredSize(button);
JButton gum = new JButton("Gum");
JButton cliffBar = new JButton("Cliff Bar");
gum.setPreferredSize(button);
cliffBar.setPreferredSize(button);
JButton littleBites = new JButton("Little Bites");
JButton welchs = new JButton("Welch's Fruit Snacks");
littleBites.setPreferredSize(button);
welchs.setPreferredSize(button);
JButton fiberOneBar = new JButton("Fiber One Bar");
JButton fiberOneBrownie = new JButton("Fiber One Brownie");
fiberOneBar.setPreferredSize(button);
fiberOneBrownie.setPreferredSize(button);
JButton cheezeIts = new JButton("Cheeze Its");
JButton goldFish = new JButton("Gold Fish");
cheezeIts.setPreferredSize(button);
goldFish.setPreferredSize(button);
JButton teaBag = new JButton("Tea Bag");
JButton poptarts = new JButton("Poptarts");
teaBag.setPreferredSize(button);
poptarts.setPreferredSize(button);
JButton sampleButton = new JButton("Sample Button");
JButton sampleButton2 = new JButton("Sample Button");
sampleButton.setPreferredSize(button);
sampleButton2.setPreferredSize(button);
JButton sampleButton3 = new JButton("Sample Button");
JButton sampleButton4 = new JButton("Sample Button");
sampleButton3.setPreferredSize(button);
sampleButton4.setPreferredSize(button);
subPane1.add(frappuccino);
subPane1.add(icedCoffee);
subPane1.add(arizona);
subPane1.add(izze);
subPane2.add(snapple);
subPane2.add(gatorade);
subPane2.add(water);
subPane2.add(appleJuice);
subPane3.add(orangeJuice);
subPane3.add(mentos);
subPane3.add(gum);
subPane3.add(cliffBar);
subPane4.add(littleBites);
subPane4.add(welchs);
subPane4.add(fiberOneBar);
subPane4.add(fiberOneBrownie);
subPane5.add(cheezeIts);
subPane5.add(goldFish);
subPane5.add(teaBag);
subPane5.add(poptarts);
alignmentLayer.add(sampleButton);
alignmentLayer.add(sampleButton2);
alignmentLayer.add(sampleButton3);
alignmentLayer.add(sampleButton4);
buttonPane.add(subPane1);
buttonPane.add(subPane2);
buttonPane.add(subPane3);
buttonPane.add(subPane4);
buttonPane.add(subPane5);
buttonPane.add(Box.createRigidArea(new Dimension(5,100)));
buttonPane.add(alignmentLayer);
pluPane.add(pluTable);
everythingPane.add(pluPane);
everythingPane.add(buttonPane);
pane.add(everythingPane);
}
JTable is more commonly used in a way that adds rows, rather than columns. I re-factored this example to illustrate the basic idea below. Each time the button is clicked, a new row is added to the table's model, which updates the table itself.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
* #see https://stackoverflow.com/a/19472190/230513
* #see https://stackoverflow.com/a/7519403/230513
*/
public class TableAddTest extends JPanel {
private static final int N_ROWS = 8;
private static String[] header = {"ID", "String", "Number", "Boolean"};
private DefaultTableModel dtm = new DefaultTableModel(null, header) {
#Override
public Class<?> getColumnClass(int col) {
return getValueAt(0, col).getClass();
}
};
private JTable table = new JTable(dtm);
private JScrollPane scrollPane = new JScrollPane(table);
private JScrollBar vScroll = scrollPane.getVerticalScrollBar();
private int row;
private boolean isAutoScroll;
public TableAddTest() {
this.setLayout(new BorderLayout());
Dimension d = new Dimension(320, N_ROWS * table.getRowHeight());
table.setPreferredScrollableViewportSize(d);
for (int i = 0; i < N_ROWS; i++) {
addRow();
}
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
vScroll.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
isAutoScroll = !e.getValueIsAdjusting();
}
});
this.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("Add Row") {
#Override
public void actionPerformed(ActionEvent e) {
addRow();
}
}));
this.add(panel, BorderLayout.SOUTH);
}
private void addRow() {
char c = (char) ('A' + row++ % 26);
dtm.addRow(new Object[]{
Character.valueOf(c),
String.valueOf(c) + String.valueOf(row),
Integer.valueOf(row),
Boolean.valueOf(row % 2 == 0)
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableAddTest nlt = new TableAddTest();
f.add(nlt);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}

Categories

Resources