How to change the contents of JComboBox based on a condition? - java

I'm relatively new to OOP and learning. I'm stuck in figuring out how do I possibly change the contents of my pane.
What I want to happen is If I click a different unit, the contents of the two pane would be changed according to the unit I chose.
Like this:
1 2 3
Here's a gist of my code:
private Container c;
private JTextField t1;
private JTextField t2;
private JButton b1;
String[] choicelen = {"meter", "kilometer", "centimeter", "millimeter", "mile", "yard", "foot"};
private JComboBox clen;
String[] choicelen1 = {"meter", "kilometer", "centimeter", "millimeter", "mile", "yard", "foot"};
private JComboBox clen1;
String[] choicetem = {"celsius", "kelvin", "fahrenheit"};
String[] choicetem1 = {"celsius", "kelvin", "fahrenheit"};
String[] choicearea = {"acre", "hectare", "sq mile", "sq yard", "sq foot", "sq inch"};
String[] choicearea1 = {"acre", "hectare"};
String[] choicevol = {"liter", "milliliter", "gallon", "quart", "pint", "cup", "fluid ounce"};
String[] choicevol1 = {"liter", "milliliter", "gallon", "quart", "pint", "cup", "fluid ounce"};
String[] choicewt = {"gram", "kilogram", "milligram", "metric ton", "pound", "ounce", "carrat"};
String[] choicewt1 = {"gram", "kilogram", "milligram", "metric ton", "pound", "ounce", "carrat"};
String[] choicetime = {"second", "millisecond", "minute", "hour", "day", "week", "month", "year"};
String[] choicetime1 = {"second", "millisecond", "minute", "hour", "day", "week", "month", "year"};
String[] choices = {"Length", "Temperature", "Area", "Volume", "Weight", "Time"};
private JComboBox c3;

Introduction
The OP's code is not a minimal reproducible example.
So, I went ahead and created the following GUI.
I only coded the conversions for length and temperature. I'm leaving the rest as an exercise for the OP.
Explanation
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
When I create a Swing GUI, I use the model-view-controller (MVC) pattern. This pattern allows me to separate my concerns and focus on one part of the application at a time.
The model is the most important part of any Swing application. A good model makes coding the view and the controllers so much easier.
A Swing model is made up of one or more plain Java getter/setter classes.
A Swing view is made up of one JFrame and as many JPanels and JDialogs as necessary.
A Swing controller is an Action or Listener that modifies the model and updates the view.
A Swing application usually has multiple controller classes.
Model
I created two model classes for this application.
The Measurement class holds a text String, a multiplier, and an adder.
Let's take the formulas for temperature conversion.
f = (c * 9/5) + 32
c = (f - 32) / 9/5
The general formula for any measurement conversion is
to value = (from value * multiplier) + adder
So, for the lengths, I converted the from value to millimeters and converted millimeters to the to value. I did a similar thing for the temperatures, where I converted the from value to celsius and converted celsius to the to value.
This way, I cut down on the code necessary to do the conversions. All the OP has to do is plug in the rest of the multipliers and adders in the UnitConversionModel class.
The UnitConversionModel class holds a Map with a String key and a List<Measurement> object. This Map allows me to easily fill the JComboBoxes and gives me the values for the conversions.
View
I generated a view based loosely on the OP's pictures. The model made constructing the view simpler.
Controller
I coded two controller classes.
The ComboBoxListener class fills in the from conversion units and the to conversion units in the conversion units JComboBoxes.
The ButtonListener class does the unit conversion.
Code
Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class UnitConversionTool implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new UnitConversionTool());
}
private JComboBox<Measurement> fromMeasurementComboBox,
toMeasurementComboBox;
private JComboBox<String> measurementTypeComboBox;
private JTextField fromMeasurementField, toMeasurementField;
private UnitConversionModel model;
public UnitConversionTool() {
this.model = new UnitConversionModel();
}
#Override
public void run() {
JFrame frame = new JFrame("Unit Conversion Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(0, 5, 5, 5);
String[] measurementTypes = model.getMeasurementTypes();
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 0;
measurementTypeComboBox = new JComboBox<>(measurementTypes);
String measurementType = measurementTypes[measurementTypes.length - 1];
measurementTypeComboBox.setSelectedItem(measurementType);
measurementTypeComboBox
.addActionListener(new ComboBoxListener(this, model));
panel.add(measurementTypeComboBox, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.gridy++;
gbc.weightx = 1.0;
panel.add(new JLabel("From"), gbc);
Measurement[] measurementUnits = model
.getMeasurementList(measurementType);
gbc.gridx++;
fromMeasurementComboBox = new JComboBox<>(measurementUnits);
panel.add(fromMeasurementComboBox, gbc);
gbc.gridx++;
fromMeasurementField = new JTextField(10);
panel.add(fromMeasurementField, gbc);
gbc.gridx++;
panel.add(new JLabel("to"), gbc);
gbc.gridx++;
toMeasurementComboBox = new JComboBox<>(measurementUnits);
panel.add(toMeasurementComboBox, gbc);
gbc.gridx++;
toMeasurementField = new JTextField(10);
toMeasurementField.setEditable(false);
panel.add(toMeasurementField, gbc);
gbc.gridwidth = 6;
gbc.gridx = 0;
gbc.gridy++;
JButton button = new JButton("Convert");
button.addActionListener(new ButtonListener(this, model));
panel.add(button, gbc);
return panel;
}
public JComboBox<Measurement> getFromMeasurementComboBox() {
return fromMeasurementComboBox;
}
public JComboBox<Measurement> getToMeasurementComboBox() {
return toMeasurementComboBox;
}
public JComboBox<String> getMeasurementTypeComboBox() {
return measurementTypeComboBox;
}
public JTextField getFromMeasurementField() {
return fromMeasurementField;
}
public JTextField getToMeasurementField() {
return toMeasurementField;
}
public class ComboBoxListener implements ActionListener {
private final UnitConversionTool view;
private final UnitConversionModel model;
public ComboBoxListener(UnitConversionTool view,
UnitConversionModel model) {
this.view = view;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
String selectedMeasurementType = (String) view
.getMeasurementTypeComboBox().getSelectedItem();
Measurement[] measurementUnits = model
.getMeasurementList(selectedMeasurementType);
int count = view.getFromMeasurementComboBox().getItemCount();
for (int index = count - 1; index >= 0; index--) {
view.getFromMeasurementComboBox().removeItemAt(index);
view.getToMeasurementComboBox().removeItemAt(index);
}
for (Measurement m : measurementUnits) {
view.getFromMeasurementComboBox().addItem(m);
view.getToMeasurementComboBox().addItem(m);
}
}
}
public class ButtonListener implements ActionListener {
private final UnitConversionTool view;
private final UnitConversionModel model;
public ButtonListener(UnitConversionTool view,
UnitConversionModel model) {
this.view = view;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
Measurement fromMeasurement = (Measurement) view
.getFromMeasurementComboBox().getSelectedItem();
Measurement toMeasurement = (Measurement) view
.getToMeasurementComboBox().getSelectedItem();
double fromValue = Double
.valueOf(view.getFromMeasurementField().getText());
double toValue = (fromValue + fromMeasurement.getAdder())
* fromMeasurement.getMultiplier();
toValue = toValue / toMeasurement.getMultiplier()
- toMeasurement.getAdder();
String text = String.format("%.2f", toValue);
view.getToMeasurementField().setText(text);
}
}
public class UnitConversionModel {
private final Map<String, List<Measurement>> measurementMap;
private final Measurement[] lengthMeasurements = {
new Measurement("meter", 1000, 0),
new Measurement("kilometer", 1_000_000, 0),
new Measurement("centimeter", 10, 0),
new Measurement("millimeter", 1, 0),
new Measurement("mile", 1.609344e+6, 0),
new Measurement("yard", 914.4, 0),
new Measurement("foot", 304.8, 0) };
private final Measurement[] temperatureMeasurements = {
new Measurement("celsius", 1, 0),
new Measurement("kelvin", 1, -273.15),
new Measurement("fahrenheit", 5.0 / 9.0, -32) };
private final Measurement[] areaMeasurements = {
new Measurement("acre", 0, 0), new Measurement("hectare", 0, 0),
new Measurement("sq mile", 0, 0),
new Measurement("sq yard", 0, 0),
new Measurement("sq foot", 0, 0),
new Measurement("sq inch", 0, 0) };
private final Measurement[] volumeMeasurements = {
new Measurement("liter", 0, 0),
new Measurement("milliliter", 0, 0),
new Measurement("gallon", 0, 0), new Measurement("quart", 0, 0),
new Measurement("pint", 0, 0), new Measurement("cup", 0, 0),
new Measurement("fluid ounce", 0, 0) };
private final Measurement[] weightMeasurements = {
new Measurement("gram", 0, 0),
new Measurement("kilogram", 0, 0),
new Measurement("milligram", 0, 0),
new Measurement("metric ton", 0, 0),
new Measurement("pound", 0, 0), new Measurement("ounce", 0, 0),
new Measurement("carat", 0, 0) };
private final Measurement[] timeMeasurements = {
new Measurement("second", 0, 0),
new Measurement("millisecond", 0, 0),
new Measurement("minute", 0, 0), new Measurement("hour", 0, 0),
new Measurement("day", 0, 0), new Measurement("week", 0, 0),
new Measurement("month", 0, 0), new Measurement("year", 0, 0) };
private final String[] measurementTypes = { "Length", "Temperature",
"Area", "Volume", "Weight", "Time" };
private final Measurement[][] measurements = { lengthMeasurements,
temperatureMeasurements, areaMeasurements, volumeMeasurements,
weightMeasurements, timeMeasurements };
public UnitConversionModel() {
this.measurementMap = new LinkedHashMap<>();
for (int index = 0; index < measurementTypes.length; index++) {
String s = measurementTypes[index];
Measurement[] measurementUnits = measurements[index];
List<Measurement> measurementList = new ArrayList<>();
for (Measurement m : measurementUnits) {
measurementList.add(m);
}
measurementMap.put(s, measurementList);
}
}
public String[] getMeasurementTypes() {
return measurementTypes;
}
public Measurement[] getMeasurementList(String measurement) {
List<Measurement> measurementList = measurementMap.get(measurement);
return measurementList
.toArray(new Measurement[measurementList.size()]);
}
}
public class Measurement {
private final double adder, multiplier;
private final String text;
public Measurement(String text, double multiplier, double adder) {
this.text = text;
this.multiplier = multiplier;
this.adder = adder;
}
public double getAdder() {
return adder;
}
public double getMultiplier() {
return multiplier;
}
#Override
public String toString() {
return text;
}
}
}

I got it working by adding this code I found from a similar post:
c3 = new JComboBox<>(choices);
c.add(c3);
choose = new JComboBox<>(choicelen);
c.add(choose);
choose1 = new JComboBox<>(choicelen1);
c.add(choose1);
c3.addActionListener(new Listener());
class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (c3.getSelectedItem().equals("Length")) {
choose.setModel(new JComboBox<>(choicelen).getModel());
choose1.setModel(new JComboBox<>(choicelen1).getModel());
}
else if (c3.getSelectedItem().equals("Temperature")) {
choose.setModel(new JComboBox<>(choicetem).getModel());
choose1.setModel(new JComboBox<>(choicetem1).getModel());
}
else if (c3.getSelectedItem().equals("Area")) {
choose.setModel(new JComboBox<>(choicearea).getModel());
choose1.setModel(new JComboBox<>(choicearea1).getModel());
}
else if (c3.getSelectedItem().equals("Volume")) {
choose.setModel(new JComboBox<>(choicevol).getModel());
choose1.setModel(new JComboBox<>(choicevol1).getModel());
}
else if (c3.getSelectedItem().equals("Weight")) {
choose.setModel(new JComboBox<>(choicewt).getModel());
choose1.setModel(new JComboBox<>(choicewt1).getModel());
}
else if (c3.getSelectedItem().equals("Time")) {
choose.setModel(new JComboBox<>(choicetime).getModel());
choose1.setModel(new JComboBox<>(choicetime1).getModel());
}
}
}
Thank you guys!

Related

Java JDialog Passing Object From Within the JDialog using a Sumbit Button from the JDialog

ive searched online for the answer for a few hours now, so far i havent found anything helpful, i have a JDialog that is supposed to send an object back to the JPanel that called it, after running the code several times i noticed that the JPanel Constructor Finishes before i can press the Save button inside the JDialog,
my problem is this,
how do i pass the object from the JDialog to the JPanel and in which part of the Jpanel Code do i write it?
Here is the JPanel Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class AquaPanel extends JPanel implements ActionListener
{
private JFrame AQF;
private BufferedImage img;
private HashSet<Swimmable> FishSet;
private int FishCount;
private AddAnimalDialog JDA;
public AquaPanel(AquaFrame AQ)
{
super();
FishCount=0;
this.setSize(800, 600);
this.AQF = AQ;
gui();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
// if(!FishSet.isEmpty())
// {
// Iterator ITR = FishSet.iterator();
//
// while(ITR.hasNext())
// {
// ((Swimmable) ITR.next()).drawAnimal(g);
// }
// }
}
private void AddAnim()
{
Swimmable test = null;
JDA = new AddAnimalDialog(test);
JDA.setVisible(true);//shows jdialog box needs to set to false on new animal
}
private void Sleep()
{
}
private void Wake()
{
}
private void Res()
{
}
private void Food()
{
}
private void Info()
{
}
private void gui()
{
JPanel ButtonPanel = new JPanel();
Makebuttons(ButtonPanel);
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
ButtonPanel.setLayout(new GridLayout(1,0));
this.add(ButtonPanel,BorderLayout.SOUTH);
}
private void Makebuttons(JPanel ButtonPanel)
{
JButton Addanim = new JButton("Add Animal");
Addanim.setBackground(Color.LIGHT_GRAY);
Addanim.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AddAnim();
}
});
JButton Sleep = new JButton("Sleep");
Sleep.setBackground(Color.LIGHT_GRAY);
Sleep.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Sleep();
}
});
JButton Wake = new JButton("Wake Up");
Wake.setBackground(Color.LIGHT_GRAY);
Wake.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Wake();
}
});
JButton Res = new JButton("Reset");
Res.setBackground(Color.LIGHT_GRAY);
Res.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Res();
}
});
JButton Food = new JButton("Food");
Food.setBackground(Color.LIGHT_GRAY);
Food.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Food();
}
});
JButton Info = new JButton("Info");
Info.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Info();
}
});
Info.setBackground(Color.LIGHT_GRAY);
JButton ExitAQP = new JButton("Exit");
ExitAQP.setBackground(Color.LIGHT_GRAY);
ExitAQP.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
ButtonPanel.add(Addanim);
ButtonPanel.add(Sleep);
ButtonPanel.add(Wake);
ButtonPanel.add(Res);
ButtonPanel.add(Food);
ButtonPanel.add(Info);
ButtonPanel.add(ExitAQP);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()=="Confirm Add")
{
if(JDA.GetDone())
{
FishSet.add(JDA.GetAnim()) ;
JOptionPane.showMessageDialog(this, JDA.GetAnim().getAnimalName());
}
}
}
public void setBackgr(int sel)
{
switch (sel)
{
case 0:
img=null;
this.setBackground(Color.WHITE);
break;
case 1:
img=null;
this.setBackground(Color.BLUE);
break;
case 2:
try {
img = ImageIO.read(new File("src/aquarium_background.jpg"));
} catch (IOException e) {
System.out.println("incorrect input image file path!!!!");
e.printStackTrace();
}
}
}
private void ConfirmAnimal()
{
if(JDA.GetAnim()!=null)
{
JOptionPane.showMessageDialog(this, "fish exists");
}
else
{
JOptionPane.showMessageDialog(this, "fish doesn't exists");
}
}
}
and the JDialog Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddAnimalDialog extends JDialog
{
private JTextField SizeField;
private JTextField HSpeedField;
private JTextField VSpeedField;
private int SelectedAnimal;
private int SelectedColor;
private Boolean IsDone;
private JButton SaveBTN;
Swimmable Animal;
public AddAnimalDialog(Swimmable Anim)
{
super();
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
IsDone = false;
gui();
Anim = Animal;
}
private void gui()
{
this.setSize(new Dimension(400, 300));
JPanel panel = new JPanel();
this.getContentPane().add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{151, 62, 63, 0};
gbl_panel.rowHeights = new int[]{20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel AnimName = new JLabel("Animal Type:");
GridBagConstraints gbc_AnimName = new GridBagConstraints();
gbc_AnimName.insets = new Insets(0, 0, 5, 5);
gbc_AnimName.gridx = 0;
gbc_AnimName.gridy = 1;
panel.add(AnimName, gbc_AnimName);
JComboBox AnimTypecomboBox = new JComboBox();
AnimTypecomboBox.addItem("Fish");
AnimTypecomboBox.addItem("Jellyfish");
GridBagConstraints gbc_AnimTypecomboBox = new GridBagConstraints();
gbc_AnimTypecomboBox.insets = new Insets(0, 0, 5, 5);
gbc_AnimTypecomboBox.anchor = GridBagConstraints.NORTH;
gbc_AnimTypecomboBox.gridx = 1;
gbc_AnimTypecomboBox.gridy = 1;
panel.add(AnimTypecomboBox, gbc_AnimTypecomboBox);
JLabel AnimSize = new JLabel("Size(between 20 to 320):");
GridBagConstraints gbc_AnimSize = new GridBagConstraints();
gbc_AnimSize.insets = new Insets(0, 0, 5, 5);
gbc_AnimSize.gridx = 0;
gbc_AnimSize.gridy = 2;
panel.add(AnimSize, gbc_AnimSize);
SizeField = new JTextField();
GridBagConstraints gbc_SizeField = new GridBagConstraints();
gbc_SizeField.insets = new Insets(0, 0, 5, 5);
gbc_SizeField.fill = GridBagConstraints.HORIZONTAL;
gbc_SizeField.gridx = 1;
gbc_SizeField.gridy = 2;
panel.add(SizeField, gbc_SizeField);
SizeField.setColumns(10);
JLabel HSpeed = new JLabel("Horizontal Speed(between 1 to 10):");
GridBagConstraints gbc_HSpeed = new GridBagConstraints();
gbc_HSpeed.insets = new Insets(0, 0, 5, 5);
gbc_HSpeed.gridx = 0;
gbc_HSpeed.gridy = 3;
panel.add(HSpeed, gbc_HSpeed);
HSpeedField = new JTextField();
GridBagConstraints gbc_HSpeedField = new GridBagConstraints();
gbc_HSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_HSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_HSpeedField.gridx = 1;
gbc_HSpeedField.gridy = 3;
panel.add(HSpeedField, gbc_HSpeedField);
HSpeedField.setColumns(10);
JLabel VSpeed = new JLabel("Vertical Speed(between 1 to 10):");
GridBagConstraints gbc_VSpeed = new GridBagConstraints();
gbc_VSpeed.insets = new Insets(0, 0, 5, 5);
gbc_VSpeed.gridx = 0;
gbc_VSpeed.gridy = 4;
panel.add(VSpeed, gbc_VSpeed);
VSpeedField = new JTextField();
GridBagConstraints gbc_VSpeedField = new GridBagConstraints();
gbc_VSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_VSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_VSpeedField.gridx = 1;
gbc_VSpeedField.gridy = 4;
panel.add(VSpeedField, gbc_VSpeedField);
VSpeedField.setColumns(10);
JLabel lblAnimalColor = new JLabel("Animal Color:");
GridBagConstraints gbc_lblAnimalColor = new GridBagConstraints();
gbc_lblAnimalColor.insets = new Insets(0, 0, 5, 5);
gbc_lblAnimalColor.gridx = 0;
gbc_lblAnimalColor.gridy = 5;
panel.add(lblAnimalColor, gbc_lblAnimalColor);
JComboBox ColorComboBox = new JComboBox();
ColorComboBox.setModel(new DefaultComboBoxModel(new String[] {"Red", "Magenta", "Cyan", "Blue", "Green"}));
GridBagConstraints gbc_ColorComboBox = new GridBagConstraints();
gbc_ColorComboBox.insets = new Insets(0, 0, 5, 5);
gbc_ColorComboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_ColorComboBox.gridx = 1;
gbc_ColorComboBox.gridy = 5;
panel.add(ColorComboBox, gbc_ColorComboBox);
JButton btnAddAnimal = new JButton("Confirm Add");
GetInput(btnAddAnimal,AnimTypecomboBox,ColorComboBox);
GridBagConstraints gbc_btnAddAnimal = new GridBagConstraints();
gbc_btnAddAnimal.insets = new Insets(0, 0, 0, 5);
gbc_btnAddAnimal.gridx = 0;
gbc_btnAddAnimal.gridy = 9;
panel.add(btnAddAnimal, gbc_btnAddAnimal);
JButton btnClear = new JButton("Clear");
GridBagConstraints gbc_btnClear = new GridBagConstraints();
gbc_btnClear.gridx = 2;
gbc_btnClear.gridy = 9;
panel.add(btnClear, gbc_btnClear);
}
private Color Getcolor(Object obj)
{
Color clr=Color.RED;
if(obj instanceof String)
{
switch((String)obj)
{
case "Red":
clr = Color.RED;
break;
case "Magenta":
clr = Color.MAGENTA;
break;
case "Cyan":
clr = Color.CYAN;
break;
case "Blue":
clr = Color.BLUE;
break;
case "Green":
clr = Color.GREEN;
break;
}
}
return clr;
}
private Fish MakeFish(int size,Color col,int horSpeed,int verSpeed)
{
return new Fish(size,col,horSpeed,verSpeed);
}
private Jellyfish MakeJellyfish(int size,Color col,int horSpeed,int verSpeed)
{
return new Jellyfish(size,col,horSpeed,verSpeed);
}
public Swimmable GetAnim()
{
return Animal;
}
public Boolean GetDone()
{
return IsDone;
}
private void GetInput(JButton Jbtn,JComboBox type,JComboBox col)
{
Jbtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Fish"))
{
Color clr=Color.RED;
Object tmp = col.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeFish(size,clr,Hspeed,VSpeed);
}
else if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Jellyfish"))
{
Color clr=Color.RED;
Object tmp = type.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeJellyfish(size,clr,Hspeed,VSpeed);
}
IsDone=true;
Hide();
SaveBTN = Jbtn;
}
});
}
private void Hide()
{
this.setVisible(false);
}
public JButton GetBTN()
{
return SaveBTN;
}
}
So in short in the JDialog i need to get information from comboboxes and texfields and send that data to an object constructor, and on the "Save" button click i need to transfer the Object from the JDialog that i created with the constructor to the JPanel, how do i do it?
i realized i can send the JPanel to the JDialog and in the JDialog's code where i create the object, i modify the Jpanel's Hashset accordingly

Can't get custom JPanel to show up on JDialog

I have developed my own properties type data structure for setting some basic data within an application. I was just using the regular properties, but I wanted the user to be able to edit these and then have notes, display order, and whether or not they are active. Also, to be able to group the different properties.
I created a panel that displays the property with an "Edit" button for them to actually make changes.
Then another panel that loads a group and displays all of the properties for that group.
Both of those panels seem to work fine. Then when I create a JDialog that should load all of the groups into a panel each, I can't get it to display. I have toyed with lots of layouts and no luck. In addition, I will need a scrollpane so when they grow overtime.
I am not quite sure what to do at this point...if I add buttons to the panel, it scrolls just fine, so I assume something is wrong with the Panel I am trying to add.
Here is the property group class:
import java.util.LinkedHashMap;
public class SMoKEPropertyGroup {
private String name = null;
private String notes = null;
private int displayOrder = 0;
private boolean active = true;
private LinkedHashMap<String, SMoKEProperty> properties = new LinkedHashMap<>();
public SMoKEPropertyGroup(String name, String notes, int displayOrder, boolean active) {
super();
this.name = name;
this.notes = notes;
this.displayOrder = displayOrder;
this.active = active;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public int getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(int displayOrder) {
this.displayOrder = displayOrder;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public LinkedHashMap<String, SMoKEProperty> getProperties() {
return properties;
}
public void addProperties(SMoKEProperty property) {
this.properties.put(property.getName(), property);
}
}
Here is the actual property class:
public class SMoKEProperty {
private String groupName = null;
private String name = null;
private String value = null;
private String notes = null;
private int displayOrder = 0;
private boolean active = true;
private String displayableName = null;
public SMoKEProperty(String groupName, String name, String value, String notes, int displayOrder, boolean active) {
super();
this.groupName = groupName;
this.name = name;
this.value = value;
this.notes = notes;
this.displayOrder = displayOrder;
this.active = active;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getName() {
return name;
}
public String getDisplayableName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public int getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(int displayOrder) {
this.displayOrder = displayOrder;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Override
public String toString() {
return "SMoKEProperty \n" + " groupName=" + groupName + "\ndisplayableName=" + getDisplayableName() + "\nname="
+ name + "\nvalue=" + value + "\nnotes=" + notes + "\ndisplayOrder=" + displayOrder + "\nactive="
+ active + "\n\n";
}
}
Here is the panel that displays a property:
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class PanelSmokeProperty extends JPanel {
private JLabel lblName = new JLabel();
public PanelSmokeProperty(SMoKEProperty prop) {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 318, 567, 97, 0 };
gridBagLayout.rowHeights = new int[] { 25, 0 };
gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
setLayout(gridBagLayout);
JButton btnEdit = new JButton("Edit");
lblName.setHorizontalAlignment(SwingConstants.RIGHT);
lblName.setFont(new Font("Tahoma", Font.PLAIN, 13));
GridBagConstraints gbc_lblName = new GridBagConstraints();
gbc_lblName.weighty = 0.4;
gbc_lblName.weightx = 0.4;
gbc_lblName.fill = GridBagConstraints.HORIZONTAL;
gbc_lblName.insets = new Insets(0, 0, 0, 5);
gbc_lblName.gridx = 0;
gbc_lblName.gridy = 0;
this.add(lblName, gbc_lblName);
lblName.setText(prop.getName() + " = ");
JLabel lblValue = new JLabel(prop.getValue());
GridBagConstraints gbc_lblValue = new GridBagConstraints();
gbc_lblValue.weighty = 0.4;
gbc_lblValue.weightx = 0.4;
gbc_lblValue.fill = GridBagConstraints.HORIZONTAL;
gbc_lblValue.insets = new Insets(0, 0, 0, 5);
gbc_lblValue.gridx = 1;
gbc_lblValue.gridy = 0;
add(lblValue, gbc_lblValue);
GridBagConstraints gbc_btnEdit = new GridBagConstraints();
gbc_btnEdit.weighty = 0.2;
gbc_btnEdit.weightx = 0.2;
gbc_btnEdit.anchor = GridBagConstraints.NORTH;
gbc_btnEdit.fill = GridBagConstraints.BOTH;
gbc_btnEdit.gridx = 2;
gbc_btnEdit.gridy = 0;
add(btnEdit, gbc_btnEdit);
}
}
Here is the panel to show a property group:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
public class PanelSmokePropertyGroup extends JPanel {
public PanelSmokePropertyGroup(SMoKEPropertyGroup propGroup) {
this.setBorder(new TitledBorder(null, propGroup.getName(), TitledBorder.LEADING, TitledBorder.TOP, null, null));
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 1133, 0 };
gridBagLayout.rowHeights = new int[] { 100, 176, 0 };
gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
setLayout(gridBagLayout);
JLabel lblLabelForDescription = new JLabel("Label for Description");
lblLabelForDescription.setPreferredSize(new Dimension(100, 75));
lblLabelForDescription.setVerticalAlignment(SwingConstants.TOP);
GridBagConstraints gbc_lblLabelForDescription = new GridBagConstraints();
gbc_lblLabelForDescription.anchor = GridBagConstraints.NORTH;
gbc_lblLabelForDescription.fill = GridBagConstraints.HORIZONTAL;
gbc_lblLabelForDescription.insets = new Insets(0, 0, 5, 0);
gbc_lblLabelForDescription.gridx = 0;
gbc_lblLabelForDescription.gridy = 0;
this.add(lblLabelForDescription, gbc_lblLabelForDescription);
JPanel panelForProperties = new JPanel();
GridBagConstraints gbc_panelForProperties = new GridBagConstraints();
gbc_panelForProperties.weighty = 1.0;
gbc_panelForProperties.weightx = 1.0;
gbc_panelForProperties.gridx = 0;
gbc_panelForProperties.gridy = 1;
add(panelForProperties, gbc_panelForProperties);
GridBagLayout gbl_panelForProperties = new GridBagLayout();
gbl_panelForProperties.columnWidths = new int[] { 0, 0 };
gbl_panelForProperties.rowHeights = new int[] { 0, 0 };
gbl_panelForProperties.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
gbl_panelForProperties.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
panelForProperties.setLayout(gbl_panelForProperties);
GridBagConstraints gbc_panelProperty = new GridBagConstraints();
gbc_panelProperty.fill = GridBagConstraints.HORIZONTAL;
gbc_panelProperty.gridx = 0;
// int scrollPaneHeight = (int) scrollPane.getBounds().getHeight();
// panelForProperties.setPreferredSize(new Dimension(749,
// scrollPaneHeight));
int y = 0;
for (SMoKEProperty p : propGroup.getProperties().values()) {
PanelSmokeProperty panelPropery = new PanelSmokeProperty(p);
gbc_panelProperty.gridy = y++;
panelForProperties.add(panelPropery, gbc_panelProperty);
}
}
public static void main(String... args) {
JFrame frame = new JFrame("test");
frame.setPreferredSize(new Dimension(700, 700));
PanelSmokePropertyGroup panel = new PanelSmokePropertyGroup(DialogProperties.getGroups().get("Group 1"));
// PanelSmokePropertyGroup2 panel2 = new
// PanelSmokePropertyGroup2(DialogProperties.getGroups().get("Group
// 2"));
frame.getContentPane().add(panel);
// frame.getContentPane().add(panel2);
frame.setVisible(true);
}
}
And finally, here is the JDialog that uses all that and won't show those panels properly:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.util.LinkedHashMap;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
public class DialogProperties extends JDialog {
private final JPanel contentPanel = new JPanel();
public static void main(String[] args) {
try {
DialogProperties dn = new DialogProperties();
dn.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dn.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public DialogProperties() {
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("System Properties");
setModal(true);
setBounds(100, 100, 869, 608);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 851, 0 };
gridBagLayout.rowHeights = new int[] { 561, 0 };
gridBagLayout.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
getContentPane().setLayout(gridBagLayout);
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc_contentPanel = new GridBagConstraints();
gbc_contentPanel.fill = GridBagConstraints.BOTH;
gbc_contentPanel.gridx = 0;
gbc_contentPanel.gridy = 0;
getContentPane().add(contentPanel, gbc_contentPanel);
GridBagLayout gbl_contentPanel = new GridBagLayout();
gbl_contentPanel.columnWidths = new int[] { 1, 800, 0 };
gbl_contentPanel.rowHeights = new int[] { 477, 50, 0 };
gbl_contentPanel.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
gbl_contentPanel.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
contentPanel.setLayout(gbl_contentPanel);
JScrollPane scrollPane = new JScrollPane();
// scrollPane.setBounds(12, 13, 1235, 382);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridwidth = 2;
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 0;
contentPanel.add(scrollPane, gbc_scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
panel.setLayout(new GridLayout(0, 1));
JButton okButton = new JButton("OK");
GridBagConstraints gbc_okButton = new GridBagConstraints();
gbc_okButton.ipady = 45;
gbc_okButton.ipadx = 45;
gbc_okButton.anchor = GridBagConstraints.SOUTHEAST;
gbc_okButton.gridx = 1;
gbc_okButton.gridy = 1;
contentPanel.add(okButton, gbc_okButton);
okButton.setActionCommand("OK");
getRootPane().setDefaultButton(okButton);
for (SMoKEPropertyGroup group : getGroups().values()) {
PanelSmokePropertyGroup p = new PanelSmokePropertyGroup(group);
panel.add(p);
}
}
public static LinkedHashMap<String, SMoKEPropertyGroup> getGroups() {
LinkedHashMap<String, SMoKEPropertyGroup> groups = new LinkedHashMap<>();
for (int i = 1; i <= 10; i++) {
SMoKEPropertyGroup g1 = new SMoKEPropertyGroup("Group " + i, "some notes", 0, true);
for (int p = 1; p <= 15; p++) {
g1.addProperties(new SMoKEProperty(g1.getName(), "Property " + p, "something", "notes", 0, true));
}
groups.put(g1.getName(), g1);
}
return groups;
}
}

Java GUI use one button to add multiple text fields to a text file?

I have to create a GUI that takes the input for multiple text fields, and when the user clicks one button, it adds all of the input to a text file. All the text fields will have to do with all the parts of an mp3 file. (artist/album, etc) Then, once the mp3 files are added to the text file, I have to create a button to edit or delete them. I'm confused as to how to make an "add" button for multiple text fields. Here is what I have so far:
public musicLib()
{
setLayout(new FlowLayout());
// Song Row
itemLabel = new JLabel("Item Code: ");
add(itemLabel);
itemCode = new JTextField(10);
add(itemCode);
descriptionLabel = new JLabel("Description: ");
add(descriptionLabel);
description = new JTextField(10);
add(description);
artistLabel = new JLabel("Artist: ");
add(artistLabel);
artist = new JTextField(10);
add(artist);
albumLabel = new JLabel("Album: ");
add(albumLabel);
album = new JTextField(10);
add(album);
// Buttons
addButton = new JButton("Add");
add(addButton);
Event e = new Event(); error"no suitable constructor found"
addButton.addActionListener(e); // error"incompatible types"
addButton.addActionListener(new ActionListener()
{
String nl = "\n",
data = "";
public void dataWriter(String data, String fileName) throws IOException {
File file = getFileStreamPath(fileName); // error"cannot find symbol"
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE); // error"cannot find symbol"
for (String string: data) // error"for- each not applicable to expression type"
{
writer.write(string.getBytes());
writer.flush();
}
writer.close();
}
}
Thank you guys very much for your help. I just need some help getting the one button to add multiple text field inputs to the text file. Thanks in advance!
This chunk, will be a part of the initial gui setup function:
/**
* On click listener for the add button
*/
addButton.addActionListener(new ActionListener() {
String nl = "\n",
data = "";
public void actionPerformed(ActionEvent ae){
data += "Label: " + albumLabel.getText() + nl;
data += "Artist: " + albumArtist.getText() + nl;
/*
* Repeat the same for any other text fields you have
*/
dataWriter(data, "test.txt");
}
});
And here is your file writer:
public void dataWriter(String data, String fileName) {
File file = getFileStreamPath(fileName);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);
for (String string: data){
writer.write(string.getBytes());
writer.flush();
}
writer.close();
}
If I correctly understand you, you want something like that;
StringBuilder sb = new StringBuilder();
sb.append("ItemLabel: "+itemLabel.getText()+"\n");
sb.append("Description: "+description.getText()+"\n");
and add what you need. When you write to file
out.write(sb.toString());
I wrote this very quick program to read and write field data using a Map of fields. The map consists of components and metadata on how to lay it out and whether its information is exportable or not.
It is far from complete, but with a little file IO, you can store and retrieve information and send it to the form as long as the incoming data matches the "schema" defined in the applications parsing logic.
Figure 1
Window after the "Edit" button is clicked.
Figure 2
Output after all fields' data has been exported to text; using the "Add" button.
Code
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
public class MusicApp extends JPanel {
private static final long serialVersionUID = 6555747177061710030L;
private static final String APP_TITLE = "Music App";
private static final int APP_WIDTH = 800;
private static final int APP_HEIGHT = 600;
private static class GridItem {
private JComponent component;
private boolean isExportable;
private int xPos;
private int yPos;
private int colSpan;
private int rowSpan;
public GridItem(JComponent component, boolean isExportable, int xPos, int yPos) {
this(component, isExportable, xPos, yPos, 1, 1);
}
public GridItem(JComponent component, boolean isExportable, int xPos, int yPos, int colSpan, int rowSpan) {
this.component = component;
this.isExportable = isExportable;
this.xPos = xPos;
this.yPos = yPos;
this.colSpan = colSpan;
this.rowSpan = rowSpan;
}
}
private int appWidth;
private int appHeight;
private Map<String, GridItem> componentMap;
private GridBagLayout layout;
private GridBagConstraints constraints;
public MusicApp(int width, int height) {
super();
this.appWidth = width;
this.appHeight = height;
this.init();
this.createChildren();
}
protected void init() {
this.constraints = new GridBagConstraints();
this.layout = new GridBagLayout();
this.componentMap = new LinkedHashMap<String, GridItem>();
// Disable size for now.
//this.setPreferredSize(new Dimension(appWidth, appHeight));
this.setLayout(this.layout);
this.constraints.ipadx = 3;
this.constraints.ipady = 3;
this.constraints.insets = new Insets(8, 4, 8, 4);
//JLabel itemLabel, descriptionLabel, artistLabel, albumLabel, priceLabel;
//JTextField itemCode, description, artist, album, price;
//JButton addButton,editButton, deleteButton;
this.constraints.anchor = GridBagConstraints.LAST_LINE_END;
componentMap.put("itemLabel", new GridItem(new JLabel("Item"), false, 0, 0, 3, 1));
this.constraints.fill = GridBagConstraints.HORIZONTAL;
componentMap.put("artistLabel", new GridItem(new JLabel("Artist"), false, 0, 1));
componentMap.put("artistText", new GridItem(new JTextField(), true, 1, 1, 2, 1));
componentMap.put("albumLabel", new GridItem(new JLabel("Album"), false, 0, 2));
componentMap.put("albumText", new GridItem(new JTextField(), true, 1, 2, 2, 1));
componentMap.put("priceLabel", new GridItem(new JLabel("Price"), false, 0, 3));
componentMap.put("priceText", new GridItem(new JTextField(), true, 1, 3, 2, 1));
componentMap.put("descriptionLabel", new GridItem(new JLabel("Description"), false, 0, 4));
componentMap.put("descriptionText", new GridItem(new JTextField(20), true, 1, 4, 2, 1));
componentMap.put("addButton", new GridItem(new JButton("Add"), false, 0, 5));
componentMap.put("editButton", new GridItem(new JButton("Edit"), false, 1, 5));
componentMap.put("deleteButton", new GridItem(new JButton("Delete"), false, 2, 5));
((JButton) componentMap.get("addButton").component).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(grabFieldData());
}
});;
((JButton) componentMap.get("editButton").component).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String[] lines = {
"artistText: Led Zeppelin",
"albumText: Houses of the Holy",
"priceText: 12.99",
"descriptionText: The fifth studio album by British rock band Led Zeppelin, released by Atlantic Records on 28 March 1973."
};
setFieldData(lines);
}
});;
((JButton) componentMap.get("deleteButton").component).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clearFieldData();
}
});;
}
protected void createChildren() {
Iterator<Map.Entry<String, GridItem>> it;
for (it = componentMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, GridItem> item = it.next();
GridItem gridItem = item.getValue();
this.constraints.gridx = gridItem.xPos;
this.constraints.gridy = gridItem.yPos;
this.constraints.gridwidth = gridItem.colSpan;
this.constraints.gridheight = gridItem.rowSpan;
this.add(gridItem.component, this.constraints);
}
}
private String grabFieldData() {
StringBuffer buff = new StringBuffer();
Iterator<Map.Entry<String, GridItem>> it;
for (it = componentMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, GridItem> item = it.next();
GridItem gridItem = item.getValue();
if (gridItem.isExportable) {
if (gridItem.component instanceof JTextComponent) {
buff.append(item.getKey()).append(": ")
.append(((JTextComponent) gridItem.component).getText())
.append("\n");
}
}
}
return buff.toString();
}
private void clearFieldData() {
Iterator<Map.Entry<String, GridItem>> it;
for (it = componentMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, GridItem> item = it.next();
GridItem gridItem = item.getValue();
if (gridItem.isExportable) {
if (gridItem.component instanceof JTextComponent) {
((JTextComponent) gridItem.component).setText("");
}
}
}
}
private void setFieldData(String[] textLines) {
clearFieldData();
for (String line : textLines) {
String[] values = line.split(":\\s*");
if (values.length == 2) {
GridItem gridItem = componentMap.get(values[0]);
if (gridItem.isExportable && gridItem.component instanceof JTextComponent) {
JTextComponent field = ((JTextComponent) gridItem.component);
field.setText(values[1]);
field.setCaretPosition(0);
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame(APP_TITLE);
f.setContentPane(new MusicApp(APP_WIDTH, APP_HEIGHT));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}

How do I add 2 separate JPanels together to get 1 JPanel?

I am trying to make a sign in program with a time clock display. I am having a hard time trying to get the clock into the already made JPanel. It currently pops up 2 seperate JPanels when I run the program. Please help with any suggestions.
CODE:
private static JLabel lblUserName;
private static JTextField txtUserName;
private static JButton btnSignIn;
private static JLabel lblPassword;
private static JPasswordField txtPassword;
private static JButton btnCancel;
private static JTabbedPane tabbedPane;
public static void main(String[] args)
{
UserSignIn frame = new UserSignIn();
JFrame frm = new JFrame();
SimpleDigitalClock clock1 = new SimpleDigitalClock();
frm.add(clock1);
//Pack
frm.pack();
frame.pack();
// Set origional focus on User Name text field
txtUserName.requestFocusInWindow();
// Make Visible
frame.setVisible(true);
frm.setVisible(true);
}
static class SimpleDigitalClock extends JPanel
{
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc)
{
this.stringTime = abc;
}
public int Number(int a, int b)
{
return (a <= b) ? a : b;
}
SimpleDigitalClock()
{
Timer t = new Timer(1000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v)
{
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10)
{
this.aHour = "0";
}
if (hour >= 10)
{
this.aHour = "";
}
if (minute < 10)
{
this.bMinute = "0";
}
if (minute >= 10)
{
this.bMinute = "";
}
if (second < 10)
{
this.cSecond = "0";
}
if (second >= 10)
{
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute+ minute + ":" + cSecond + second);
v.setColor(Color.RED);
int length = Number(this.getWidth(),this.getHeight());
Font Font1 = new Font("Digital", Font.BOLD, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length/6, length/2);
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(200, 200);
}
}
public UserSignIn()
{
initGUI();
}
public void initGUI()
{
setTitle("Login");
JPanel pnlUserSignIn = new JPanel(new GridBagLayout());
this.getContentPane().add(pnlUserSignIn);
//build table for employees signed in
JTable t = new JTable(null);
JLabel label = new JLabel("Employees Currently Signed In");
// ROW 1 BUTTONS
// Username and Sign In buttons
lblUserName = new JLabel("Username: ");
txtUserName = new JTextField("Username");
// Actions
//txtUserName.addMouseListener(this);
// Adding objects to Panel
JPanel pnlLogin = new JPanel();
pnlLogin.add(lblUserName);
pnlLogin.add(txtUserName);
//ROW 2 BUTTONS
//Password and Cancel
btnSignIn = new JButton("Sign In");
btnCancel=new JButton("Cancel");
//Actions
btnSignIn.addActionListener(this);
btnCancel.addActionListener(this);
// Adding objects to Panel
JPanel pnlPassword = new JPanel();
pnlPassword.add(btnSignIn);
pnlPassword.add(btnCancel);
JPanel detailsPanel = new JPanel();
detailsPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
// Putting Objects into the grid
gbc.gridx = 0;
gbc.gridy = 0;
pnlUserSignIn.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
pnlUserSignIn.add(new JScrollPane(t), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
pnlUserSignIn.add(pnlLogin, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
pnlUserSignIn.add(pnlPassword, gbc);
//gbc.gridx = 1;
//gbc.gridy = 1;
//gbc.gridwidth = 1;
//gbc.gridheight = 2;
//panel.add(detailsPanel, gbc);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent actionEvent)
{
if(actionEvent.getSource()==btnCancel)
{
System.exit(0);
}
//if(actionEvent.getSource()==txtUserName)
//{
// txtUserName.setText("");
// txtUserName.requestFocus();
//}
}
PLEASE IGNORE THE COMMENTED CODE, I am working on many things at once.
You don't need another frame. Just add clock to existing one. For example to the SOUTH:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.Timer;
public class UserSignIn extends JFrame implements ActionListener{
private static JLabel lblUserName;
private static JTextField txtUserName;
private static JButton btnSignIn;
private static JLabel lblPassword;
private static JPasswordField txtPassword;
private static JButton btnCancel;
private static JTabbedPane tabbedPane;
public static void main(String[] args) {
UserSignIn frame = new UserSignIn();
SimpleDigitalClock clock1 = new SimpleDigitalClock();
frame.add(clock1, BorderLayout.SOUTH);
// Pack
frame.pack();
// Set origional focus on User Name text field
txtUserName.requestFocusInWindow();
// Make Visible
frame.setVisible(true);
}
static class SimpleDigitalClock extends JPanel {
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc) {
this.stringTime = abc;
}
public int Number(int a, int b) {
return (a <= b) ? a : b;
}
SimpleDigitalClock() {
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v) {
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10) {
this.aHour = "0";
}
if (hour >= 10) {
this.aHour = "";
}
if (minute < 10) {
this.bMinute = "0";
}
if (minute >= 10) {
this.bMinute = "";
}
if (second < 10) {
this.cSecond = "0";
}
if (second >= 10) {
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute + minute + ":" + cSecond
+ second);
v.setColor(Color.RED);
int length = Number(this.getWidth(), this.getHeight());
Font Font1 = new Font("Digital", Font.BOLD, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length / 6, length / 2);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public UserSignIn() {
initGUI();
}
public void initGUI() {
setTitle("Login");
JPanel pnlUserSignIn = new JPanel(new GridBagLayout());
this.getContentPane().add(pnlUserSignIn);
// build table for employees signed in
JTable t = new JTable(null);
JLabel label = new JLabel("Employees Currently Signed In");
// ROW 1 BUTTONS
// Username and Sign In buttons
lblUserName = new JLabel("Username: ");
txtUserName = new JTextField("Username");
// Actions
// txtUserName.addMouseListener(this);
// Adding objects to Panel
JPanel pnlLogin = new JPanel();
pnlLogin.add(lblUserName);
pnlLogin.add(txtUserName);
// ROW 2 BUTTONS
// Password and Cancel
btnSignIn = new JButton("Sign In");
btnCancel = new JButton("Cancel");
// Actions
btnSignIn.addActionListener(this);
btnCancel.addActionListener(this);
// Adding objects to Panel
JPanel pnlPassword = new JPanel();
pnlPassword.add(btnSignIn);
pnlPassword.add(btnCancel);
JPanel detailsPanel = new JPanel();
detailsPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
// Putting Objects into the grid
gbc.gridx = 0;
gbc.gridy = 0;
pnlUserSignIn.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
pnlUserSignIn.add(new JScrollPane(t), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
pnlUserSignIn.add(pnlLogin, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
pnlUserSignIn.add(pnlPassword, gbc);
// gbc.gridx = 1;
// gbc.gridy = 1;
// gbc.gridwidth = 1;
// gbc.gridheight = 2;
// panel.add(detailsPanel, gbc);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getSource() == btnCancel) {
System.exit(0);
}
// if(actionEvent.getSource()==txtUserName)
// {
// txtUserName.setText("");
// txtUserName.requestFocus();
// }
}
}

Bidirectional databinding on WindowBuilder seems not to work

I'm developing my first JDialog with Eclipse Juno, WindowBuilder, "Swing Automatic Databinding" (beansbinding-1.2.1.jar) on Java7 SE.
I'm curious to test auto-databinding
I got an editing dialog for the class User with the help of Eclipse Databinding GUI only.
package it.marcuzzi.databindtest;
public class User {
private String name;
private int age;
public User() {}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
My dialog opens with its text fields containing correct initial values from a User instance. When I modify text-fields texts and then click the Ok button, I can see no changes to the User instance.
Here is my dialog code .....
package it.marcuzzi.databindtest;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.beansbinding.Bindings;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class UserJDialog extends JDialog {
private static final long serialVersionUID = 7043021546503322090L;
private BindingGroup m_bindingGroup;
private JPanel m_contentPane;
private it.marcuzzi.databindtest.User user = new it.marcuzzi.databindtest.User();
private JTextField nameJTextField;
private JTextField ageJTextField;
private JButton btnOk;
public static void main(String[] args) {
try {
UserJDialog dialog = new UserJDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public UserJDialog() {
user.setName("marco");
user.setAge(10);
setBounds(100, 100, 450, 300);
m_contentPane = new JPanel();
setContentPane(m_contentPane);
//
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 0, 0, 0 };
gridBagLayout.rowHeights = new int[] { 0, 0, 0, 0, 0, 0 };
gridBagLayout.columnWeights = new double[] { 0.0, 1.0, 1.0E-4 };
gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0E-4 };
m_contentPane.setLayout(gridBagLayout);
JLabel nameLabel = new JLabel("Name:");
GridBagConstraints labelGbc_0 = new GridBagConstraints();
labelGbc_0.insets = new Insets(5, 5, 5, 5);
labelGbc_0.gridx = 0;
labelGbc_0.gridy = 0;
m_contentPane.add(nameLabel, labelGbc_0);
nameJTextField = new JTextField();
GridBagConstraints componentGbc_0 = new GridBagConstraints();
componentGbc_0.insets = new Insets(5, 0, 5, 0);
componentGbc_0.fill = GridBagConstraints.HORIZONTAL;
componentGbc_0.gridx = 1;
componentGbc_0.gridy = 0;
m_contentPane.add(nameJTextField, componentGbc_0);
JLabel ageLabel = new JLabel("Age:");
GridBagConstraints labelGbc_1 = new GridBagConstraints();
labelGbc_1.insets = new Insets(5, 5, 5, 5);
labelGbc_1.gridx = 0;
labelGbc_1.gridy = 1;
m_contentPane.add(ageLabel, labelGbc_1);
ageJTextField = new JTextField();
GridBagConstraints componentGbc_1 = new GridBagConstraints();
componentGbc_1.insets = new Insets(5, 0, 5, 0);
componentGbc_1.fill = GridBagConstraints.HORIZONTAL;
componentGbc_1.gridx = 1;
componentGbc_1.gridy = 1;
m_contentPane.add(ageJTextField, componentGbc_1);
btnOk = new JButton("Ok");
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println( "Name: "+user.getName()+"\tAge: "+user.getAge());
UserJDialog.this.setVisible(false);
}
});
GridBagConstraints gbc_btnOk = new GridBagConstraints();
gbc_btnOk.gridx = 1;
gbc_btnOk.gridy = 4;
m_contentPane.add(btnOk, gbc_btnOk);
if (user != null) {
m_bindingGroup = initDataBindings();
}
}
protected BindingGroup initDataBindings() {
BeanProperty<it.marcuzzi.databindtest.User, java.lang.String> nameProperty = BeanProperty.create("name");
BeanProperty<javax.swing.JTextField, java.lang.String> textProperty = BeanProperty.create("text");
AutoBinding<it.marcuzzi.databindtest.User, java.lang.String, javax.swing.JTextField, java.lang.String> autoBinding = Bindings
.createAutoBinding(AutoBinding.UpdateStrategy.READ_WRITE, user, nameProperty, nameJTextField, textProperty);
autoBinding.bind();
//
BeanProperty<it.marcuzzi.databindtest.User, java.lang.Integer> ageProperty = BeanProperty.create("age");
BeanProperty<javax.swing.JTextField, java.lang.String> textProperty_1 = BeanProperty.create("text");
AutoBinding<it.marcuzzi.databindtest.User, java.lang.Integer, javax.swing.JTextField, java.lang.String> autoBinding_1 = Bindings
.createAutoBinding(AutoBinding.UpdateStrategy.READ_WRITE, user, ageProperty, ageJTextField, textProperty_1);
autoBinding_1.bind();
//
BindingGroup bindingGroup = new BindingGroup();
bindingGroup.addBinding(autoBinding);
bindingGroup.addBinding(autoBinding_1);
//
return bindingGroup;
}
public it.marcuzzi.databindtest.User getUser() {
return user;
}
public void setUser(it.marcuzzi.databindtest.User newUser) {
setUser(newUser, true);
}
public void setUser(it.marcuzzi.databindtest.User newUser, boolean update) {
user = newUser;
if (update) {
if (m_bindingGroup != null) {
m_bindingGroup.unbind();
m_bindingGroup = null;
}
if (user != null) {
m_bindingGroup = initDataBindings();
}
}
}
}
Binding update strategies are all READ_WRITE so I can't understand why it doesn't update User instance!
Any idea ?
Thanks,
Marco
Actually, it is updating the User instance but your widgets aren't get notified about it. You have to fire a PropertyChangeEvent in your setters. Here's an example:
import java.beans.*;
public class Foo {
private int bar;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public int getBar() { return bar; }
public void setBar(int bar) {
int oldValue = this.bar;
this.bar = bar;
pcs.firePropertyChange("bar", oldValue, bar);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
pcs.addPropertyChangeListener(pcl);
}
public void removePropertyChangeListener(PropertyChangeListener pcl) {
pcs.removePropertyChangeListener(pcl);
}
}

Categories