Modify a JLabel inside a void method - combobox

Please i need your help, im trying to do that i want 3-4 days now and i cant.
I have 2 Classes MainForm and Class2.
I have a JLablel inside a method at Class1 and i want to modify it by pressing a button from the Class2.
public class MainForm {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainForm window = new MainForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(400, 200, 488, 322);
frame.setTitle("ShutDown");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setResizable(false);
/**
* Time BOX
*/
JComboBox<String> timeBox = new JComboBox<String>();
timeBox.setBounds(73, 142, 90, 20);
timeBox.addItem("Days");
timeBox.addItem("Hours");
timeBox.addItem("Minutes");
timeBox.addItem("Seconds");
timeBox.addItem("Right now");
timeBox.setSelectedItem("Minutes");
frame.getContentPane().add(timeBox);
String getTimeBox = timeBox.getSelectedItem().toString();
/**
* The label info.
*/
JLabel labelInfo = new JLabel("");
labelInfo.setBounds(73, 209, 310, 14);
frame.getContentPane().add(labelInfo);
labelInfo.setText(getTimeBox);
}
and the Class 2
Class2
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
i tried much and allways doesnt work, whats the code i need to write in that button to get the selectedItem from the timeBox (comboBox)
and put it to that label?

First of all you need references of both
JComboBox & JLable objects in class 2.
Simple way to do that is to declare respective private members in MainForm instead of local members of initialize method & pass them in to the constructor or use setter method approach.
Let consider that the reference names are jComboBox & jLable respectively.
Now you can use following syntax to reference them from actionPerformed method of the anonymous class using this syntax Class2.this.jComboBox & Class2.this.jLable (jComboBox & jLable is object reference).

Related

GMAP.NET, adding labels to markers

I am using GMAPS in C# (Winforms) and I would like to add a marker with a label. I followed the answer at GMAP.NET adding labels underneath markers and noticed that there is an issue with the implementation. The markers are not plotted in the correct place and the labels are all plotted on top of each other. I think it is not correctly calling the OnRender method for the marker? Can anyone point me in the right direction?
In ran into the same issue and just calling base.OnRender(g); wasn't fixing it for me. The trick is to derive from GMarkerGoogle instead of GMapMarker as done in the answer you provided.
Also I had to do some tweaks with the text rendering. I came up with this solutions, works fine for me:
public class GmapMarkerWithLabel : GMarkerGoogle, ISerializable
{
private readonly Font _font;
private GMarkerGoogle _innerMarker;
private readonly string _caption;
public GmapMarkerWithLabel(PointLatLng p, string caption, GMarkerGoogleType type)
: base(p, type)
{
_font = new Font("Arial", 11);
_innerMarker = new GMarkerGoogle(p, type);
_caption = caption;
}
public override void OnRender(Graphics g)
{
base.OnRender(g);
var stringSize = g.MeasureString(_caption, _font);
var localPoint = new PointF(LocalPosition.X - stringSize.Width / 2, LocalPosition.Y + stringSize.Height);
g.DrawString(_caption, _font, Brushes.Black, localPoint);
}
public override void Dispose()
{
if (_innerMarker != null)
{
_innerMarker.Dispose();
_innerMarker = null;
}
base.Dispose();
}
#region ISerializable Members
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
GetObjectData(info, context);
}
protected GmapMarkerWithLabel(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endregion
}

JavaFX 8: Checkbox in TableView and Add-on into to selected Item?

I would like to create a payroll program such that when the user tick a CheckBox in TableView, the name (String) will be carried on to the panel on the right and with TextFields to enter more info such as this:
I tried to follow the MVC hierarchy thus far as I code:
PayrollMainApp.java
public class PayrollMainApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Employee> selectEmployeeTable = FXCollections.observableArrayList();
public PayrollMainApp(){
selectEmployeeTable.add(new Employee(false,"Hans Muster"));
selectEmployeeTable.add(new Employee(true,"Ruth Mueller"));
selectEmployeeTable.add(new Employee(false,"Heinz Kurz"));
selectEmployeeTable.add(new Employee(false,"Cornelia Meier"));
selectEmployeeTable.add(new Employee(false,"Werner Meyer"));
selectEmployeeTable.add(new Employee(false,"Lydia Kunz"));
selectEmployeeTable.add(new Employee(false,"Anna Best"));
selectEmployeeTable.add(new Employee(false,"Stefan Meier"));
selectEmployeeTable.add(new Employee(false,"Martin Mueller"));
}
public ObservableList<Employee> getSelectEmployeeTable(){
return selectEmployeeTable;
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("PayrollApp");
initRootLayout();
showEmployeeOverview();
}
/**
* Initializes the root layout.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(PayrollMainApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Shows the person overview inside the root layout.
*/
public void showEmployeeOverview() {
try {
// Load person overview.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(PayrollMainApp.class.getResource("view/EmployeeOverview.fxml"));
AnchorPane personOverview = (AnchorPane) loader.load();
// Set person overview into the center of root layout.
rootLayout.setCenter(personOverview);
// Give the controller access to the main app
EmployeeOverviewController controller = loader.getController();
controller.setMainApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the main stage.
* #return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
Employee.java
public class Employee {
private BooleanProperty checkedBox = new SimpleBooleanProperty(false);
private StringProperty employeeName = new SimpleStringProperty();
public Employee(){
super();
}
public Employee(boolean checkedBox, String employeeName){
this.checkedBox = new SimpleBooleanProperty(false);
this.employeeName = new SimpleStringProperty(employeeName);
}
public BooleanProperty checkedBoxProperty(){
return this.checkedBox;
}
public StringProperty employeeNameProperty(){
return this.employeeName;
}
public java.lang.Boolean getSelectBox() {
return this.checkedBoxProperty().get();
}
public StringProperty getEmployeeName() {
return employeeName;
}
public void setSelectBox(final java.lang.Boolean checkedBox){
this.checkedBoxProperty().set(checkedBox);
}
public void setEmployeeName(StringProperty employeeName) {
this.employeeName = employeeName;
}
}
EmployeeOverviewController.java
public class EmployeeOverviewController {
#FXML
private TableView<Employee> selectEmployeeTable;
#FXML
private TableColumn<Employee, String> employeeNameColumn;
#FXML
private TableColumn<Employee, Boolean> checkBoxColumn;
private PayrollMainApp mainApp;
public EmployeeOverviewController() {
}
#FXML
public void initialize() {
checkBoxColumn.setCellValueFactory(cellData -> cellData.getValue().checkedBoxProperty());
checkBoxColumn.setCellFactory(param -> new CheckBoxTableCell<Employee, Boolean>());
employeeNameColumn.setCellValueFactory(cellData -> cellData.getValue().employeeNameProperty());
}
public void setMainApp(PayrollMainApp mainApp){
this.mainApp = mainApp;
//Add observable list data to the table
selectEmployeeTable.setItems(mainApp.getSelectEmployeeTable());
}
}
And a util class to make the checkBox visible in the table:
SelectBoxCellFactory.java
public class SelectBoxCellFactory implements Callback {
#Override
public TableCell call(Object param) {
CheckBoxTableCell<Employee,Boolean> checkBoxCell = new CheckBoxTableCell();
return checkBoxCell;
}
}
Here is my output thus far:
I know this has a table in it as compared to the previous output. Honestly I'm still indecisive as to use which, because I think using TextFields would make it look better. But all I hope for now is that this design is not impossible to code...
I really hope you can help me... Thank you for your help in advance.
It's probably easiest to use a TableView for the right panel. You can create a FilteredList from your original list:
FilteredList<Employee> selectedEmployees
= new FilteredList<>(selectEmployeeTable, Employee::getSelectBox);
and then use that for your second table.
If you prefer to use text fields (in what looks like a GridPane?) you can still use the filtered list above, but you will need to register a listener with it and update the layout "by hand" when items are added and removed.

Event handler for array

Have we event handler,event listener,action listener or any like these, for arrayin any compile-based language (e.g. Java,c++,c)?
I am searching a way to track the changes of an array. So when value of a cell changed the listener notify me about this change and the cell number that this changed occurred for it.
is there any language or any option for this problem?
Edit
If you do not want to use a custom type you can have a look at this implementation to observe when an array is changed : http://www.codeproject.com/Articles/162966/Observing-Changes-to-an-Underlying-Array
Here is an example from Microsoft in C# that does what you are looking for with an ArrayList
http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx
// events1.cs
using System;
namespace MyCollections
{
using System.Collections;
// A delegate type for hooking up change notifications.
public delegate void ChangedEventHandler(object sender, EventArgs e);
// A class that works just like ArrayList, but sends event
// notifications whenever the list changes.
public class ListWithChangedEvent: ArrayList
{
// An event that clients can use to be notified whenever the
// elements of the list change.
public event ChangedEventHandler Changed;
// Invoke the Changed event; called whenever list changes
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
Changed(this, e);
}
// Override some of the methods that can change the list;
// invoke event after each
public override int Add(object value)
{
int i = base.Add(value);
OnChanged(EventArgs.Empty);
return i;
}
public override void Clear()
{
base.Clear();
OnChanged(EventArgs.Empty);
}
public override object this[int index]
{
set
{
base[index] = value;
OnChanged(EventArgs.Empty);
}
}
}
}
namespace TestEvents
{
using MyCollections;
class EventListener
{
private ListWithChangedEvent List;
public EventListener(ListWithChangedEvent list)
{
List = list;
// Add "ListChanged" to the Changed event on "List".
List.Changed += new ChangedEventHandler(ListChanged);
}
// This will be called whenever the list changes.
private void ListChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event fires.");
}
public void Detach()
{
// Detach the event and delete the list
List.Changed -= new ChangedEventHandler(ListChanged);
List = null;
}
}
class Test
{
// Test the ListWithChangedEvent class.
public static void Main()
{
// Create a new list.
ListWithChangedEvent list = new ListWithChangedEvent();
// Create a class that listens to the list's change event.
EventListener listener = new EventListener(list);
// Add and remove items from the list.
list.Add("item 1");
list.Clear();
listener.Detach();
}
}
}

C# Send text from Form2 textbox to Form1 Textbox

I need some help, i want to set text from a textbox from Form2.cs to the another textbox in Form1.cs but i keep getting this error:
Error 2 An object reference is required for the non-static field, method, or property.
I'm coding in c# and i cannot find it anywhere on the internet how to do this?
you have to provide an istance of Form2 to Form1. Fore example you can pass it in the constructor like:
public Form2(Form1 frm)
and then you can call something like this
this.TextBox1.Text = frm.TextBox1.Text
I'm writing this answer only based your error code.
You try to access a non-static method without using any instance of belongs it class object. For example; this code will fail.
class Program
{
public static void Main()
{
WriteMethod();
}
public void WriteMethod()
{
Console.Writeline("Succes!");
}
}
But this code works;
class Program
{
public static void Main()
{
Program p = new Program();
p.WriteMethod();
}
public void WriteMethod()
{
Console.Writeline("Succes!");
}
}
Hope you get the main point.
Well your case is too simple, you can do too many things in order to exchange data between classes
Why don't you try saving data in another static class, or a singleton one...
//this code worked for me
//in form2 put following code prevent form from opening multiple times
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private static Form2 Instance;
public static Form2 GetInstance()
{
if (Instance ==null || Instance.IsDisposed)
{
Instance = new Form2();
}
else
{
Instance.BringToFront();
}
return Instance;
}
// in form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button2_Click(object sender, EventArgs e)
{
Form2 form2 = Form2.GetInstance();
form2.textBox1.Text = textBox1.Text;
form2.Show();
}
}

Many objects with global and local state

I'm looking for the best Design for the following situation.
We have many objects form one class, for instance a picture frame. Now each of the picture frames can display 3 types of picture. 1) a face 2) a screenshot 3) empty
Thats easy:
public enum PictureMode
{
Face,
Screen,
None
}
public class PictureFrame {
private PictureMode mode;
public PictureMode Mode
{
get { retrun mode; }
set { /* set currentPicture to the correct one */ }
}
private Image currentPicture;
private Image face;
private Image screen;
private Image empty;
public PictureFrame(Image face, Image screen) {
this.face = face;
this.screen = screen;
mode = PictureMode.None; // Maybe this is our default.
}
}
We can now create some PictureFrames with different pictures and easily change the mode for each one.
Now I want to add a global setter for all PictureFrames. Then each new PictureFrame should take the global setting as the default one. It can later be set to an different through.
Here is my solution, but I want to discuss if there is a better one.
I added a static field PictureFrame.Instances to the PictureFrame class where all PictureFrames are reachable. Now I can iterate over all the PictureFrames to apply the new global mode to all frames.
In addition I have a second static field PictureFrame.GlobalImageMode where I set the global mode if I change it on all Frames and read it in the Constructor of the PictureFrame. The setter for the GlobalImageMode can be static in the PictureFrame class, too.
Just wild shot here...: Why don't you always use getter for current frame mode with a condition in it:
class PictureFrame {
private PictureMode instanceMode;
private static PictureMode? globalMode;
private PictureMode CurrentMode {
get {
return globalMode ?? instanceMode;
}
}
}
If I understand the problem statement correctly, I think this is similar to what you need:
public class Face extends Image { }
public class Screen extends Image { }
public class PictureFrame {
private Image picture = null;
public PictureFrame(Image newPicture) {
this.setPicture(newPicture);
}
public setPicture(Image newPicture) {
this.picture = newPicture;
}
}
public class PictureFactory {
private static Image defaultPicture = null;
public static void setDefaultPicture(Image newPicture) {
PictureFactory.defaultPicture = newPicture;
}
public static Image getDefaultPicture() {
return PictureFactory.defaultPicture;
}
public static PictureFrame getNewPictureFrame() {
return new PictureFrame(PictureFactory.defaultPicture);
}
}
public class PictureFrameManager {
private static PictureManager INSTANCE = new PictureManager();
private Vector<PictureFrame> frames = new Vector<PictureFrame>();
public static PictureFrameManager getInstance() {
return PictureManager.INSTANCE;
}
private PictureFrameManager() {}
private void addPictureFrame(PictureFrame frame) {
this.frames.add(frame);
}
private void setFramesToDefault() {
Image defaultPicture = PictureFactory.getDefaultPicture();
Enumeration<PictureFrame> iFrames = frames.elements();
while(iFrames.hasMoreElements()) {
iFrames.nextElement().setPicture(defaultPicture);
}
}
}
You use it via:
Face face = new Face();
//...do something to load the face object here
PictureFactory.setDefaultPicture(face);
PictureFrame frame = PictureFactory.getNewPictureFrame();
PictureFrameManager manager = PictureFrameManager.getInstance();
manager.addPictureFrame(frame);
Screen screen = new Screen();
//...do something to load the screen object here
PictureFactory.setDefaultPicture(screen);
manager.setFramesToDefault();
Alternately, if you don't want to extend Image or you want to have multiple modes, you could create a decorator object to wrap the image in and say what mode it is.

Resources