How to open an internal frame - java

i open a new internalframe in this main frame, i have 2 class,
DisplayInternalFrame aDisplay = new DisplayInternalFrame(name, surname);
desktop.add(aDisplay);
aDisplay.setMaximum(true);
aDisplay.show()
i have a desktop pane and its name desktop, this is my main frame, the internal frame is loading when the application runs,
now my 2nd class is internalframe, it has a table, i want to open new internal frame when people push a table item, my table name is errorTable
private void errorTableMouseClicked(java.awt.event.MouseEvent evt) {
errorInternalFrame acceptFrame = new errorInternalFrame();
desktop.add(acceptFrame);
the desktop is on the class 1 so i cant reach desktop cuz now i am on the internalframe event,
basically when people push an item on the table on the internalframe, open a new internal frame, or something like this.

"the desktop is on the class 1 so i cant reach desktop cuz now i am on the internalframe event, "
What you can do is create an interface with a method to addToDesktop
public interface AddableDesktop {
public void addToDesktop();
}
Then in your class with the desktop, implement it
public class Main extends JFrame implements AddableDesktop {
private JDesktopPane desktop;
#Override
public void addToDesktop() {
errorInternalFrame acceptFrame = new errorInternalFrame();
desktop.add(acceptFrame);
acceptFrame.setVisible(true);
}
}
You'll also need to pass the Main instance (which is an instance of AddableDesktop) to the DisplayInternalFrame. Then you can call the addToDesktop method.
public class DisplayInternalFrame extends JInternalFrame {
private AddableDesktop addableDesktop;
public DisplayInternalFrame(String name, String surname, AddableDesktop ad) {
this.addableDesktop = ad;
}
...
private void errorTableMouseClicked(java.awt.event.MouseEvent evt) {
addableDesktop.addToDesktop();
}
}
When you create the DisplayInternalFrame in your Main class, you'll pass the Main instance to the contructor
DisplayInternalFrame aDisplay =
new DisplayInternalFrame(name, surname, Main.this);
This may not be the exact set up you're looking for, but it shows how you provide functionality from one class to the another.

Related

Access GUI components from another class

I'm new to Java and I've hit a brick wall. I want to access GUI components (that have been created in one class) from another class. I am creating a new GUI class from one class, like so;
GUI gui = new GUI();
and I can access the components in that class, but when I go to a different class I cant. I really just need to access the JTextAreas to update their content. Could someone point me in the right direction please, any help is greatly appreciated.
GUI Class:
public class GUI {
JFrame frame = new JFrame("Server");
...
JTextArea textAreaClients = new JTextArea(20, 1);
JTextArea textAreaEvents = new JTextArea(8, 1);
public GUI()
{
frame.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 3));
...
frame.setVisible(true);
}
}
First respect encapsulation rules. Make your fields private. Next you want to have getters for the fields you need to access.
public class GUI {
private JTextField field = new JTextField();
public GUI() {
// pass this instance of GUI to other class
SomeListener listener = new SomeListener(GUI.this);
}
public JTextField getTextField() {
return field;
}
}
Then you'll want to pass your GUI to whatever class needs to access the text field. Say an ActionListener class. Use constructor injection (or "pass reference") for the passing of the GUI class. When you do this, the GUI being referenced in the SomeListener is the same one, and you don't ever create a new one (which will not reference the same instance you need).
public class SomeListener implements ActionListener {
private GUI gui;
private JTextField field;
public SomeListener(GUI gui) {
this.gui = gui;
this.field = gui.getTextField();
}
}
Though the above may work, it may be unnecesary. First think about what exactly it is you want to do with the text field. If some some action that can be performed in the GUI class, but you just need to access something in the class to perform it, you could just implement an interface with a method that needs to perform something. Something like this
public interface Performable {
public void someMethod();
}
public class GUI implements Performable {
private JTextField field = ..
public GUI() {
SomeListener listener = new SomeListener(GUI.this);
}
#Override
public void someMethod() {
field.setText("Hello");
}
}
public class SomeListener implements ActionListener {
private Performable perf;
public SomeListener(Performable perf) {
this.perf = perf;
}
#Override
public void actionPerformed(ActionEvent e) {
perf.someMethod();
}
}
Several approaches are possible:
The identifier gui is a reference to your GUI instance. You can pass gui to whatever class needs it, as long as you respect the event dispatch thread. Add public accessor methods to GUI as required.
Declarations such as JTextArea textAreaClients have package-private accessibility. They can be referenced form other classes in the same package.
Arrange for your text areas to receive events from another class using a PropertyChangeListener, as shown here.
The best option to access that text areas is creating a get method for them. Something like this:
public JTextArea getTextAreaClients(){
return this.textAreaClients;
}
And the same for the other one.So to access it from another class:
GUI gui = new GUI();
gui.getTextAreaClients();
Anyway you will need a reference for the gui object at any class in which you want to use it, or a reference of an object from the class in which you create it.
EDIT ---------------------------------------
To get the text area from GUI to Server you could do something like this inside of Create-Server.
GUI gui = new GUI();
Server server = new Server();
server.setTextAreaClients(gui.getTextAreaClients());
For this you should include a JTextArea field inside of Server and the setTextAreaClients method that will look like this:
JTextArea clients;
public void setTextAreaClients(JTextArea clients){
this.clients = clients;
}
So in this way you will have a reference to the JTextArea from gui.
here i add a simple solution hope it works good,
Form A
controls
Textfield : txtusername
FormB fb = new FormB();
fb.loginreset(txtusername); //only textfield name no other attributes
Form B
to access FormA's control
public void ResetTextbox(JTextField jf)
{
jf.setText(null); // or you can set or get any text
}
There is actually no need to use a class that implements ActionListener.
It works without, what might be easier to implement:
public class SomeActionListener {
private Gui gui;
private JButton button1;
public SomeActionListener(Gui gui){
this.gui = gui;
this.button1 = gui.getButton();
this.button1.addActionListener(l -> System.out.println("one"));
}
}
and then, like others have elaborated before me in this topic:
public class GUI {
private JButton button = new JButton();
public GUI() {
// pass this instance of GUI to other class
SomeActionListener listener = new SomeActionListener(GUI.this);
}
public JButton getButton() {
return button;
}
}

Refresh JPanel content on tab switch

I'm writing a simple UI just to get the hang of things. I have a tabbed window with two tabs, one has a button that counts up an integer, the other has a text field showing the content of said integer. Or at least that's the plan.
Everything works just fine if I stuff everything into one class. I can access tab 1 from my actionlistener and change the text field in tab 1 from the button press in tab 2. But I don't want my entire program to be in one class, obviously.
And here I have no idea what to do: I need to tell the textfield in the Class Tab1 to change on the button press in the Class Tab2. What's the right thing to do here? My first thought was to hand over an instance of Tab1 in the creation of Tab2, so I could do tab1.changeText(). But that would get messy quickly once I'd get more tabs that interact with each other. So, instead, I want to update the content of the first tab every time it is opened, but I don't know how to do that. And I don't know if that's the right thing to do, either. So, help!
Here's some code. "content" is an instance of Content, a class handling all the logic like adding to the counter.
Main GUI Class:
public class GUI extends JFrame {
//Stuff..
JTabbedPane tabs = new JTabbedPane();
tabs.addTab("One", new Tab1(content));
tabs.addTab("Two", new Tab2(content));
//Stuff..
Tab 1:
public class Tab1 extends JPanel {
public Tab1(Content content) {
JPanel tab1 = new JPanel();
//Stuff..
JTextField tfCount = new JTextField(content.getCounter(), 10);
tab1.add(tfCount);
this.add(tab1);
//Stuff..
Tab 2:
public class Tab2 extends JPanel {
public Tab2(Content content) {
JPanel tab2 = new JPanel();
//Stuff..
JButton btnCount2 = new JButton("Count");
btnCount2.addActionListener(new TestListener(this.content));
tab2.add(btnCount2);
this.add(tab2);
}
private class TestListener implements ActionListener {
Content content;
public TestListener(Content content) {
this.content = content;
}
#Override
public void actionPerformed(ActionEvent e) {
this.content.addToCounter(1);
}
}
Now, if all of that would be in one class (plus subclasses), I could just access tfCount from Tab2 and do tfCount.setText(content.getCounter());. Now tfCount is in a different class, though, and I cannot access it, unless I hand over an instance of Tab1 to Tab2 (like tabs.addTab("Two", new Tab2(content, Tab1);). Couldn't I instead get Tab1 to repaint itself whenever it is opened, like having a method that executes tfCount.setText(content.getCounter()) in Tab1 whenever it is opened, or something along those lines? If so, how do I do that?
With you controls separated in this manner you have a view choices...
You Could...
Share an instance of each "tab" with each of the other tabs, allowing them to either access the others controls or attach listeners across each other. This is very tightly coupled and messy.
The other problem is, does the button really care about the text field or visa versa...
You Could...
Create a simple model that contains the current int value and provides a means to change that value.
The model would have the capacity to fire a ChangeEvent (for example) when the value is changed, which interested parties could listen for and update themselves accordingly.
This decouples the code, reducing the complexity and greatly increasing the flexibility and reuse of various elements of your code.
This is commonly known as an observer pattern and is widely used in Swing.
A possible (listener) example...
For me, I always start with an interface, this describes the absolute minimum requirements that must be meet in order to achieve the required goal. Each tab will want to know the current value, be able to set the next value and listener for changes to the model...
public interface NumberModel {
public int getValue();
public void setValue(int value);
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
}
An abstract implementation deals with the more "common" implementation details, things that a concrete implementation won't want to have to implement, as it's common enough to all implementations. In this case, that would the listener management...
public abstract class AbstractNumberModel implements NumberModel {
private List<ChangeListener> listeners;
public AbstractNumberModel() {
listeners = new ArrayList<>(25);
}
#Override
public void addChangeListener(ChangeListener listener) {
listeners.add(listener);
}
#Override
public void removeChangeListener(ChangeListener listener) {
listeners.remove(listener);
}
protected ChangeListener[] getChangeListeners() {
// FIFO...
List<ChangeListener> copy = new ArrayList<>(listeners);
Collections.reverse(copy);
return copy.toArray(copy.toArray(new ChangeListener[listeners.size()]));
}
protected void fireStateChanged() {
ChangeListener[] listeners = getChangeListeners();
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
}
And finally, a concrete implementation, which deals with the implementation specific details...
public class DefaultNumberModel extends AbstractNumberModel {
private int value;
public DefaultNumberModel() {
}
public DefaultNumberModel(int value) {
setValue(value);
}
#Override
public int getValue() {
return value;
}
#Override
public void setValue(int num) {
if (num != value) {
value = num;
fireStateChanged();
}
}
}
We could be a slightly more flexible model by doing something like public interface NumberModel<N extends Number> which would allow you define models that could hold Integer, Double, Float and Long for example, but I'll leave that to you.
Each of you tab views will need a setModel(NumberModel) method, so you can pass the model it. In these methods, you will attach a listener to the model and get the current value so that the model and view are in sync.

How do I pass the values from one class to another?

I have this gui pop up panel and it got things to filled up like packets number, distance etc. Once users fill in the information, he will click ok, the gui will close and my other gui class which has calculation method should receives all data that are filled in earlier gui. How do I store that data? I know I can store in temp file but I don't want to do that. I hope you can enlighten me.
import java.awt.*;
import java.applet.Applet;
class Example extends Applet implements ActionListener
{
TextField txt = new TextField(10);
Button goButton = new Button("Go");
String data = new String ();
public void init ()
{
add(txt);
add(goButton);
goButton.addActionListener(this);
}
public void actionPerformed (ActionEvent e)
{
String cmd = e.getActionCommand();
if (cmd.equals("Go"))
{
// preserve data
data = txt.getText();
repaint();
}
}
}
You should create an intermediate class that represents the data.
After the GUI has been filled in and the submit button clicked, parse the data and fill in the fields in your class.
For example:
public class MyData {
public String Name;
public String Address;
}
Then, fire a method in your calculation method that takes this class as a parameter:
public void Calculate(MyData data) {
...
}
For more advanced handling, look into "interfaces" in Java - that's the standard way this is done.

Object has null values when subclass attempts to use it. Why?

I'm a newbie Java guy so I'm probably doing this entire thing completely wrong. I have to do this giant project for software engineering class. The code is about 2,000 lines long so this is skeleton code
public class BookRental extends JFrame{
public Client currentClient = new Client(); // creating client object
//rest of declared variables.
public class Client{ //Client class containing all get/set methods for each variable
private username;
private void setUsername(String u){
username = u;
}
public String getUsername(){
return username;
}
public class LoginPanel extends JPanel{} //Panel to show and receive login info.
public class RegisterPanel extends JPanel{} //Panel to register.
public class MenuPanel extends JPanel{ //Panel showing main menu.
//At this point currentClient will contain values
public ClientInfoPanel(){
initComponents();
}
private void initComponents(){
infoPanelUserName = new JLabel();
infoPanelFullName.setText("Currently logged in as: " + currentClient.getUsername());
}
private JLabel infoPanelUserName;
}
public class ClientInfoPanel extends JPanel{} //Panel to print currentClient info to screen using JLabel objects
private void ViewClientInfoButtonActionPerformed(event){ // Using button in Menu Panel to setVisibility of clientInfoPanel to (true)
//At this point there will be a value for currentClient
clientInfoPanel = new ClientInfoPanel();
this.add(clientInfoPanel);
menuPanel.setVisible(false);
clientInfoPanel.setVisible(true);
}
public BookRental(){initComponents();} //Constructor
private void initComponents(){} // Creates all panels and sets visibility off, besides login
public static void main(String args[]){
new BookRental().setVisible(true);
}
}
I already am pretty sure I am doing this COMPLETELY wrong, however my question is why can't I access currentClient inside of ClientInfoPanel? Say for this JLabel:
infoPanelUserName.setText("Currently logged in as: " + currentClient.getUsername());
The ClientInfoPanel recognizes currentClient exists and that the getUsername() method exists, however it prints:
"Currently logged in as: "
The code you showed looks fine, so the problem is somewhere else, or this code is not representative of what you have. Also, you ARE accessing currentClient successfully, unless you're getting a NullPointerException or catching it somewhere, then the .getUsername() call IS resolving. So the problem is actually with .getUsername(), somehow username is uninitialized when you call .getUsername();
As a test, can you call .setUsername() on currentClient right before you call .getUsername()? That should help us narrow down the problem, isolate it to either the class access or the variable being initialized.
Also, do you know how to debug with breakpoints? You mentioned you're new, so you might not know this is possible. If you're using Eclipse (or another good IDE) you can set breakpoints and run the program in DEBUG build, then the program will freeze when it hits the line you set a breakpoint on, and you can watch as the program moves line by line, and see the variables as they are updated by the program. Google java debug tutorial. :)
I agree (not sure whether I should add since someone else already answered, what is the etiquette?). I ran this fine and it showed me a panel with the user logged in as Me as set in the BookRental constructor:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class BookRental extends JFrame{
public Client currentClient = new Client(); // creating client object
//rest of declared variables.
public class Client{ //Client class containing all get/set methods for each variable
private String username;
private void setUsername(String u){
username = u;
}
public String getUsername(){
return username;
}
}
public class ClientInfoPanel extends JPanel{ //Panel showing main menu.
//At this point currentClient will contain values
public ClientInfoPanel(){
initComponents();
}
private void initComponents(){
infoPanelUserName = new JLabel();
infoPanelUserName.setText("Currently logged in as: " + currentClient.getUsername());
this.add(infoPanelUserName);
}
private JLabel infoPanelUserName;
}
public ClientInfoPanel clientInfoPanel;
//Constructor
public BookRental(){
currentClient.setUsername("Me");
initComponents();
}
private void initComponents(){
clientInfoPanel = new ClientInfoPanel();
this.add(clientInfoPanel);
clientInfoPanel.setVisible(true);
}
public static void main(String args[]){
new BookRental().setVisible(true);
}
}

Clearing a JTextArea from another class

I'm very new to Java and I'm setting myself the challenge on writing a Caesar shift cipher decoder. I'm basically trying to clear a JTextArea from another class. I have two classes, a GUI class called CrackerGUI and a shift class. The JtextArea is in the GUI class along with the following method:
public void setPlainTextBox(String text)
{
plainTextBox.setText(text);
}
The GUI class also has a clear button with the following:
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
Shift classShift = new Shift();
classShift.btnClear();
}
Lastly i have the method in the shift class to clear the JTextArea.
public class Shift extends CrackerGUI {
public void btnClear()
{
CrackerGUI gui = new CrackerGUI();
gui.setPlainText(" ");
System.out.println("testing");
}
}
The testing text is printing out to console but the JTextArea wont clear. I'm not sure as to why :). I am sure it's a very simple mistake but it has me baffled. Any help would be appreciated.
Thank you in advance.
You're misusing inheritance to solve a problem that doesn't involve inheritance. Don't have Shift extend CrackerGUI and don't create a new CrackerGUI object inside of the btnClear() method since neither CrackerGUi is the one that's displayed. Instead have Shift hold a reference to the displayed CrackerGUI object and have it call a public method of this object.
e.g.,
public class Shift {
private CrackerGUI gui;
// pass in a reference to the displayed CrackerGUI object
public Shift(CrackerGUI gui) {
this.gui = gui;
}
public void btnClear() {
//CrackerGUI gui = new CrackerGUI();
gui.setPlainText(" ");
System.out.println("testing");
}
}
You also should probably not be creating new Shift objects in your GUI's actionPerformed methods, but rather use only one Shift object that is a class field.
The btnClear method clears the text area of a new CrackerGUI instance. It's like if you wanted to clear a drawing on a sheet of paper by taking a new blank sheet and clearing it. The original sheet of paper will keep its drawing.
You need to pass the gui instance to your Shift:
public class Shift {
private CrackerGUI gui;
public Shift(CrackerGUI gui) {
this.gui = gui;
}
public void btnClear() {
this.gui.setPlainText(" ");
}
}
and in the CrackerGUI class :
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
Shift classShift = new Shift(this);
classShift.btnClear();
}
Assuming CrackerGUI is your GUI, you should have the following instead:
public class CrackerGUI {
public void setPlainTextBox(String text)
{
plainTextBox.setText(text);
}
public void btnClear()
{
setPlainTextBox("");
System.out.println("testing");
}
}
One last thing, never make your GUI elements public! You should ask the GUI to clear itself and leave that knowledge of clearing elements hidden inside it.
You could try using static methods, as you would end up creating a new gui, then displaying that one, in stead of the current one already displayed.
This would require the parent class to be static too, which may cause errors in some of your methods, just a heads up.
Or else, you could create your own setText method:
void setText(JTextField t, String s){
t.setText(s);
}
that may enable you to directly edit components in the current GUI.

Categories