Commands are running twice in Java actionperformed - java

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

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:

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
}

Moving from one frame to another in java swing

I'm just making a small application on window builder and need some help with it. I've made 2 frames individually and I don't know how to specify the action of the button in such a way that when I click on the 'next' botton in the first frame, I want it to move to the second frame.
Here's the source code for each file.
first.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.JTextArea;
import java.awt.Font;
import java.awt.event.ActionListener;
public class first extends JFrame {
private JPanel contentPane;
private final Action action = new SwingAction();
private final Action action_1 = new SwingAction();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
first frame = new first();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public first() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNext.setAction(action_1);
btnNext.setBounds(257, 228, 55, 23);
contentPane.add(btnNext);
JButton btnExit = new JButton("Exit");
btnExit.setBounds(344, 228, 51, 23);
contentPane.add(btnExit);
JRadioButton rdbtnAdd = new JRadioButton("Add");
rdbtnAdd.setBounds(27, 80, 109, 23);
contentPane.add(rdbtnAdd);
JRadioButton rdbtnDelete = new JRadioButton("Delete");
rdbtnDelete.setBounds(27, 130, 109, 23);
contentPane.add(rdbtnDelete);
JRadioButton rdbtnEdit = new JRadioButton("Edit");
rdbtnEdit.setBounds(27, 180, 109, 23);
contentPane.add(rdbtnEdit);
JLabel lblSelectAnOption = new JLabel("Select an Option");
lblSelectAnOption.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblSelectAnOption.setBounds(27, 36, 121, 23);
contentPane.add(lblSelectAnOption);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Next");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
new second_add();
}
}
}
second.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import java.awt.event.ActionListener;
public class second_add extends JFrame {
private JPanel contentPane;
private JTextField txtTypeYourQuestion;
private JTextField txtQuestionWeight;
private JTextField txtEnter;
private JTextField txtEnter_1;
private JTextField txtValue;
private JTextField txtValue_1;
private final Action action = new SwingAction();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
second_add frame = new second_add();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public second_add() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtTypeYourQuestion = new JTextField();
txtTypeYourQuestion.setBounds(22, 11, 177, 20);
txtTypeYourQuestion.setText("Type your Question Here");
contentPane.add(txtTypeYourQuestion);
txtTypeYourQuestion.setColumns(10);
txtQuestionWeight = new JTextField();
txtQuestionWeight.setBounds(209, 11, 86, 20);
txtQuestionWeight.setText("Question weight");
contentPane.add(txtQuestionWeight);
txtQuestionWeight.setColumns(10);
txtEnter = new JTextField();
txtEnter.setBounds(22, 55, 86, 20);
txtEnter.setText("Enter . . .");
contentPane.add(txtEnter);
txtEnter.setColumns(10);
txtEnter_1 = new JTextField();
txtEnter_1.setText("Enter . . . ");
txtEnter_1.setBounds(22, 104, 86, 20);
contentPane.add(txtEnter_1);
txtEnter_1.setColumns(10);
txtValue = new JTextField();
txtValue.setText("Value . .");
txtValue.setBounds(118, 55, 51, 20);
contentPane.add(txtValue);
txtValue.setColumns(10);
txtValue_1 = new JTextField();
txtValue_1.setText("Value . .");
txtValue_1.setBounds(118, 104, 51, 20);
contentPane.add(txtValue_1);
txtValue_1.setColumns(10);
JButton btnFinish = new JButton("Finish");
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnFinish.setAction(action);
btnFinish.setBounds(335, 228, 89, 23);
contentPane.add(btnFinish);
JButton btnAddChoice = new JButton("Add choice");
btnAddChoice.setBounds(236, 228, 89, 23);
contentPane.add(btnAddChoice);
JButton btnAddQuestion = new JButton("Add question");
btnAddQuestion.setBounds(136, 228, 89, 23);
contentPane.add(btnAddQuestion);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
}
Having multiple JFrame instances in one application is bad usability
Consider using something like a CardLayout instead.
Modify like this-
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
second_add second = new second_add();
setVisible(false); // Hide current frame
second.setVisible(true);
}
});
You can navigate to a frame by creating its object and using setVisible method to display it. If you want to do it on a button click, write it inside its event handler.
JFrame o = new JFrame();
o.setVisible(true);
dispose(); // This will close the current frame
The quick and dirty solution would to set the first frame's visibility to false and the second frames visibility to true in your buttonclick action. (see Sajal Dutta's answer)
But to have a consistent behaviour even for more than 2 frames, let each frame be stored in a HashTable in your main class (class holding the main method and not extending JFrame) with the ID being the order of the frame (first frame D 1, second: ID 2, etc.).
Then create a static method
public void switchFrame(JFrame originatingFrame, int NextFrame){
originatingFrame.this.setVisible(false);
((JFrame) myHashTable.get(NextFrame)).setVisible(true);
}
in your main class which can be called from each frame using
mainClass.switchFrame(this, IdOfFrameYouWantToGoTo);
that way you can also implement "Back"- and "Skip"-Buttons should you want to create something like a wizard.
NOTE: I did not test this code. This should just be seen as a general overview of how to do this.
The below piece of code will show to navigate from one page to another page in a menu format.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class AddressBookDemo implements ActionListener, Runnable {
ArrayList personsList;
PersonDAO pDAO;
Panel panel;
JFrame appFrame;
JLabel jlbName, jblPassword, jlbAddress;
JPasswordField jPassword;
JTextField jtfName, jtfAddress;
JButton jbbSave, jbnClear, jbnExit, btnNext, button;
String name, address, password;
final int CARDS = 4;
CardLayout cl = new CardLayout();
JPanel cardPanel = new JPanel(cl);
CardLayout c2 = new CardLayout();
JPanel cardPanel2 = new JPanel(c2);
int currentlyShowing = 0;
Thread errorThrower;
// int phone;
// int recordNumber; // used to naviagate using >> and buttons
Container cPane;
Container cPane2;
private JFrame frame;
private TextArea textArea;
private Thread reader;
private Thread reader2;
private boolean quit;
private final PipedInputStream pin = new PipedInputStream();
private final PipedInputStream pin2 = new PipedInputStream();
public static void main(String args[]) {
new AddressBookDemo();
}
public AddressBookDemo() {
name = "";
password = "";
address = "";
// phone = -1; //Stores 0 to indicate no Phone Number
// recordNumber = -1;
createGUI();
personsList = new ArrayList();
// creating PersonDAO object
pDAO = new PersonDAO();
}
public void createGUI() {
/* Create a frame, get its contentpane and set layout */
appFrame = new JFrame("ManualDeploy ");
cPane = appFrame.getContentPane();
cPane.setLayout(new GridBagLayout());
// frame=new JFrame("Java Console");
textArea=new TextArea();
textArea.setEditable(false);
Button button=new Button("clear");
panel=new Panel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
panel.add(textArea,gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx03.gridy = 1;
panel.add(button,gridBagConstraintsx03);
// frame.add(panel);
// frame.setVisible(true);
// cPane2 = frame.getContentPane();
// cPane2.setLayout(new GridBagLayout());
button.addActionListener(this);
try
{
PipedOutputStream pout=new PipedOutputStream(this.pin);
System.setOut(new PrintStream(pout,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
}
try
{
PipedOutputStream pout2=new PipedOutputStream(this.pin2);
System.setErr(new PrintStream(pout2,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
}
quit=false; // signals the Threads that they should exit
// Starting two seperate threads to read from the PipedInputStreams
//
reader=new Thread(this);
reader.setDaemon(true);
reader.start();
//
reader2=new Thread(this);
reader2.setDaemon(true);
reader2.start();
// testing part
// you may omit this part for your application
//
System.out.println("Hello World 2");
System.out.println("All fonts available to Graphic2D:\n");
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames=ge.getAvailableFontFamilyNames();
for(int n=0;n<fontNames.length;n++) System.out.println(fontNames[n]);
// Testing part: simple an error thrown anywhere in this JVM will be printed on the Console
// We do it with a seperate Thread becasue we don't wan't to break a Thread used by the Console.
System.out.println("\nLets throw an error on this console");
errorThrower=new Thread(this);
errorThrower.setDaemon(true);
errorThrower.start();
arrangeComponents();
// arrangeComponents2();
final int CARDS = 2;
final CardLayout cl = new CardLayout();
final JPanel cardPanel = new JPanel(cl);
JMenu menu = new JMenu("M");
for (int x = 0; x < CARDS; x++) {
final int SELECTION = x;
JPanel jp = new JPanel();
if (x == 0) {
jp.add(cPane);
} else if (x == 1) {
jp.add(panel);
} else if (x == 2)
jp.add(new JButton("Panel 2"));
else
jp.add(new JComboBox(new String[] { "Panel 3" }));
cardPanel.add("" + SELECTION, jp);
JMenuItem menuItem = new JMenuItem("Show Panel " + x);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
currentlyShowing = SELECTION;
cl.show(cardPanel, "" + SELECTION);
}
});
menu.add(menuItem);
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
btnNext = new JButton("Next >>");
JButton btnPrev = new JButton("<< Previous");
JPanel p = new JPanel(new GridLayout(1, 2));
p.add(btnPrev);
p.add(btnNext);
btnNext.setVisible(false);
JFrame f = new JFrame();
f.getContentPane().add(cardPanel);
f.getContentPane().add(p, BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.setJMenuBar(menuBar);
f.setVisible(true);
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (currentlyShowing < CARDS - 1) {
cl.next(cardPanel);
currentlyShowing++;
}
}
});
btnPrev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (currentlyShowing > 0) {
cl.previous(cardPanel);
currentlyShowing--;
}
}
});
}
public void arrangeComponents() {
jlbName = new JLabel("Username");
jblPassword = new JLabel("Password");
jlbAddress = new JLabel("Sftpserver");
jtfName = new JTextField(20);
jPassword = new JPasswordField(20);
jtfAddress = new JTextField(20);
jbbSave = new JButton("move sftp");
jbnClear = new JButton("Clear");
jbnExit = new JButton("Exit");
/* add all initialized components to the container */
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
cPane.add(jlbName, gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
gridBagConstraintsx02.gridx = 1;
gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx02.gridy = 0;
gridBagConstraintsx02.gridwidth = 2;
gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
cPane.add(jtfName, gridBagConstraintsx02);
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx03.gridy = 1;
cPane.add(jblPassword, gridBagConstraintsx03);
GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
gridBagConstraintsx04.gridx = 1;
gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx04.gridy = 1;
gridBagConstraintsx04.gridwidth = 2;
gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
cPane.add(jPassword, gridBagConstraintsx04);
GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints();
gridBagConstraintsx05.gridx = 0;
gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx05.gridy = 2;
cPane.add(jlbAddress, gridBagConstraintsx05);
GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints();
gridBagConstraintsx06.gridx = 1;
gridBagConstraintsx06.gridy = 2;
gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx06.gridwidth = 2;
gridBagConstraintsx06.fill = GridBagConstraints.BOTH;
cPane.add(jtfAddress, gridBagConstraintsx06);
GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
gridBagConstraintsx09.gridx = 0;
gridBagConstraintsx09.gridy = 4;
gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5);
cPane.add(jbbSave, gridBagConstraintsx09);
GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints();
gridBagConstraintsx10.gridx = 1;
gridBagConstraintsx10.gridy = 4;
gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnClear, gridBagConstraintsx10);
GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints();
gridBagConstraintsx11.gridx = 2;
gridBagConstraintsx11.gridy = 4;
gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnExit, gridBagConstraintsx11);
jbbSave.addActionListener(this);
// jbnDelete.addActionListener(this);
jbnClear.addActionListener(this);
jbnExit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("inside button123");
if (e.getSource() == jbbSave) {
savePerson();
} else if (e.getSource() == jbnClear) {
clear();
} else if (e.getSource() == jbnExit) {
System.exit(0);
}
else if (e.getSource() == button)
{
System.out.println("inside button");
textArea.setText(" ");
}
}
// Save the Person into the Address Book
public void savePerson() {
name = jtfName.getText();
password = jPassword.getText();
address = jtfAddress.getText();
if (name.equals("")) {
JOptionPane.showMessageDialog(null, "Please enter password",
"ERROR", JOptionPane.ERROR_MESSAGE);
} else if (password != null && password.isEmpty()) {
JOptionPane.showMessageDialog(null, "Please enter password",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
else {
btnNext.setVisible(true);
JOptionPane.showMessageDialog(null, "Person Saved");
}
}
public void clear() {
jtfName.setText("");
jPassword.setText("");
jtfAddress.setText("");
personsList.clear();
}
public synchronized void run()
{
try
{
while (Thread.currentThread()==reader)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin.available()!=0)
{
String input=this.readLine(pin);
textArea.append(input);
}
if (quit) return;
}
while (Thread.currentThread()==reader2)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin2.available()!=0)
{
String input=this.readLine(pin2);
textArea.append(input);
}
if (quit) return;
}
} catch (Exception e)
{
textArea.append("\nConsole reports an Internal error.");
textArea.append("The error is: "+e);
}
// just for testing (Throw a Nullpointer after 1 second)
// if (Thread.currentThread()==errorThrower)
// {
// try { this.wait(1000); }catch(InterruptedException ie){}
// throw new NullPointerException("Application test: throwing an NullPointerException It should arrive at the console");
// }
}
public synchronized String readLine(PipedInputStream in) throws IOException
{
String input="";
do
{
int available=in.available();
if (available==0) break;
byte b[]=new byte[available];
in.read(b);
input=input+new String(b,0,b.length);
}while( !input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
return input;
}
public synchronized void windowClosed(WindowEvent evt)
{
quit=true;
this.notifyAll(); // stop all threads
try { reader.join(1000);pin.close(); } catch (Exception e){}
try { reader2.join(1000);pin2.close(); } catch (Exception e){}
System.exit(0);
}
}

Categories

Resources