I am writing a program for class, and I have about all of it done but one part that is really confusing me.
I have to create a system for flooring that a person can choose the floor type, enter their length and width of their floor and it calculates and produces a order summary.
Now, I am able to get all of this but the calculations correct (and I haven't even started on the database connection because of it.)
My professor is extremely vague in her directions and even the answers to her questions, so as a last ditch effort I thought I would try here.
I cannot for the life of me figure it out so ANY help is greatly appreciated.
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class FloorMart
{
private static JFrame frame = null;
private static Integer cost;
private static String floorSize;
private static String floorType;
private double floorLength;
private double floorWidth;
public static void main(String[] args)
{
frame = new JFrame("FloorMart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(320, 300);
JTabbedPane tPane = new JTabbedPane();
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
panel1.setPreferredSize(new Dimension(200, 200));
JLabel jLabel = new JLabel();
jLabel.setText("Welcome to the FloorMart ordering system! ");
panel1.add(jLabel);
JLabel jLabel1 = new JLabel();
jLabel1.setText("Enter your Name: ");
panel1.add(jLabel1);
JTextField text1 = new JTextField(10);
panel1.add(text1);
JLabel jLabel2 = new JLabel();
jLabel2.setText("Enter your Pnone Number: ");
panel1.add(jLabel2);
JTextField text2 = new JTextField(10);
panel1.add(text2);
tPane.addTab("Customer", panel1);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Floor Type? ");
panel2.add(jLabel);
ButtonGroup group = new ButtonGroup();
JRadioButton RadioButton = new JRadioButton("Carpet - $10 per sq ft", true);
panel2.add(RadioButton);
group.add(RadioButton);
JRadioButton RadioButton1 = new JRadioButton("Hardwood - $20 per sq ft");
panel2.add(RadioButton1);
group.add(RadioButton1);
tPane.addTab("Floor Type", panel2);
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Enter the length and width of your floor! ");
panel3.add(jLabel);
JLabel jLabel3 = new JLabel();
jLabel3.setText("Enter the floor length: ");
panel3.add(jLabel3);
JTextField length = new JTextField(10);
panel3.add(length);
//length.setText(cost.toString()); //
JLabel jLabel4 = new JLabel();
jLabel4.setText("Enter the floor width: ");
panel3.add(jLabel4);
JTextField width = new JTextField(10);
panel3.add(width);
//width.setText(cost.toString()); //
tPane.addTab("Floor Size", panel3);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout());
panel4.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Total Cost: ");
panel4.add(jLabel);
JTextField text3 = new JTextField(10);
panel4.add(text3);
JButton button = new JButton("Order Summary");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JPanel panelNew = new JPanel();
panelNew.setLayout(new BoxLayout(panelNew, BoxLayout.Y_AXIS));
JLabel jLabeln = new JLabel("Order Summary");
JLabel jLabeln1 = new JLabel("Customer Name: " + text1.getText());
JLabel jLabeln2 = new JLabel("Phone Number: " + text2.getText());
JLabel jLabeln3 = new JLabel("Floor Type: " + floorType);
JLabel jLabeln4 = new JLabel("Floor Area: " + floorSize);
JLabel jLabeln5 = new JLabel("Total: $" + new Double(cost) + "0");
JLabel jLabeln6 = new JLabel("Thank you for shopping at FloorMart!");
panelNew.add(jLabeln);
panelNew.add(jLabeln1);
panelNew.add(jLabeln2);
panelNew.add(jLabeln3);
panelNew.add(jLabeln4);
panelNew.add(jLabeln5);
panelNew.add(jLabeln6);
frame.invalidate();
frame.remove(panel1);frame.remove(panel2);frame.remove(panel3);
frame.remove(panel4);
frame.remove(tPane);
frame.add(panelNew);
frame.revalidate();
frame.repaint();
}
});
panel4.add(button);
tPane.addTab("Total", panel4);
ChangeListener changeListener= new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource();
int index = sourceTabbedPane.getSelectedIndex();
if(index == 2)
{
double floorLength = Double.parseDouble(length.getText());
double floorWidth = Double.parseDouble(width.getText());
floorSize = floorLength * floorWidth;
if(RadioButton.isSelected())
{
cost = 10; //per sq ft
floorType = RadioButton.getText();
}
else if(RadioButton1.isSelected())
{
cost = 20; //per sq ft
floorType = RadioButton1.getText();
}
text3.setText(cost.toString());
}
}
};
tPane.addChangeListener(changeListener);
frame.add(tPane);
frame.setVisible(true);
}
}
I can see two basic things that needs to be changed:
a. this does not compile (floorSize should be double)
String floorSize;
double floorLength = Double.parseDouble(length.getText());
double floorWidth = Double.parseDouble(width.getText());
floorSize = floorLength * floorWidth;
b. The calculation of floorSize should not be triggered by ChangeListener (which causes the calculation to be done before values are entered).
Use "Order Summary" JButton to trigger the calculation.
Here is a working version of the code. See my comments:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class FloorMart
{
private static JFrame frame = null;
private static Integer cost; //better use int
//////////////////////////////////////
//changed from string to double
private static double floorSize;
////////////////////////////////////
private static String floorType;
private double floorLength;
private double floorWidth;
public static void main(String[] args)
{
frame = new JFrame("FloorMart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(320, 300);
JTabbedPane tPane = new JTabbedPane();
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
panel1.setPreferredSize(new Dimension(200, 200));
JLabel jLabel = new JLabel();
jLabel.setText("Welcome to the FloorMart ordering system! ");
panel1.add(jLabel);
JLabel jLabel1 = new JLabel();
jLabel1.setText("Enter your Name: ");
panel1.add(jLabel1);
JTextField text1 = new JTextField(10);
panel1.add(text1);
JLabel jLabel2 = new JLabel();
jLabel2.setText("Enter your Pnone Number: ");
panel1.add(jLabel2);
JTextField text2 = new JTextField(10);
panel1.add(text2);
tPane.addTab("Customer", panel1);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Floor Type? ");
panel2.add(jLabel);
ButtonGroup group = new ButtonGroup();
JRadioButton RadioButton = new JRadioButton("Carpet - $10 per sq ft", true);
panel2.add(RadioButton);
group.add(RadioButton);
JRadioButton RadioButton1 = new JRadioButton("Hardwood - $20 per sq ft");
panel2.add(RadioButton1);
group.add(RadioButton1);
tPane.addTab("Floor Type", panel2);
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Enter the length and width of your floor! ");
panel3.add(jLabel);
JLabel jLabel3 = new JLabel();
jLabel3.setText("Enter the floor length: ");
panel3.add(jLabel3);
JTextField length = new JTextField(10);
panel3.add(length);
//length.setText(cost.toString()); //
JLabel jLabel4 = new JLabel();
jLabel4.setText("Enter the floor width: ");
panel3.add(jLabel4);
JTextField width = new JTextField(10);
panel3.add(width);
//width.setText(cost.toString()); //
tPane.addTab("Floor Size", panel3);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout());
panel4.setPreferredSize(new Dimension(200, 200));
jLabel = new JLabel();
jLabel.setText("Total Cost: ");
panel4.add(jLabel);
JTextField text3 = new JTextField(10);
panel4.add(text3);
JButton button = new JButton("Order Summary");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
//////////////////////////////////////////////////////////////
//calculation moved to here
double floorLength = Double.parseDouble(length.getText());
double floorWidth = Double.parseDouble(width.getText());
floorSize = floorLength * floorWidth;
if(RadioButton.isSelected())
{
cost = 10; //per sq ft
floorType = RadioButton.getText();
}
else if(RadioButton1.isSelected())
{
cost = 20; //per sq ft
floorType = RadioButton1.getText();
}
text3.setText(cost.toString());
//////////////////////////////////////////////////////////////
JPanel panelNew = new JPanel();
panelNew.setLayout(new BoxLayout(panelNew, BoxLayout.Y_AXIS));
JLabel jLabeln = new JLabel("Order Summary");
JLabel jLabeln1 = new JLabel("Customer Name: " + text1.getText());
JLabel jLabeln2 = new JLabel("Phone Number: " + text2.getText());
JLabel jLabeln3 = new JLabel("Floor Type: " + floorType);
JLabel jLabeln4 = new JLabel("Floor Area: " + floorSize);
///////////////////////////////////////////////////////////////////////////
// changed JLabel jLabeln5 = new JLabel("Total: $" + new Double(cost*floorSize) + "0");
//to:
JLabel jLabeln5 = new JLabel("Total: $" + new Double(cost*floorSize) + "0");
///////////////////////////////////////////////////////////////////////////
JLabel jLabeln6 = new JLabel("Thank you for shopping at FloorMart!");
panelNew.add(jLabeln);
panelNew.add(jLabeln1);
panelNew.add(jLabeln2);
panelNew.add(jLabeln3);
panelNew.add(jLabeln4);
panelNew.add(jLabeln5);
panelNew.add(jLabeln6);
frame.invalidate();
frame.remove(panel1);frame.remove(panel2);frame.remove(panel3);
frame.remove(panel4);
frame.remove(tPane);
frame.add(panelNew);
frame.revalidate();
frame.repaint();
}
});
panel4.add(button);
tPane.addTab("Total", panel4);
/////////////////////////////////
//removed ChangeListener
////////////////////////////////
frame.add(tPane);
frame.setVisible(true);
}
}
Related
I have spent many hours digging around the web and cannot seem to find a straightforward answer or method to add a dropdown selection into my main panel that houses the various text fields, in this case, I am trying to add a paint color selection to the panel so that color can then be used as a variable in determining cost.
The closest I have come so far is having a combo box popup in a new window but then was unable to retrieve the selection.
package paintestimator;
import java.lang.String;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.PopupMenu;
import javax.swing.JComboBox;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PaintEstimator extends JFrame
{
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
//Josh
public PaintEstimator()
{
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
JButton ChoiceA = new JButton("Paint Color");
//JComboBox vendorBTN = (new JComboBox());
ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
//box to show chosen color
//mainPanel.add(new JLabel("Color Chosen"));
// mainPanel.add(sColor);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add( new JLabel("Select a Color"));
mainPanel.add (ChoiceA);
// mainPanel.add(sColor);
// Select<String> select = new Select<>();
//select.setLabel("Sort by");
//select.setItems("Most recent first", "Rating: high to low",
// "Rating: low to high", "Price: high to low", "Price: low to high");
//select.setValue("Most recent first");
// mainPanel.add(select);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
// mainPanel.add(ChoiceA);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
//Josh
class CalcChangeBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n); // still need refine decimal point to #.0
(one decimal place)
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f)
{
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// clear text fields and set focus
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
class ChoiceAListener implements ActionListener
{
public void actionPreformed (ActionEvent e)
{
}
public static void main(String[] args)
{
PaintEstimator window = new PaintEstimator();
window.setVisible(true);
}
}
Below is the combo box I was able to create:
public static void main(String[] args)
{
String[] optionsToChoose =
{
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
JFrame jFrame = new JFrame();
JComboBox<String> jComboBox = new JComboBox<>(optionsToChoose);
jComboBox.setBounds(80, 50, 140, 20);
JButton jButton = new JButton("Done");
jButton.setBounds(100, 100, 90, 20);
JLabel jLabel = new JLabel();
jLabel.setBounds(90, 100, 400, 100);
jFrame.add(jButton);
jFrame.add(jComboBox);
jFrame.add(jLabel);
jFrame.setLayout(null);
jFrame.setSize(350, 250);
jFrame.setVisible(true);
jButton.addActionListener((ActionEvent e) ->
{
String selectedColor = "You selected " +
jComboBox.getItemAt(jComboBox.getSelectedIndex());
jLabel.setText(selectedColor);
});
}
Start by reading through How to Use Combo Boxes (and it wouldn't hurt to look over some the examples)
Start by creating an instance field for the combobox...
public class PaintEstimator extends JFrame {
//...
private JComboBox<String> colorChoice = new JComboBox<>();
//...
Next, create a ComboBoxModel to hold the values you want to present and replace the ChoiceA button with the combobox...
mainPanel.add(new JLabel("Select a Color"));
//mainPanel.add(ChoiceA);
// mainPanel.add(sColor);
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
And then in your ActionListener, get the selected value...
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
Runnable example...
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new PaintEstimator();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintEstimator extends JFrame {
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
private JComboBox<String> colorChoice = new JComboBox<>();
public PaintEstimator() {
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
//ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add(new JLabel("Select a Color"));
String[] optionsToChoose = {
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(optionsToChoose);
colorChoice.setModel(model);
mainPanel.add(colorChoice);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
class CalcChangeBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String choosenColor = (String) colorChoice.getSelectedItem();
System.out.println("choosenColor = " + choosenColor);
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n);
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f) {
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
}
}
The first column in my grid always comes out right but then the rest begin replacing the other cells. Also the border layout does not seem to be functioning. I do not know what the problem is. It should have the title on top, a 7x3 grid in the center and the buttons on the bottom. Please help! Thank you!
import java.awt.BorderLayout;
import java.awt.GridLayout;
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.JPanel;
import javax.swing.JTextField;
public class GUI extends JFrame{
private JPanel mainPanel,titlePanel, fieldPanel, buttonPanel;
private JLabel title, teams, totalP, wlt;
private JTextField team1, team2, team3, team4, team5, team6, total1, total2, total3, total4, total5, total6, wlt1, wlt2, wlt3, wlt4, wlt5, wlt6;
private JButton read, calc, champWin, earthCW, exit;
final private int WINDOW_HEIGHT = 400;
final private int WINDOW_WIDTH = 900;
public GUI(){
buildtitlePanel();
buildfieldPanel();
buildbuttonPanel();
buildmainPanel();
setTitle("Desert Soccer League");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void buildmainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private void buildtitlePanel() {
titlePanel = new JPanel();
title = new JLabel();
title.setText("2014 Desert Soccer League Totals");
titlePanel.add(title);
}
private void buildfieldPanel() {
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(7, 3));
teams = new JLabel();
teams.setText("Teams");
totalP = new JLabel();
totalP.setText("Total Points");
wlt = new JLabel();
wlt.setText("Win-Loss-Tie");
team1 = new JTextField(10);
team2 = new JTextField(10);
team3 = new JTextField(10);
team4 = new JTextField(10);
team5 = new JTextField(10);
team6 = new JTextField(10);
total1 = new JTextField(10);
total2 = new JTextField(10);
total3 = new JTextField(10);
total4 = new JTextField(10);
total5 = new JTextField(10);
total6 = new JTextField(10);
wlt1 = new JTextField(10);
wlt2 = new JTextField(10);
wlt3 = new JTextField(10);
wlt4 = new JTextField(10);
wlt5 = new JTextField(10);
wlt6 = new JTextField(10);
team1.setEditable(false);
team2.setEditable(false);
team3.setEditable(false);
team4.setEditable(false);
team5.setEditable(false);
team6.setEditable(false);
total1.setEditable(false);
total2.setEditable(false);
total3.setEditable(false);
total4.setEditable(false);
total5.setEditable(false);
total6.setEditable(false);
wlt1.setEditable(false);
wlt2.setEditable(false);
wlt3.setEditable(false);
wlt4.setEditable(false);
wlt5.setEditable(false);
wlt6.setEditable(false);
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
fieldPanel.add(totalP);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
fieldPanel.add(wlt);
fieldPanel.add(wlt1);
fieldPanel.add(wlt2);
fieldPanel.add(wlt3);
fieldPanel.add(wlt4);
fieldPanel.add(wlt5);
fieldPanel.add(wlt6);
}
private void buildbuttonPanel() {
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 5));
read = new JButton();
calc = new JButton();
champWin = new JButton();
earthCW = new JButton();
exit = new JButton();
read.setText("Read Input File");
read.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
calc.setText("Calculate Points");
calc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
champWin.setText("Championship Winner");
champWin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
earthCW.setText("Earth Cup Winner");
earthCW.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
exit.setText("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
buttonPanel.add(read);
buttonPanel.add(calc);
buttonPanel.add(champWin);
buttonPanel.add(earthCW);
buttonPanel.add(exit);
}
}
mainPanel = new JPanel();
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
By default a JPanel uses a FlowLayout. If you want to use a BorderLayout, then you need to set the layout on the panel:
mainPanel = new JPanel( new BorderLayout() );
The GridLayout fills out the rows first so the code should be:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
...
Also note that in your code you are adding the total? fields twice (which won't do anything), instead of the team? fields.
Another way to specify the grid is to just use:
fieldPanel.setLayout(new GridLayout(0, 3));
This tells the grid to add 3 components to each row then move on to the next row. This way you don't have to worry about the exact number of rows.
To add to camickr answer you're also adding the same total fields multiple times, so change this:
fieldPanel.add(teams);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
to
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
This is what is causing your display issue.
Your code should look like:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
fieldPanel.add(team2);
fieldPanel.add(total2);
fieldPanel.add(wlt2);
// etc.
I created a JTabbedPane and a few JPanel objects. Since each panel pretty much looked the same the fields also are called the same. I thought it was OK since all the fields are local variables. Now I am in the controller class and I am having a issue with:
The best way to add action listeners to all the fields in each JPanel and
figure out which tabbed pane is selected.
Here is the GUI:
package mainGUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class MainMenuGUI {
JTabbedPane tabbedPane = new JTabbedPane();
JPanel findUserPanel;
JPanel deleteUserPanel;
JPanel addUserPanel;
JFrame frame = new JFrame();
JPanel tabbedPanel = new JPanel();
//Controller class for MainMenuGUI
ControllerMainMenuGUI listen = new ControllerMainMenuGUI(this);
public MainMenuGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
findUserPanel = createFindUserPanel();
deleteUserPanel = createDeleteUserPanel();
addUserPanel = createAddUserPanel();
tabbedPane.addTab("Find User", findUserPanel);
tabbedPane.addTab("Delete User", deleteUserPanel);
tabbedPane.addTab("Add User", addUserPanel);
tabbedPanel.add(tabbedPane);
frame.add(tabbedPanel);
frame.pack();
// opens frame in the center of the screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
JPanel createFindUserPanel() {
findUserPanel = new JPanel();
findUserPanel.setPreferredSize(new Dimension(300, 300));
findUserPanel.setLayout(new GridLayout(5, 7));
JLabel firstlbl = new JLabel("First Name");
JLabel lastlbl = new JLabel("Last Name");
JLabel addresslbl = new JLabel("Address");
JLabel agelbl = new JLabel("Age");
JTextField firstNametxt = new JTextField(15);
JTextField lastNametxt = new JTextField(15);
JTextField addresstxt = new JTextField(30);
JTextField age = new JTextField(3);
JButton btn = new JButton("Submit");
JScrollPane window = new JScrollPane();
window.setViewportBorder(new LineBorder(Color.RED));
window.setPreferredSize(new Dimension(150, 150));
findUserPanel.add(firstlbl);
findUserPanel.add(firstNametxt);
findUserPanel.add(lastlbl);
findUserPanel.add(lastNametxt);
findUserPanel.add(addresslbl);
findUserPanel.add(addresstxt);
findUserPanel.add(agelbl);
findUserPanel.add(age);
findUserPanel.add(window, BorderLayout.CENTER);
findUserPanel.add(btn);
return findUserPanel;
}
JPanel createDeleteUserPanel() {
deleteUserPanel = new JPanel();
deleteUserPanel.setPreferredSize(new Dimension(300, 300));
deleteUserPanel.setLayout(new GridLayout(5, 7));
JLabel firstlbl = new JLabel("First Name");
JLabel lastlbl = new JLabel("Last Name");
JLabel addresslbl = new JLabel("Address");
JLabel agelbl = new JLabel("Age");
JTextField firstNametxt = new JTextField(15);
JTextField lastNametxt = new JTextField(15);
JTextField addresstxt = new JTextField(30);
JTextField age = new JTextField(3);
JButton btn = new JButton("Submit");
JScrollPane window = new JScrollPane();
window.setViewportBorder(new LineBorder(Color.RED));
window.setPreferredSize(new Dimension(150, 150));
deleteUserPanel.add(firstlbl);
deleteUserPanel.add(firstNametxt);
deleteUserPanel.add(lastlbl);
deleteUserPanel.add(lastNametxt);
deleteUserPanel.add(addresslbl);
deleteUserPanel.add(addresstxt);
deleteUserPanel.add(agelbl);
deleteUserPanel.add(age);
deleteUserPanel.add(window, BorderLayout.CENTER);
deleteUserPanel.add(btn);
return deleteUserPanel;
}
JPanel createAddUserPanel() {
addUserPanel = new JPanel();
addUserPanel.setPreferredSize(new Dimension(300, 300));
addUserPanel.setLayout(new GridLayout(5, 7));
JLabel firstlbl = new JLabel("First Name");
JLabel lastlbl = new JLabel("Last Name");
JLabel addresslbl = new JLabel("Address");
JLabel agelbl = new JLabel("Age");
JTextField firstNametxt = new JTextField(15);
JTextField lastNametxt = new JTextField(15);
JTextField addresstxt = new JTextField(30);
JTextField age = new JTextField(3);
// nametxt.setPreferredSize(new Dimension(1,10));
JButton btn = new JButton("Submit");
JScrollPane window = new JScrollPane();
window.setViewportBorder(new LineBorder(Color.RED));
window.setPreferredSize(new Dimension(150, 150));
addUserPanel.add(firstlbl);
addUserPanel.add(firstNametxt);
addUserPanel.add(lastlbl);
addUserPanel.add(lastNametxt);
addUserPanel.add(addresslbl);
addUserPanel.add(addresstxt);
addUserPanel.add(agelbl);
addUserPanel.add(age);
addUserPanel.add(window, BorderLayout.CENTER);
addUserPanel.add(btn);
return addUserPanel;
}
}
Controller class:
package mainGUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ControllerMainMenuGUI {
MainMenuGUI mainMenuGUI;
int currentTabbedIndex = 0;
ControllerMainMenuGUI(MainMenuGUI mainMenuGUI){
this.mainMenuGUI = mainMenuGUI;
}
//inner class will handle MainMenuGUI actions
class Actions implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
}
private void addTabbedPaneListeners() {
mainMenuGUI.tabbedPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent ce) {
currentTabbedIndex =
mainMenuGUI.tabbedPane.getSelectedIndex();
System.out.println("Current tab is:" + currentTabbedIndex);
}
});
}
}
}
I have the following GUI codded up but I would like to increase the length of the scroll bar on the right side.
Any Idea How to do this?
// test class that implements the gui stuff.
public class testing
{
//variables
private JFrame f = new JFrame("GUI TEST");
private JPanel p = new JPanel();
private JPanel p2 = new JPanel();
private JPanel p3 = new JPanel();
private JPanel p4 = new JPanel();
private JPanel p5 = new JPanel();
private JPanel p6 = new JPanel();
private JPanel p7 = new JPanel();
private JPanel p8 = new JPanel();
private JPanel p9 = new JPanel();
private JPanel p10 = new JPanel();
private JPanel p11 = new JPanel();
private JButton b1 = new JButton("Button");
private JTextField tf1 = new JTextField(" ");
private JTextField tf2 = new JTextField(" ");
private JTextField tf3 = new JTextField(" ");
private JTextArea ta1 = new JTextArea(10,45);
private JLabel label1 = new JLabel("Label 1");
private JLabel label2 = new JLabel("Label 2");
private JLabel label3 = new JLabel("Label 3");
private JLabel label4 = new JLabel("Label 4");
private JScrollBar sb1 = new JScrollBar();
//class constructor
public testing()
{
gui();
}
public void gui()
{
//change length of scroll bar
f.setVisible(true);
f.setSize(600,300);
p.add(label1);
p.add(tf1);
p2.add(label2);
p2.add(tf2);
p3.add(label3);
p3.add(tf3);
p4.add(sb1);
p4.add(label4);
p5.add(ta1);
p6.add(b1);
p4.setBackground(Color.GRAY);
p9.setBackground(Color.GRAY);
p10.setBackground(Color.GRAY);
p11.setBackground(Color.GRAY);
p9.add(p);
p9.add(p2);
p9.add(p3);
p10.add(p5);
p11.add(p6);
//adds panels to frames
f.add(p4, BorderLayout.EAST);
f.add(p9, BorderLayout.NORTH);
f.add(p10, BorderLayout.CENTER);
f.add(p11, BorderLayout.PAGE_END);
}
public static void main(String[] args)
{
new testing();
}
Ordinarilly, you'd simply add your JTextArea to a JScrollPane, which handles the resizing behavior for you.
f.add(new JScrollPane(ta1), BorderLayout.CENTER);
For demonstration purposes, you can override the getPreferredSize() method of the JScrollBar to see the effect.
private JScrollBar sb1 = new JScrollBar(){
#Override
public Dimension getPreferredSize() {
return new Dimension(
super.getPreferredSize().width, ta1.getPreferredSize().height);
}
};
In addition,
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
Use the appropriate constructor to establish the desired initial size of text components.
Use an appropriate layout to get the desired resizing behavior.
As tested:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Testing {
//variables
private JFrame f = new JFrame("GUI TEST");
private JPanel p = new JPanel();
private JPanel p2 = new JPanel();
private JPanel p3 = new JPanel();
private JPanel p4 = new JPanel();
private JPanel p5 = new JPanel();
private JPanel p6 = new JPanel();
private JPanel p9 = new JPanel();
private JPanel p10 = new JPanel();
private JPanel p11 = new JPanel();
private JButton b1 = new JButton("Button");
private JTextField tf1 = new JTextField(12);
private JTextField tf2 = new JTextField(12);
private JTextField tf3 = new JTextField(12);
private JTextArea ta1 = new JTextArea(10, 45);
private JLabel label1 = new JLabel("Label 1");
private JLabel label2 = new JLabel("Label 2");
private JLabel label3 = new JLabel("Label 3");
private JLabel label4 = new JLabel("Label 4");
private JScrollBar sb1 = new JScrollBar(){
#Override
public Dimension getPreferredSize() {
return new Dimension(super.getPreferredSize().width, ta1.getPreferredSize().height);
}
};
//class constructor
public Testing() {
gui();
}
public void gui() {
p.add(label1);
p.add(tf1);
p2.add(label2);
p2.add(tf2);
p3.add(label3);
p3.add(tf3);
p4.add(sb1);
p4.add(label4);
p5.add(ta1);
p6.add(b1);
p4.setBackground(Color.GRAY);
p9.setBackground(Color.GRAY);
p10.setBackground(Color.GRAY);
p11.setBackground(Color.GRAY);
p9.add(p);
p9.add(p2);
p9.add(p3);
p10.add(p5);
p11.add(p6);
//adds panels to frames
f.add(p4, BorderLayout.EAST);
f.add(p9, BorderLayout.NORTH);
f.add(p10, BorderLayout.CENTER);
f.add(p11, BorderLayout.PAGE_END);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Testing();
});
}
}
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.