How can we compare two Strings and get duplicates values - java

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:

Related

Commands are running twice in Java actionperformed

I created an utility that will be used within the firewall zone to get Websphere MQ contents using Java with Swing, since I'm not sure where the defect lies, I've posted almost the entire code apart from the redundant part:
package testbox;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class MainFrame extends JFrame implements ActionListener
{
JLabel lblqname = new JLabel("Please enter the queue name");
JTextField txtqname = new JTextField(25);
JLabel lblqcur = new JLabel("where curdeth greater than");
JTextField txtqcurdfil = new JTextField(5);
JLabel lblchlname = new JLabel("Please enter the Channel name");
JTextField txtchlname = new JTextField(30);
JLabel lblchs = new JLabel("where status is: ");
JTextField txtchs = new JTextField(8);
public String ID;
public String pwdValue;
public String qname;
public int cdepth;
public String chlname;
public String chlstatus;
public String cmdissue;
JTextArea out = new JTextArea();
JButton QMGR1 = new JButton("QMGR1");
JButton QMGR2 = new JButton("QMGR2");
public MainFrame()
{
JLabel jUserName = new JLabel("ID");
JTextField userName = new JTextField();
JLabel jPassword = new JLabel("Password");
JTextField password = new JPasswordField();
Object[] ob = {jUserName, userName, jPassword, password};
int result = JOptionPane.showConfirmDialog(null, ob, "Please input password for Login", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
ID = userName.getText();
pwdValue = password.getText();
final JFrame frame = new JFrame("Environment Choice");
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("QAQmgrList", makeQAPanel());
frame.getContentPane().add(tabbedPane);
}
}
public JPanel makeQAPanel()
{
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 1;
p.add(QMGR1, gbc_QMGR1);
QMGR1.addActionListener(this);
GridBagConstraints gbc_QMGR2 = new GridBagConstraints();
gbc_QMGR2.insets = new Insets(0, 0, 5, 5);
gbc_QMGR2.gridx = 1;
gbc_QMGR2.gridy = 2;
p.add(QMGR2, gbc_QMGR2);
QMGR2.addActionListener(this);
return p;
}
public void createSubframe()
{
final JFrame subframe = new JFrame("Object Choice");
subframe.setSize(1000, 500);
subframe.getContentPane().setLayout(new GridLayout(1, 1));
out.setText(null);
out.setLineWrap(true);
out.setCaretPosition(out.getDocument().getLength());
out.setEditable (false);
JScrollPane jp = new JScrollPane(out);
jp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel queue = new JPanel();
queue.add(lblqname);
txtqname.setText(null);
queue.add(txtqname);
queue.add(lblqcur);
txtqcurdfil.setText(null);
queue.add(txtqcurdfil);
txtqname.addActionListener(this);
txtqcurdfil.addActionListener(this);
JPanel chl = new JPanel();
chl.add(lblchlname);
txtchlname.setText(null);
chl.add(txtchlname);
chl.add(lblchs);
txtchs.setText(null);
chl.add(txtchs);
txtchlname.addActionListener(this);
txtchs.addActionListener(this);
tabbedPane.addTab("Queues", queue);
tabbedPane.addTab("Channels", chl);
subframe.getContentPane().add(tabbedPane);
subframe.getContentPane().add(jp);
tabbedPane.setVisible(true);
subframe.setVisible(true);
}
public static void main(String[] args)
{SwingUtilities.invokeLater(new Runnable(){ public void run() { #SuppressWarnings("unused") MainFrame m = new MainFrame();}});}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == QMGR1|| e.getSource() == QMGR2)
{createSubframe();}
if (e.getSource() == txtqname){qname = txtqname.getText();}
if (e.getSource() == txtqcurdfil)
{
cdepth = Integer.parseInt(txtqcurdfil.getText());
cmdissue = "qn has value messages";
cmdissue = cmdissue.replace("qn", ""+qname+"");
cmdissue = cmdissue.replace("value", ""+cdepth+"");
System.out.println(cmdissue);
cmdissue = null;
}
if (e.getSource() == txtchlname){chlname = txtchlname.getText(); chlname=null;}
if (e.getSource() == txtchs)
{
chlstatus = txtchs.getText();
cmdissue = "chln is chls";
cmdissue = cmdissue.replace("chln", ""+chlname+"");
cmdissue = cmdissue.replace("chls", ""+chlstatus+"");
System.out.println(cmdissue);
}
}
}
I'm getting the expected outcome for the code:
Running for first time
Say I close this object choice panel and open a new instance, irrespective of which choice I make the command runs twice:
Running for the second time
The iteration repeats. Say I make a choice for the fourth or fifth time, the command runs 4/5 times.
I understood the fact that the somehow it is initializing the objects for the number of times I run it, and it needs to be reset after I close the panel. But I'm not sure how/where to get this done.
Apologies for the lengthy code posted, since I wanted to be sure that people can point the mistake that has been committed.
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 1;
p.add(QMGR1, gbc_QMGR1);
QMGR1.addActionListener(this);
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 2;
p.add(QMGR1, gbc_QMGR1);
QMGR1.addActionListener(this);
Looks like you are trying to add the same component to the panel twice in two different grid locations. You can't do this.
You need to:
create two different component, or
get rid of one of the components.
Edit:
JButton QMGR1 = new JButton("QMGR1");
JButton QMGR2 = new JButton("QMGR2");
You create the buttons as instance variables.
But then in the makeQAPanel() method you add the actionListener to the button.
QMGR1.addActionListener(this);
...
QMGR2.addActionListener(this);
So every time you invoke that method the actionListener gets added again.
The actionListener should be added in the constructor of you class so it is only added once.
#jesper,
someone explained to me the constructor part of it:
package testbox;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class MainFrame extends JFrame implements ActionListener
{
JLabel lblqname = new JLabel("Please enter the queue name");
JTextField txtqname = new JTextField(25);
JLabel lblqcur = new JLabel("where curdeth greater than");
JTextField txtqcurdfil = new JTextField(5);
JLabel lblchlname = new JLabel("Please enter the Channel name");
JTextField txtchlname = new JTextField(30);
JLabel lblchs = new JLabel("where status is: ");
JTextField txtchs = new JTextField(8);
public String ID;
public String pwdValue;
public String qname;
public int cdepth;
public String chlname;
public String chlstatus;
public String cmdissue;
JTextArea out = new JTextArea();
JButton QMGR1 = new JButton("QMGR1");
JButton QMGR2 = new JButton("QMGR2");
public MainFrame()
{
QMGR1.addActionListener(this);
QMGR2.addActionListener(this);
txtqname.addActionListener(this);
txtqcurdfil.addActionListener(this);
txtchlname.addActionListener(this);
txtchs.addActionListener(this);
JLabel jUserName = new JLabel("ID");
JTextField userName = new JTextField();
JLabel jPassword = new JLabel("Password");
JTextField password = new JPasswordField();
Object[] ob = {jUserName, userName, jPassword, password};
int result = JOptionPane.showConfirmDialog(null, ob, "Please input password for Login", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
ID = userName.getText();
pwdValue = password.getText();
final JFrame frame = new JFrame("Environment Choice");
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("QAQmgrList", makeQAPanel());
frame.getContentPane().add(tabbedPane);
}
}
public JPanel makeQAPanel()
{
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 1;
p.add(QMGR1, gbc_QMGR1);
GridBagConstraints gbc_QMGR2 = new GridBagConstraints();
gbc_QMGR2.insets = new Insets(0, 0, 5, 5);
gbc_QMGR2.gridx = 1;
gbc_QMGR2.gridy = 2;
p.add(QMGR2, gbc_QMGR2);
return p;
}
public void createSubframe()
{
final JFrame subframe = new JFrame("Object Choice");
subframe.setSize(1000, 500);
subframe.getContentPane().setLayout(new GridLayout(1, 1));
out.setText(null);
out.setLineWrap(true);
out.setCaretPosition(out.getDocument().getLength());
out.setEditable (false);
JScrollPane jp = new JScrollPane(out);
jp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel queue = new JPanel();
queue.add(lblqname);
txtqname.setText(null);
queue.add(txtqname);
queue.add(lblqcur);
txtqcurdfil.setText(null);
queue.add(txtqcurdfil);
JPanel chl = new JPanel();
chl.add(lblchlname);
txtchlname.setText(null);
chl.add(txtchlname);
chl.add(lblchs);
txtchs.setText(null);
chl.add(txtchs);
tabbedPane.addTab("Queues", queue);
tabbedPane.addTab("Channels", chl);
subframe.getContentPane().add(tabbedPane);
subframe.getContentPane().add(jp);
tabbedPane.setVisible(true);
subframe.setVisible(true);
}
public static void main(String[] args)
{SwingUtilities.invokeLater(new Runnable(){ public void run() { #SuppressWarnings("unused") MainFrame m = new MainFrame();}});}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == QMGR1|| e.getSource() == QMGR2)
{createSubframe();}
if (e.getSource() == txtqname){qname = txtqname.getText();}
if (e.getSource() == txtqcurdfil)
{
cdepth = Integer.parseInt(txtqcurdfil.getText());
cmdissue = "qn has value messages";
cmdissue = cmdissue.replace("qn", ""+qname+"");
cmdissue = cmdissue.replace("value", ""+cdepth+"");
System.out.println(cmdissue);
cmdissue = null;
}
if (e.getSource() == txtchlname){chlname = txtchlname.getText(); chlname=null;}
if (e.getSource() == txtchs)
{
chlstatus = txtchs.getText();
cmdissue = "chln is chls";
cmdissue = cmdissue.replace("chln", ""+chlname+"");
cmdissue = cmdissue.replace("chls", ""+chlstatus+"");
System.out.println(cmdissue);
}
}
}
Worked like a charm.. THanks for pointing it out

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:

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