Java Swing GridLayout not looking like I expect it to - java

I have a GUI that is a grid layout with 6 rows and 4 columns, the order should go:
Label - RadioButton - RadioButton - ComboBox
This is successful for the first row. However each row afterwards is messed up. Please refer to the image of the GUI.
Please disregard the commented code as I am going to be setting the visibility later once I complete the GUI layout. Thanks.
JFrame frame = new JFrame("Zoho DNC List Updater");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(height, width);
// creating menu bar
JMenuBar mb = new JMenuBar();
// mb.setLayout(new FlowLayout());
JMenu m1 = new JMenu("File");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem contact = new JMenuItem("Contact Us");
JMenuItem help = new JMenuItem("Help");
JMenuItem openFile = new JMenuItem("Open File");
JMenuItem saveFile = new JMenuItem("Save File");
JMenuItem newWindow = new JMenuItem("New window");
m2.add(contact);
m2.add(help);
m1.add(openFile);
m1.add(saveFile);
m1.add(newWindow);
JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Update Records");
// JTextField tf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Update");
JButton reset = new JButton("Quit");
panel.add(label); // Components Added using Flow Layout
// panel.add(tf);
panel.add(send);
panel.add(reset);
JPanel panel2 = new JPanel(new GridLayout(6, 4));
JRadioButton radio1 = new JRadioButton("Yes");
JRadioButton radio2 = new JRadioButton("No");
JLabel custom = new JLabel("Customize Call Report?");
ButtonGroup btnGrp = new ButtonGroup();
radio1.setBounds(120, 30, 120, 50);
radio2.setBounds(120, 30, 120, 50);
custom.setBounds(120, 30, 120, 50);
btnGrp.add(radio1);
btnGrp.add(radio2);
JComboBox campsList = new JComboBox(camps);
campsList.setSelectedIndex(5);
campsList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent r){
JComboBox cb = (JComboBox)r.getSource();
String campName = (String)cb.getSelectedItem();
}
});
JComboBox inboundsList = new JComboBox(inbounds);
inboundsList.setSelectedIndex(5);
inboundsList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent r){
JComboBox cb = (JComboBox)r.getSource();
String campName = (String)cb.getSelectedItem();
}
});
JComboBox statList = new JComboBox(stat);
statList.setSelectedIndex(5);
statList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent r){
JComboBox cb = (JComboBox)r.getSource();
String campName = (String)cb.getSelectedItem();
}
});
JComboBox groupList = new JComboBox(groups);
groupList.setSelectedIndex(5);
groupList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent r){
JComboBox cb = (JComboBox)r.getSource();
String campName = (String)cb.getSelectedItem();
}
});
JComboBox lisList = new JComboBox(lis);
lisList.setSelectedIndex(5);
lisList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent r){
JComboBox cb = (JComboBox)r.getSource();
String campName = (String)cb.getSelectedItem();
}
});
ButtonGroup btnGrp1 = new ButtonGroup();
JRadioButton campaignY = new JRadioButton("Yes");
JRadioButton campaignN = new JRadioButton("No");
JLabel campaign = new JLabel("Select all campaigns?");
campaignY.setBounds(120, 30, 120, 50);
campaignN.setBounds(120, 30, 120, 50);
btnGrp1.add(campaignY);
btnGrp1.add(campaignN);
ButtonGroup btnGrp2 = new ButtonGroup();
JRadioButton inboundY = new JRadioButton("Yes");
JRadioButton inboundN = new JRadioButton("No");
JLabel inbound = new JLabel("Select all inbound groups?");
btnGrp2.add(inboundY);
btnGrp2.add(inboundN);
ButtonGroup btnGrp3 = new ButtonGroup();
JRadioButton statusY = new JRadioButton("Yes");
JRadioButton statusN = new JRadioButton("No");
JLabel status = new JLabel("Select all call statuses?");
btnGrp3.add(statusY);
btnGrp3.add(statusN);
statusY.setBounds(120, 30, 120, 50);
statusN.setBounds(120, 30, 120, 50);
ButtonGroup btnGrp4 = new ButtonGroup();
JRadioButton userGroupY = new JRadioButton("Yes");
JRadioButton userGroupN = new JRadioButton("No");
JLabel userGroup = new JLabel("Select all user groups?");
btnGrp4.add(userGroupY);
btnGrp4.add(userGroupN);
userGroupY.setBounds(120, 30, 120, 50);
userGroupN.setBounds(120, 30, 120, 50);
ButtonGroup btnGrp5 = new ButtonGroup();
JRadioButton listsY = new JRadioButton("Yes");
JRadioButton listsN = new JRadioButton("No");
JLabel lists = new JLabel("Select all lists?");
btnGrp5.add(listsY);
btnGrp5.add(listsN);
panel2.add(custom);
panel2.add(radio1);
panel2.add(radio2);
campsList.setVisible(true);
panel2.add(campsList);
panel2.add(campaign);
panel2.add(campaignY);
panel2.add(campaignN);
inboundsList.setVisible(true);
panel2.add(inboundsList);
// campaign.setVisible(false);
// campaignY.setVisible(false);
// campaignN.setVisible(false);
panel2.add(status);
panel2.add(statusY);
panel2.add(statusN);
panel2.add(statList);
// status.setVisible(false);
// statusY.setVisible(false);
// statusN.setVisible(false);
panel2.add(inbound);
panel2.add(inboundY);
panel2.add(inboundN);
panel2.add(inboundsList);
// inbound.setVisible(false);
// inboundN.setVisible(false);
// inboundY.setVisible(false);
panel2.add(userGroup);
panel2.add(userGroupY);
panel2.add(userGroupN);
panel2.add(groupList);
// userGroup.setVisible(false);
// userGroupN.setVisible(false);
// userGroupY.setVisible(false);
panel2.add(lists);
panel2.add(listsY);
panel2.add(listsN);
panel2.add(lisList);
// lists.setVisible(false);
// listsN.setVisible(false);
// listsY.setVisible(false);

So, there are two issues.
First, when both the column and row properties are specified, the column value is ignore, as you can find in the JavaDocs
When both the number of rows and the number of columns have been set to non-zero values, either by a constructor or by the setRows and setColumns methods, the number of columns specified is ignored. Instead, the number of columns is determined from the specified number of rows and the total number of components in the layout.
So, in your case, I changed it to JPanel panel2 = new JPanel(new GridLayout(0, 4));
Second, an instance component may only reside in a single parent, once.
panel2.add(custom);
panel2.add(radio1);
panel2.add(radio2);
panel2.add(campsList);
panel2.add(campaign);
panel2.add(campaignY);
panel2.add(campaignN);
panel2.add(inboundsList);
//...
panel2.add(inbound);
panel2.add(inboundY);
panel2.add(inboundN);
panel2.add(inboundsList);
You're adding inboundsList twice, this has the effect of first removing it from the container and then re-adding it at the new position.
You will need to create a new instance of the of the JComoboBox with the same data model

Related

Place label for text box above the box and not to the side

As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);

access input that get from user in UI in java and show them in console

i want save input that i get from user and save them in element .
i want to access elements that user write in my UI.
and if i want save the elements in array list which kind of array list i should build.
in my UI i have text field name and text field middle name and combo box city has got 3 city name and and a radio box that it depend sex.
in final show them in console what should i do ?
this all of my code:
package ui;
import java.awt.*;
import javax.swing.*;
public class UI extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(500, 600);
BorderLayout blayout = new BorderLayout();
JButton center = new JButton();
JButton north = new JButton();
JButton south = new JButton();
JComboBox combo = new JComboBox();
combo.addItem("-");
combo.addItem("Tehran");
combo.addItem("Tabriz");
combo.addItem("Shiraz");
JRadioButton rb1 = new JRadioButton("man");
JRadioButton rb2 = new JRadioButton("weman");
frame.setLayout(blayout);
FlowLayout fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
JLabel jb1 = new JLabel("Name :");
JTextField name = new JTextField(20);
center.add(jb1);
center.add(name);
JLabel jb2 = new JLabel("Family :");
JTextField family = new JTextField(20);
center.add(jb2);
center.add(family);
JLabel jb4 = new JLabel("City :");
center.add(jb4);
center.add(combo);
JLabel jb5 = new JLabel("Sex :");
center.add(jb5);
center.add(rb1);
center.add(rb2);
JLabel jb6 = new JLabel("Comment :");
JTextField comment = new JTextField(50);
JLabel jb7 = new JLabel("Save");
south.add(jb7);
JPanel cpanel = new JPanel();
cpanel.add(center);
JPanel spanel = new JPanel();
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
cpanel.add(jb6);
cpanel.add(comment);
frame.add(cpanel,BorderLayout.CENTER);
frame.add(spanel,BorderLayout.SOUTH);
}
}
You need to use listeners to create code that runs when ui component is pressed. I added listener to every component. try it:
public class UI extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout blayout = new BorderLayout();
JButton center = new JButton();
JButton north = new JButton();
JButton south = new JButton();
south.addActionListener(e->{System.out.println("Save button is pressed");});
JComboBox combo = new JComboBox();
combo.addItem("-");
combo.addItem("Tehran");
combo.addItem("Tabriz");
combo.addItem("Shiraz");
combo.addActionListener(e -> {
System.out.println(((JComboBox<String>) e.getSource()).getSelectedItem());
});
JRadioButton rb1 = new JRadioButton("man");
rb1.addActionListener(e -> {
System.out.println("man: " + ((JRadioButton) e.getSource()).isSelected());
});
JRadioButton rb2 = new JRadioButton("weman");
rb2.addActionListener(e -> {
System.out.println("weman: " + ((JRadioButton) e.getSource()).isSelected());
});
frame.setLayout(blayout);
FlowLayout fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
JLabel jb1 = new JLabel("Name :");
JTextField name = new JTextField(20);
center.add(jb1);
center.add(name);
name.addActionListener(e -> {
System.out.println("name: " + ((JTextField) e.getSource()).getText());
});
JLabel jb2 = new JLabel("Family :");
JTextField family = new JTextField(20);
center.add(jb2);
center.add(family);
family.addActionListener(e -> {
System.out.println("family: " + ((JTextField) e.getSource()).getText());
});
JLabel jb4 = new JLabel("City :");
center.add(jb4);
center.add(combo);
JLabel jb5 = new JLabel("Sex :");
center.add(jb5);
center.add(rb1);
center.add(rb2);
JLabel jb6 = new JLabel("Comment :");
JTextField comment = new JTextField(50);
comment.addActionListener(e -> {
System.out.println("comment: " + ((JTextField) e.getSource()).getText());
});
JLabel jb7 = new JLabel("Save");
south.add(jb7);
JPanel cpanel = new JPanel();
cpanel.add(center);
JPanel spanel = new JPanel();
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
cpanel.add(jb6);
cpanel.add(comment);
frame.add(cpanel, BorderLayout.CENTER);
frame.add(spanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
You will have to put JRadioButton into RadioGroup to select one of them.
At first, you need to check your GUI, because from skimming it works not good. Later you can get data from the different component using an appropriate listener for each component or you can use any General button to reading data from all components and print it in a console or anywhere else.
To get data from combo, for example, will be here:
String data = combo.getSelectedIndex();
More information you can get here:
How can I get the user input in Java?

BoxLayout Left Alignment

I'm trying to left align the class and neutral buttons so they are in line with the left most card button. For some reason, setAlignmentX only shifts the buttons half way. Here is the code. Is there away to align the buttons?
private String[] listEntries = {"a","a","a","a","a"};
private JButton remove = new JButton("Remove");
private JList list;
private JButton b1 = new JButton("Class");
private JButton b2 = new JButton("Neutral");
private JPanel page = new JPanel(new CardLayout());
private DefaultListModel listModel = new DefaultListModel();
public Main () {
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel,BoxLayout.PAGE_AXIS));
leftPanel.setLayout(new BoxLayout(leftPanel,BoxLayout.PAGE_AXIS));
rightPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
leftPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel title = new JLabel("Deck Constructor", SwingConstants.CENTER);
title.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
//Set up Deck List
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisibleRowCount(-1);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(150, 80));
JLabel listTitle = new JLabel("List");
listTitle.setLabelFor(list);
listScroller.setAlignmentX(LEFT_ALIGNMENT);
rightPanel.add(listTitle);
rightPanel.add(listScroller);
rightPanel.add(remove);
//Set up Card Selection
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
b1.setActionCommand("Class");
b2.setActionCommand("Neutral");
b1.addActionListener(this);
b2.addActionListener(this);
buttonPanel.add(b1);
buttonPanel.add(b2);
JPanel classCards = new JPanel(new GridLayout(2,3, 10, 10));
JButton card1 = new JButton("Card 1");
card1.addActionListener(this);
card1.setActionCommand("addCard");
JButton card2 = new JButton("Card 2");
JButton card3 = new JButton("Card 3");
JButton card4 = new JButton("Card 4");
JButton card5 = new JButton("Card 5");
JButton card6 = new JButton("Card 6");
classCards.add(card1);
classCards.add(card2);
classCards.add(card3);
classCards.add(card4);
classCards.add(card5);
classCards.add(card6);
JPanel neutral = new JPanel();
neutral.setBackground(Color.BLUE);
page.add(classCards, "Class");
page.add(neutral, "Neutral");
leftPanel.add(buttonPanel);
leftPanel.add(page);
setPreferredSize(new Dimension(640,640/12*9));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(leftPanel,BorderLayout.CENTER);
getContentPane().add(rightPanel,BorderLayout.EAST);
getContentPane().add(title,BorderLayout.NORTH);
pack();
setVisible(true);
}
It is not perfect solution, but you can use for example:
If you want to keep buttons default size:
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING,1,2));
and delete:
buttonPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
If you want to fill buttonPanel with buttons:
JPanel buttonPanel = new JPanel(new GridLayout(1,2,2,2));
buttonPanel.setBorder(new EmptyBorder(2,1,2,1));
In (FlowLayout.LEADING,1,2) and in EmptyBorder(2,1,2,1))the 1,2 values are added to match buttonPanel and classCard hgap and vgap.

How do i display the radiobutton and label in the same row?

private String[] gender = {"Male","Female"};
private JComboBox jco = new JComboBox();
private JRadioButton[] jrbGender;
private ButtonGroup buttonGroup = new ButtonGroup();
private JButton jbtAdd = new JButton("Create");
private JButton jbtRetrieve = new JButton("Retrieve");
private JButton jbtUpdate = new JButton("Update");
private JButton jbtDelete = new JButton("Delete");
public RegistrationForMembership(){
JPanel jp1 = new JPanel(new GridLayout(6,2));
JPanel jp2 = new JPanel(new FlowLayout());
JPanel jp3 = new JPanel(new GridLayout(1,1));
jco = new JComboBox(membership);
jrbGender = new JRadioButton[gender.length];
add(jp1);
jp1.add(new JLabel("Member ID"));
jp1.add(jtfID);
jp1.add(new JLabel("Member Name"));
jp1.add(jtfName);
jp1.add(new JLabel("Member IC"));
jp1.add(jtfIC);
jp1.add(new JLabel("Address"));
jp1.add(jtfAddress);
jp1.add(new JLabel("Gender"));
for(int i =0; i<gender.length;++i){
jrbGender[i] = new JRadioButton(gender[i]);
buttonGroup.add(jrbGender[i]);
jp1.add(jrbGender[i]);
}
add(jp1);
The one of the radio button will go to the next line , how do i let the radio button on the same line with the label ?
Add the JRadioButtons to a new JPanel and add that one to jp1.
JPanel radios = new JPanel();
for (int i = 0; i < gender.length; ++i){
jrbGender[i] = new JRadioButton(gender[i]);
buttonGroup.add(jrbGender[i]);
radios.add(jrbGender[i]);
}
jp1.add(radios);
Also, it looks like jp1 should have 5 rows, not 6.
JPanel jp1 = new JPanel(new GridLayout(5,2));

JButton exits JPanel

I have multiple cancel, ok, and save buttons. When the user clicks one of these buttons, I need it to exit the JPanel, but not the whole program. I have tried multiple times and everything I do it exits the whole program. My code is below. I know there is a lot of stuff on my code and it can get confusing. Thanks in advance.
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestApplication implements ActionListener {
public static void main(String[] args) {
JLabel input = new JLabel();
final JFrame frame = new JFrame();
frame.setSize(1000, 1000);
frame.setTitle("RBA Test Application");
frame.add(input);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// Make all necessary buttons
JButton next = new JButton("Next");
JButton save = new JButton("Save");
JButton save2 = new JButton("Save");
JButton save3 = new JButton("Save");
JButton save4 = new JButton("Save");
JButton aok = new JButton("OK");
JButton bok = new JButton("OK");
JButton cok = new JButton("OK");
JButton acancel = new JButton("Cancel");
JButton bcancel = new JButton("Cancel");
JButton ccancel = new JButton("Cancel");
JButton dcancel = new JButton("Cancel");
JButton ecancel = new JButton("Cancel");
JButton fcancel = new JButton("Cancel");
JButton gcancel = new JButton("Cancel");
JButton hcancel = new JButton("Cancel");
//Make the drop down lists
String[] baudrates = {"57600", "115200", "128000", "256000"};
JComboBox baudlist = new JComboBox(baudrates);
String[] baudrates2 = {"57600", "115200", "128000", "256000"};
JComboBox baudlist2 = new JComboBox(baudrates2);
String[] bytesizes = {"7", "8"};
JComboBox bytelist = new JComboBox(bytesizes);
String[] bytesizes2 = {"7", "8"};
JComboBox bytelist2 = new JComboBox(bytesizes2);
String[] stopbit = {"1", "2"};
JComboBox stoplist = new JComboBox(stopbit);
String[] stopbit2 = {"1", "2"};
JComboBox stoplist2 = new JComboBox(stopbit2);
String[] flows = {"None", "Hardware","Xon", "Xoff"};
JComboBox flowlist = new JComboBox(flows);
String[] flows2 = {"None", "Hardware","Xon", "Xoff"};
JComboBox flowlist2 = new JComboBox(flows2);
String[] paritys = {"None", "Even", "Odd"};
JComboBox paritylist = new JComboBox(paritys);
String[] paritys2 = {"None", "Even", "Odd"};
JComboBox paritylist2 = new JComboBox(paritys2);
//Make all necessary labels
JLabel cardLabel = new JLabel("Card Number: ");
JLabel expLabel = new JLabel("Exp. Date (MM/YY): ");
JLabel cvvLabel = new JLabel("CVV: ");
JLabel ipLabel = new JLabel("IP Address: ");
JLabel connectLabel = new JLabel("Connect Time: ");
JLabel sendLabel = new JLabel("Send Time Out: ");
JLabel receiveLabel = new JLabel("Receive Time Out: ");
JLabel portLabel = new JLabel("Port: ");
JLabel baudrate = new JLabel("Baud Rate: ");
JLabel bytesize = new JLabel("Byte Size: ");
JLabel stopbits = new JLabel("Stop Bits: ");
JLabel flow = new JLabel("Flow Con..: ");
JLabel parity = new JLabel("Parity: ");
JLabel stoLabel = new JLabel("Send Time Out: ");
JLabel rtoLabel = new JLabel("Receive Time Out: ");
JLabel portLabel2 = new JLabel("Port: ");
JLabel baudrate2 = new JLabel("Baud Rate: ");
JLabel bytesize2 = new JLabel("Byte Size: ");
JLabel stopbits2 = new JLabel("Stop Bits: ");
JLabel flow2 = new JLabel("Flow Con..: ");
JLabel parity2 = new JLabel("Parity: ");
JLabel stoLabel2 = new JLabel("Send Time Out: ");
JLabel rtoLabel2 = new JLabel("Receive Time Out: ");
JLabel portLabel3 = new JLabel("Port: ");
JLabel vendor = new JLabel("Vendor ID: ");
JLabel product = new JLabel("Product ID: ");
JLabel stoLabel3 = new JLabel("Send Time Out: ");
JLabel rtoLabel3 = new JLabel("Receive Time Out: ");
JLabel amountLabel = new JLabel("Amount: ");
JLabel textLabel = new JLabel("Display Text: ");
//Make all necessary TextFields
JTextField card = new JTextField(10);
JTextField expDate = new JTextField(10);
JTextField cvv = new JTextField(10);
JTextField ip = new JTextField(10);
JTextField ct = new JTextField(10);
JTextField rto = new JTextField(10);
JTextField sto = new JTextField(10);
JTextField port = new JTextField(10);
JTextField sendto = new JTextField(10);
JTextField reto = new JTextField(10);
JTextField comport = new JTextField(10);
JTextField sendto2 = new JTextField(10);
JTextField reto2 = new JTextField(10);
JTextField comport2 = new JTextField(10);
JTextField vendorid = new JTextField(10);
JTextField productid = new JTextField(10);
JTextField sendtime = new JTextField(10);
JTextField receiveto = new JTextField(10);
JTextField amountbox = new JTextField(10);
JTextField textBox = new JTextField(10);
JTextArea logbox = new JTextArea();
//Add components to the panels
final JPanel ethernetSettings = new JPanel();
ethernetSettings.setLayout(new GridLayout(6, 2));
ethernetSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
ethernetSettings.add(ipLabel);
ethernetSettings.add(ip);
ethernetSettings.add(connectLabel);
ethernetSettings.add(ct);
ethernetSettings.add(receiveLabel);
ethernetSettings.add(rto);
ethernetSettings.add(sendLabel);
ethernetSettings.add(sto);
ethernetSettings.add(portLabel);
ethernetSettings.add(port);
ethernetSettings.add(save);
ethernetSettings.add(ecancel);
final JPanel usbHIDSettings = new JPanel();
usbHIDSettings.setLayout(new GridLayout(5, 2));
usbHIDSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
usbHIDSettings.add(vendor);
usbHIDSettings.add(vendorid);
usbHIDSettings.add(product);
usbHIDSettings.add(productid);
usbHIDSettings.add(stoLabel3);
usbHIDSettings.add(sendtime);
usbHIDSettings.add(rtoLabel3);
usbHIDSettings.add(receiveto);
usbHIDSettings.add(save4);
usbHIDSettings.add(hcancel);
final JPanel usbCDCSettings = new JPanel();
usbCDCSettings.setLayout(new GridLayout(9, 2));
usbCDCSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
usbCDCSettings.add(baudrate2);
usbCDCSettings.add(baudlist);
usbCDCSettings.add(bytesize2);
usbCDCSettings.add(bytelist);
usbCDCSettings.add(stopbits2);
usbCDCSettings.add(stoplist);
usbCDCSettings.add(flow2);
usbCDCSettings.add(flowlist);
usbCDCSettings.add(parity2);
usbCDCSettings.add(paritylist);
usbCDCSettings.add(stoLabel2);
usbCDCSettings.add(sendto2);
usbCDCSettings.add(rtoLabel2);
usbCDCSettings.add(reto2);
usbCDCSettings.add(portLabel3);
usbCDCSettings.add(comport2);
usbCDCSettings.add(save3);
usbCDCSettings.add(gcancel);
final JPanel rsSettings = new JPanel();
rsSettings.setLayout(new GridLayout(9, 2));
rsSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
rsSettings.add(baudrate);
rsSettings.add(baudlist2);
rsSettings.add(bytesize);
rsSettings.add(bytelist2);
rsSettings.add(stopbits);
rsSettings.add(stoplist2);
rsSettings.add(flow);
rsSettings.add(flowlist2);
rsSettings.add(parity);
rsSettings.add(paritylist2);
rsSettings.add(stoLabel);
rsSettings.add(sendto);
rsSettings.add(rtoLabel);
rsSettings.add(reto);
rsSettings.add(portLabel2);
rsSettings.add(comport);
rsSettings.add(save2);
rsSettings.add(fcancel);
JRadioButton ethernet = new JRadioButton("Ethernet");
ethernet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog esettings = new JDialog(frame);
esettings.setTitle("Ethernet Settings");
esettings.add(ethernetSettings);
esettings.setSize(400, 400);
esettings.pack();
esettings.setVisible(true);
}
});
JRadioButton rs = new JRadioButton("RS232");
rs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog rsettings = new JDialog(frame);
rsettings.setTitle("RS232 Settings");
rsettings.add(rsSettings);
rsettings.pack();
rsettings.setVisible(true);
}
});
JRadioButton usbcdc = new JRadioButton("USB_CDC");
usbcdc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog usbc = new JDialog(frame);
usbc.setTitle("USB_CDC Settings");
usbc.add(usbCDCSettings);
usbc.setSize(400, 400);
usbc.pack();
usbc.setVisible(true);
}
});
JRadioButton usbhid = new JRadioButton("USB_HID");
usbhid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog usbh = new JDialog(frame);
usbh.setTitle("USB_HID Settings");
usbh.add(usbHIDSettings);
usbh.setSize(400, 400);
usbh.pack();
usbh.setVisible(true);
}
});
final JPanel PortSettings = new JPanel();
PortSettings.setLayout(new GridLayout(3, 4));
PortSettings.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
PortSettings.add(ethernet);
PortSettings.add(rs);
PortSettings.add(usbcdc);
PortSettings.add(usbhid);
PortSettings.add(next);
PortSettings.add(bcancel);
final JPanel accountPanel = new JPanel();
accountPanel.setLayout(new GridLayout(4, 2));
accountPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
accountPanel.add(cardLabel);
accountPanel.add(card);
accountPanel.add(expLabel);
accountPanel.add(expDate);
accountPanel.add(cvvLabel);
accountPanel.add(cvv);
accountPanel.add(bok);
accountPanel.add(ccancel);
JRadioButton apprve = new JRadioButton("Approve");
JRadioButton decline = new JRadioButton("Decline");
final JPanel apprvordecl = new JPanel();
apprvordecl.setLayout(new GridLayout(3, 2));
apprvordecl.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
apprvordecl.add(apprve);
apprvordecl.add(decline);
apprvordecl.add(textLabel);
apprvordecl.add(textBox);
apprvordecl.add(aok);
apprvordecl.add(acancel);
final JPanel amountPanel = new JPanel();
amountPanel.setLayout(new GridLayout(2, 2));
amountPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
amountPanel.add(amountLabel);
amountPanel.add(amountbox);
amountPanel.add(cok);
amountPanel.add(dcancel);
JButton initialize = new JButton("Initialize");
JButton connect = new JButton("Connect");
JButton disconnect = new JButton("Disconnect");
JButton shutdown = new JButton("Shut Down");
JButton portsettings = new JButton("Port Settings");
portsettings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog port = new JDialog(frame);
port.setTitle("Port Settings");
port.setSize(400, 400);
port.add(PortSettings);
port.pack();
port.setVisible(true);
}
});
JButton online = new JButton("Go Online");
JButton offline = new JButton("Go Offline");
JButton status = new JButton("Status");
JButton reboot = new JButton("Reboot");
JButton account = new JButton("Account");
account.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog accountDialog = new JDialog(frame);
accountDialog.setTitle("Account");
accountDialog.setSize(400, 400);
accountDialog.add(accountPanel);
accountDialog.pack();
accountDialog.setVisible(true);
}
});
JButton amount = new JButton("Amount");
amount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog amount2 = new JDialog(frame);
amount2.setTitle("Amount");
amount2.setSize(400, 400);
amount2.add(amountPanel);
amount2.pack();
amount2.setVisible(true);
}
});
JButton reset = new JButton("Reset");
JButton approvordecl = new JButton("Approve / Decline");
approvordecl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog apprv = new JDialog(frame);
apprv.setTitle("Approve / Decline");
apprv.setSize(400, 400);
apprv.add(apprvordecl);
apprv.pack();
apprv.setVisible(true);
}
});
JButton test = new JButton("Test Button #1");
JButton testing = new JButton("Test Button #2");
JRadioButton button = new JRadioButton("Radio Button");
JRadioButton button2 = new JRadioButton("Radio Button");
JCheckBox checkbox = new JCheckBox("Check Box");
JCheckBox checkbox2 = new JCheckBox("Check Box");
ButtonGroup group = new ButtonGroup();
group.add(usbhid);
group.add(usbcdc);
group.add(ethernet);
group.add(rs);
ButtonGroup approvegroup = new ButtonGroup();
approvegroup.add(apprve);
approvegroup.add(decline);
JPanel testPanel = new JPanel();
testPanel.add(button);
testPanel.add(button2);
testPanel.add(checkbox2);
JPanel posPanel = new JPanel();
posPanel.add(test);
posPanel.add(testing);
posPanel.add(checkbox);
JPanel llpPanel = new JPanel();
llpPanel.add(online);
llpPanel.add(offline);
llpPanel.add(status);
llpPanel.add(reboot);
llpPanel.add(account);
llpPanel.add(amount);
llpPanel.add(reset);
llpPanel.add(approvordecl);
llpPanel.add(logbox);
JPanel buttonPanel = new JPanel();
buttonPanel.add(initialize);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
buttonPanel.add(shutdown);
buttonPanel.add(portsettings);
frame.add(buttonPanel);
frame.add(buttonPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
tabbedPane.addTab("Test", null, testPanel, "Test");
JPanel tabsPanel = new JPanel(new BorderLayout());
tabsPanel.add(tabbedPane);
frame.add(tabsPanel, BorderLayout.CENTER);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
I have tried multiple times and everything I do it exits the whole program.
I don't see you code for closing the dialog so I can't guess what you might be doing wrong.
In your ActionListener you would invoke the dispose method on the dialog. The code would be something like:
JButton button = (JButton)event.getSource();
Window dialog = SwingUtilities.windowForComponent( button );
dialog.dispose();
A different approach might be to use a JOptionPane, then you don't need to code your own ActionListeners. You can easily add a panel to an option pane. The code below shows two approaches:
import java.awt.*;
import javax.swing.*;
public class OptionPanePanel
{
private static void createAndShowUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
// Build a custom panel
JPanel panel = new JPanel( new GridLayout(2, 2) );
panel.add( new JLabel("First Name") );
JTextField firstName = new JTextField(10);
// firstName.addAncestorListener( new RequestFocusListener(false) );
panel.add( firstName );
panel.add( new JLabel("Last Name") );
JTextField lastName = new JTextField(10);
panel.add( lastName );
int result = JOptionPane.showConfirmDialog(
null, // use your JFrame here
panel,
"Enter Name",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE);
if(result == JOptionPane.YES_OPTION)
{
System.out.println(firstName.getText() + " : " + lastName.getText());
}
else
{
System.out.println("Canceled");
}
// Let Option Pane build the panel for you
Object[] msg = {"First Name:", firstName, "Last Name:", lastName};
result = JOptionPane.showConfirmDialog(
frame,
msg,
"Enter Name...",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.YES_OPTION)
{
System.out.println(firstName.getText() + " : " + lastName.getText());
}
else
{
System.out.println("Canceled");
}
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
One problem with this approach is that focus will be on the OK button instead of the text field. To get around this you can use the RequestFocusListener found in Dialog Focus.

Categories