Related
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!
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
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);
}
});
}
}
I know there are already many topics on this issue but I promise you I have exhausted the search.
At the opening of my application, the "ExampleGUI" window should display, when a Calendar button is clicked a Calendar Frame pops up and the user chooses a date, which is represented as a String. This string, along with some other information, is passed back to the ExampleGUI, as a new ExampleGUI. It will then go to the method updateDate, which should display the date that the user chose on the current frame, as a JLabel. However, no matter what I try, the JLabel will not display or will not update. I know about SetText, it's not currently included in my code but I have tried it and it doesn't work. I know it is passing the date correctly because System.out.println will work fine. If you have any help I will be forever grateful I am officially stumped.
UPDATE
Added the most pared down code I could make -- sorry the Calendar is so long, I couldn't take much out but I promise it is not the problem you just need it to run the GUI where the problem resides.
Thanks!
CODE:
Runner Class:
import java.awt.EventQueue;
public class Runner {
public Runner() {
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
GUI frame = new GUI();
frame.setVisible(true);
}
});
}
}
GUI Class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame {
private JPanel contentPane;
public String newDate;
public String myStartEnd;
public String StartDate;
public JLabel lblFinalStartDate;
public JLabel lblFinalEndDate;
public JPanel panelSearchCriteria = new JPanel();
public GUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
GridBagConstraints gbc_panelSearchCriteria = new GridBagConstraints();
gbc_panelSearchCriteria.gridx = 0;
gbc_panelSearchCriteria.gridy = 0;
contentPane.add(panelSearchCriteria, gbc_panelSearchCriteria);
GridBagLayout gbl_panelSearchCriteria = new GridBagLayout();
panelSearchCriteria.setLayout(gbl_panelSearchCriteria);
JButton btnChooseSDate = new JButton("Choose Date");
btnChooseSDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String source = new String("Start");
Calndar startCal = new Calndar(source);
}
});
GridBagConstraints gbc_btnChooseSDate = new GridBagConstraints();
gbc_btnChooseSDate.gridx = 1;
gbc_btnChooseSDate.gridy = 1;
panelSearchCriteria.add(btnChooseSDate, gbc_btnChooseSDate);
}
public GUI(String str, String soE) {
this();
updateDate(str, soE);
}
public void updateDate(String d, String se) {
String tempdate = new String(d + "");
String answer = new String(se + "");
if (answer.equals("Start")) {
StartDate = new String(tempdate + "");
lblFinalStartDate = new JLabel(StartDate);
GridBagConstraints gbc_lblFinalStartDate = new GridBagConstraints();
gbc_lblFinalStartDate.insets = new Insets(0, 0, 0, 5);
gbc_lblFinalStartDate.gridx = 2;
gbc_lblFinalStartDate.gridy = 1;
this.panelSearchCriteria.add(lblFinalStartDate, gbc_lblFinalStartDate);
System.out.println(lblFinalStartDate.getText());
}else{
}
}
}
Calendar Class:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class Calndar extends JFrame {
private JPanel contentPane;
private JTable table;
public int realDay, realMonth, realYear, currentMonth, currentYear;
public JButton btnPrev = new JButton("<<");
public JButton btnNext = new JButton(">>");
public JLabel Monthlabel = new JLabel("");
public int returnedDAY, returnedMONTH, returnedYEAR;
public String FinalDate;
public Calndar(String SoE) {
setBounds(100, 100, 330, 430);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
GregorianCalendar cal = new GregorianCalendar();
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH);
realMonth = cal.get(GregorianCalendar.MONTH);
realYear = cal.get(GregorianCalendar.YEAR);
currentMonth = realMonth;
currentYear = realYear;
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.insets = new Insets(0, 0, 5, 5);
gbc_label.gridx = 1;
gbc_label.gridy = 0;
panel.add(Monthlabel, gbc_label);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridwidth = 3;
gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 1;
panel.add(scrollPane, gbc_scrollPane);
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowHeight(35);
table.setCellSelectionEnabled(true);
table.setModel(new DefaultTableModel(
new Object[][] { { null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, { null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, { null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, },
new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }));
scrollPane.setViewportView(table);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnChoose = new JButton("Select");
btnChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if (row == (-1) || col == (-1)) {
JOptionPane.showMessageDialog(null, "Please Select a Date", "Error", JOptionPane.WARNING_MESSAGE);
} else {
returnDate(row, col);
GUI DS1 = new GUI(getFinalDate(), SoE);
dispose();
}
}
});
btnChoose.setMargin(new Insets(5, 20, 5, 20));
panel_1.add(btnChoose);
refreshCalendar(realMonth, realYear);
setVisible(true);
}
public void refreshCalendar(int M, int Y) {
int nod, som;
Monthlabel.setText("July");
GregorianCalendar cal = new GregorianCalendar(Y, M, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
table.setValueAt(null, i, j);
}
}
for (int i = 1; i <= nod; i++) {
int row = new Integer((i + som - 2) / 7);
int column = ((i + som - 2) % 7);
table.setValueAt(i, row, column);
}
}
public String returnDate(int r, int c) {
returnedYEAR = 2015;
returnedMONTH = 7;
returnedDAY = (int) table.getValueAt(r, c);
FinalDate = new String("" + returnedYEAR + "-" + returnedMONTH + "-" + returnedDAY);
return FinalDate;
}
public String getFinalDate(){
if(FinalDate.equals(null)){
String str = new String("None");
return str;
}else{
return FinalDate;
}
}
}
Your problem is here:
btnChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if (row == (-1) || col == (-1)) {
JOptionPane.showMessageDialog(null, "Please Select a Date",
"Error", JOptionPane.WARNING_MESSAGE);
} else {
returnDate(row, col);
GUI DS1 = new GUI(getFinalDate(), SoE); // *****************
dispose();
}
}
});
You are creating a new GUI object, one completely distinct from the currently displayed GUI instance.
suggestions:
The new window should not be a JFrame but should be a modal JDialog. If it is a modal dialog, it will freeze the calling code from the point that it is set visible, and then that code will resume flow once the dialog is no longer visible.
Set this dialog visible from the original class, the GUI's ActionListener.
Don't have Calndar object change anything in GUI. Rather in its action listener store the selected date (if anything is selected) in a field, and dispose of the dialog.
Then the calling class, here GUI can query the Calndar object once it is no Calndar is longer visible, within GUI's select ActionListener, but after Calndar is set visible, and extract the selected date by calling a public getter method on the Calndar object.
Then GUI can use this information to update its visualized data.
Call revalidate and repaint after adding or removing components from a running GUI.
In the future, try to use only 1 file for your example program.
For example. Note in the code below major changes are commented with // !!:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.GregorianCalendar;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class GUI extends JFrame {
private JPanel contentPane;
public String newDate;
public String myStartEnd;
public String StartDate;
public JLabel lblFinalStartDate;
public JLabel lblFinalEndDate;
public JPanel panelSearchCriteria = new JPanel();
public GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
GridBagConstraints gbc_panelSearchCriteria = new GridBagConstraints();
gbc_panelSearchCriteria.gridx = 0;
gbc_panelSearchCriteria.gridy = 0;
contentPane.add(panelSearchCriteria, gbc_panelSearchCriteria);
GridBagLayout gbl_panelSearchCriteria = new GridBagLayout();
panelSearchCriteria.setLayout(gbl_panelSearchCriteria);
JButton btnChooseSDate = new JButton("Choose Date");
btnChooseSDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String source = new String("Start");
Calndar startCal = new Calndar(GUI.this, source); // !!
startCal.setVisible(true); // !!
String finalDate = startCal.getFinalDate();
updateDate(finalDate, source); // !!
}
});
GridBagConstraints gbc_btnChooseSDate = new GridBagConstraints();
gbc_btnChooseSDate.gridx = 1;
gbc_btnChooseSDate.gridy = 1;
panelSearchCriteria.add(btnChooseSDate, gbc_btnChooseSDate);
}
public GUI(String str, String soE) {
this();
updateDate(str, soE);
}
public void updateDate(String d, String se) {
String tempdate = new String(d + "");
String answer = new String(se + "");
if (answer.equals("Start")) {
StartDate = new String(tempdate + "");
lblFinalStartDate = new JLabel(StartDate);
GridBagConstraints gbc_lblFinalStartDate = new GridBagConstraints();
gbc_lblFinalStartDate.insets = new Insets(0, 0, 0, 5);
gbc_lblFinalStartDate.gridx = 2;
gbc_lblFinalStartDate.gridy = 1;
this.panelSearchCriteria.add(lblFinalStartDate, gbc_lblFinalStartDate);
System.out.println(lblFinalStartDate.getText());
revalidate(); // !!
repaint(); // !!
} else {
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
GUI frame = new GUI();
frame.setVisible(true);
}
});
}
}
class Calndar extends JDialog { // !!
private JPanel contentPane;
private JTable table;
public int realDay, realMonth, realYear, currentMonth, currentYear;
public JButton btnPrev = new JButton("<<");
public JButton btnNext = new JButton(">>");
public JLabel Monthlabel = new JLabel("");
public int returnedDAY, returnedMONTH, returnedYEAR;
public String FinalDate;
public Calndar(GUI gui, final String SoE) { // !!
super(gui, "Calndar Title", ModalityType.APPLICATION_MODAL); // !!
setBounds(100, 100, 330, 430);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
GregorianCalendar cal = new GregorianCalendar();
realDay = cal.get(GregorianCalendar.DAY_OF_MONTH);
realMonth = cal.get(GregorianCalendar.MONTH);
realYear = cal.get(GregorianCalendar.YEAR);
currentMonth = realMonth;
currentYear = realYear;
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.insets = new Insets(0, 0, 5, 5);
gbc_label.gridx = 1;
gbc_label.gridy = 0;
panel.add(Monthlabel, gbc_label);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridwidth = 3;
gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 1;
panel.add(scrollPane, gbc_scrollPane);
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowHeight(35);
table.setCellSelectionEnabled(true);
table.setModel(new DefaultTableModel(new Object[][] {
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null },
{ null, null, null, null, null, null, null }, }, new String[] {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }));
scrollPane.setViewportView(table);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnChoose = new JButton("Select");
btnChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if (row == (-1) || col == (-1)) {
JOptionPane.showMessageDialog(null, "Please Select a Date",
"Error", JOptionPane.WARNING_MESSAGE);
} else {
returnDate(row, col);
// !! GUI DS1 = new GUI(getFinalDate(), SoE);
dispose();
}
}
});
btnChoose.setMargin(new Insets(5, 20, 5, 20));
panel_1.add(btnChoose);
refreshCalendar(realMonth, realYear);
// setVisible(true);
}
public void refreshCalendar(int M, int Y) {
int nod, som;
Monthlabel.setText("July");
GregorianCalendar cal = new GregorianCalendar(Y, M, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
table.setValueAt(null, i, j);
}
}
for (int i = 1; i <= nod; i++) {
int row = new Integer((i + som - 2) / 7);
int column = ((i + som - 2) % 7);
table.setValueAt(i, row, column);
}
}
public String returnDate(int r, int c) {
returnedYEAR = 2015;
returnedMONTH = 7;
returnedDAY = (int) table.getValueAt(r, c);
FinalDate = new String("" + returnedYEAR + "-" + returnedMONTH + "-"
+ returnedDAY);
return FinalDate;
}
public String getFinalDate() {
if (FinalDate.equals(null)) {
String str = new String("None");
return str;
} else {
return FinalDate;
}
}
}
Also:
I wouldn't add a JLabel when adding the date in the main GUI. Rather I'd create a JLabel field, add it to the GUI initially, and then simply set its text when the need arises.
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);
}
}