How do you pass an object into a new form? - java

Why doesn't my car object pass into my ViewCarForm?
A car gets passed into InventoryItemPanel.
public class InventoryItemPanel extends JPanel{
Car car;
Button button = new Button("View More Details");
public InventoryItemPanel(Car car){
this.car = car;
// executes ButtonActionPerformed when button is clicked.
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonActionPerformed(evt);
}
});
add(button);
}
public void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
new ViewCarForm(car).setVisible(true);
}
}
The button when clicked is then supposed to pass the same car to ViewCarForm.
public class ViewCarForm extends javax.swing.JFrame {
Car car;
public ViewCarForm() {
initComponents();
}
public ViewCarForm(Car car){
new ViewCarForm().setVisible(true);
jLabel.setText(car.getMake());
}
}
However, the label in ViewCarForm does not get updated by the car object, so I assume that it is not passing through?

Let's look at what this constructor is doing:
public ViewCarForm(Car car){
new ViewCarForm().setVisible(true); // (A)
jLabel.setText(car.getMake()); // (B)
}
On line (A) you create a new ViewCarForm object -- and you do so within the ViewCarForm constructor, not something that I recommend that you do, since now you have two ViewCarForm instances, the original one, and a new one that you display.
On line (B) you set the text of a JLabel, a variable of the first and non-displayed ViewCarForm instance (I'm guessing that it's a variable of this class -- you never show us the variable declaration or instantiation. OK this will set the JLabel text of a non-displayed GUI, meanwhile the second ViewCarForm instance, the one that you do display, has no change to the text of its JLabel.
You don't call this() or initComponents() within the 2nd constructor, and so the code from the first default constructor, including the initComponents(); call, is never called, and so components are never properly laid out when this constructor is called.
Solution: don't do this, don't create two ViewCarForm instances, especially from within the same class's constructor. The only reason you don't have a stackoverflow error is because your class has two constructors, but even without the stackoverflow, it's insanity to do this. Create only one instance and set its JLabel text. Get rid of line (A)
Also, if the ViewCarForm is a secondary window, it shouldn't even be a JFrame but rather it should be a JDialog, either modal or non-modal depending on your need.
Also, you only init components in one ViewCarForm constructor and not in the other. So the JLabel will not show up in the second constructor/instance.
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import javax.swing.*;
public class InventoryFoo extends JPanel {
private static final Car FIRST_CAR = new Car("Honda");
private InventoryItemPanel inventoryItemPanel = new InventoryItemPanel(FIRST_CAR);
public InventoryFoo() {
inventoryItemPanel.setBorder(BorderFactory.createTitledBorder("Inventory Item"));
add(inventoryItemPanel);
}
private static void createAndShowGui() {
InventoryFoo mainPanel = new InventoryFoo();
JFrame frame = new JFrame("InventoryFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class InventoryItemPanel extends JPanel {
Car car;
// Button button = new Button("View More Details"); // should be a JButton
JButton button = new JButton("View More Details"); // should be a JButton
public InventoryItemPanel(Car car) {
this.car = car;
// executes ButtonActionPerformed when button is clicked.
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonActionPerformed(evt);
}
});
add(button);
}
public void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
// new ViewCarPanel(car).setVisible(true);
// get current JFrame
Window thisJFrame = SwingUtilities.getWindowAncestor(this);
// Create a non-modal JDialog
JDialog dialog = new JDialog(thisJFrame, "Car Make", ModalityType.MODELESS);
// create new viewCarPanel
ViewCarPanel viewCarPanel = new ViewCarPanel(car);
// add to dialog
dialog.add(viewCarPanel);
dialog.pack();
dialog.setLocationRelativeTo(thisJFrame);
dialog.setVisible(true);
}
}
// better for this to be a JPanel
class ViewCarPanel extends JPanel {
Car car;
private JLabel jLabel = new JLabel();
public ViewCarPanel() {
add(new JLabel("Car Make:"));
add(jLabel);
setPreferredSize(new Dimension(300, 80));
}
public ViewCarPanel(Car car) {
// so that we init components from the default constructor
this();
// new ViewCarPanel().setVisible(true);
jLabel.setText(car.getMake());
}
}
class Car {
private String make;
public Car(String make) {
this.make = make;
}
public String getMake() {
return this.make;
}
}

Related

Run new GUI window from an event of another class

I have 2 classes. Both implements runnable to create the GUI. The first one is the main, and the second one is the secondary class.
I want within the actionlistener of the main class to startup the secondary class.
Here is the code (the two classes are separated files):
public class Main implements Runnable
{
private JTextField txt1, txt2;
private JLabel lbl1, lbl2;
public void run()
{
JFrame frame = new JFrame("Secondary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();
JPanel background = new JPanel();
background.setLayout(new BoxLayout(background, BoxLayout.LINE_AXIS));
.........
// Horizontally adding the textbox and button in a Box
Box box = new Box(BoxLayout.Y_AXIS);
......
background.add(box);
pane.add(background);
frame.pack();
frame.setVisible(true);
}
private class SListener implements ActionListener
{
public void actionPerformed(ActionEvent a)
{
Secondary s = new Secondary();
}
}
public static void main (String[] args)
{
Main gui = new Main();
SwingUtilities.invokeLater(gui);
}
}
public class Secondary implements Runnable
{
private JTextField txt1, txt2;
private JLabel lbl1, lbl2;
public Secondary()
{
Secondary gui = new Secondary();
SwingUtilities.invokeLater(gui);
}
public void run()
{
JFrame frame = new JFrame("Secondary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();
JPanel background = new JPanel();
background.setLayout(new BoxLayout(background, BoxLayout.LINE_AXIS));
.........
// Horizontally adding the textbox and button in a Box
Box box = new Box(BoxLayout.Y_AXIS);
......
background.add(box);
pane.add(background);
frame.pack();
frame.setVisible(true);
}
}
I want to keep the code in two files, I don't want to mixed the two classes in one file.
As you can see from the code, in the Secondary class, in it's constructor I create an Instance of the Secondary class and I run the gui so that when the Instance of this class is created in the Main class, to run the gui.
Unfortunately this technique is not working.
Any ideas?
Thanks
The following line are complety wrong:
public Secondary(){
Secondary gui = new Secondary();
SwingUtilities.invokeLater(gui);
}
Each time you call new Secondary() somewhere in your code, the above code will be triggered, which in turn calls new Secondary() again, and again, and again, ... and your program is blocked.
You probably want to replace it either by
public Secondary(){
SwingUtilities.invokeLater(this);
}
which will avoid the loop, but this is weird behaviour for a constructor.
It makes much more sense to switch to an empty constructor (or delete it all together)
public Secondary(){
}
and rewrite your listener to
public void actionPerformed(ActionEvent a){
Secondary s = new Secondary();
SwingUtilities.invokeLater( s );
}
I would recommend that you completely re-design your program. I find that it is most helpful to gear my GUI's towards creation of JPanels, not top level windows such as JFrame, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. I find that this greatly increase the flexibility of my GUI coding, and is exactly what I suggest that you do. So...
Your first class creates a JPanel that is then placed into a JFrame.
In the first class's ActionListener, create an instance of the 2nd class, place it into a JDialog (not a JFrame), and then display it.
For example,
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TwoWindowEg {
public TwoWindowEg() {
// TODO Auto-generated constructor stub
}
private static void createAndShowGui() {
GuiPanel1 mainPanel = new GuiPanel1();
JFrame frame = new JFrame("Main GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class GuiPanel1 extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private GuiPanel2 guiPanel2 = new GuiPanel2(); // our second class!
private JDialog dialog = null; // our JDialog
public GuiPanel1() {
setBorder(BorderFactory.createTitledBorder("GUI Panel 1"));
add(new JButton(new LaunchNewWindowAction("Launch New Window")));
add(new JButton(new DisposeAction("Exit", KeyEvent.VK_X)));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class LaunchNewWindowAction extends AbstractAction {
public LaunchNewWindowAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
// get the Window that holds this JPanel
Window win = SwingUtilities.getWindowAncestor(GuiPanel1.this);
dialog = new JDialog(win, "Second Window", ModalityType.APPLICATION_MODAL);
dialog.add(guiPanel2);
dialog.pack();
}
dialog.setVisible(true);
}
}
}
class GuiPanel2 extends JPanel {
public GuiPanel2() {
setBorder(BorderFactory.createTitledBorder("GUI Panel 1"));
add(new JLabel("The second JPanel/Class"));
add(new JButton(new DisposeAction("Exit", KeyEvent.VK_X)));
}
}
class DisposeAction extends AbstractAction {
public DisposeAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component comp = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
win.dispose();
}
}
Alternatively, you could swap JPanel "views" using a CardLayout, but either way, you will want to avoid showing two JFrames. Please have a look at The Use of Multiple JFrames, Good/Bad Practice?.

return a value from a JFrame to main()

I am writing a program which has a JFrame with a JMenu in it. Once the user clicks a menuItem, a JDialog is being called, to get a String from the user. I want to use that string in my main programm but i don't know how to return that value from the JFrame to the main programm (I managed to return the value from the JDialog to the JFrame). Any ideas?
My main::
public static void main(String[] args)
{
myFirstFrame m = new myFirstFrame();
m.setVisible(true);
String localhost = m.getLh();
System.out.println(localhost);
}
My JFrame::
public class myFirstFrame extends JFrame
{
String lh;
myDialog myD;
public myFirstFrame(JFrame mf)
{
super();
setTitle("Welcome");
setSize(300, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JMenuItem playg = new JMenuItem("Play game");
simetoxi.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
myD = new myDialog(myFirstFrame.this);
myD.setVisible(true);
String lh = myD.getText();
System.out.println(lh + "ASasASas");
dispose();
}
});
JMenu game = new JMenu("GAME");
game.add(playg);
JMenuBar myBar = new JMenuBar();
myBar.add(game);
setJMenuBar(myBar);
}
public String getLh()
{
return lh;
}
}
My JDialog::
public class myDialog extends JDialog
{
JTextField t1;
String sname;
public myDialog(JFrame fr)
{
super(fr, true);
setTitle("Connect");
setSize(200, 200);
setLayout(new FlowLayout());
JLabel l1 = new JLabel("Give the server name");
t1 = new JTextField(15);
add(l1);
add(t1);
JButton okb = new JButton("submit");
okb.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
sname = t1.getText();
dispose();
}
});
add(okb);
}
public String getText()
{
return sname;
}
}
The problem is that when main creates the Frame, it doesn't stop and wait for the value to become available before executing the rest of the main function.
There are many ways you could solve this problem. For example, rather than putting System.out.println(localhost) in main, you could put it in a different method. Then, in the Frame, call that method when you get the value.
If you really want to put that call in main, you will have to find some way to make main block until the value is available. For example, you could create a BlockingQueue, and try to dequeue the value from within main. In the Frame event handler, push the needed value onto the queue.
The main method will not wait for your JFrame to go through those steps, so calling a getter in your main program (even if you "correct"
String lh = myD.getText();
to
lh == myD.getText();
will not work. - Pass this information to a class/method that makes good use of it, perhaps processing it in a separate thread - depends of what you want to do with "localhost".

How can I inform the class which have an instance of a GUI builder class, when the JButton ActionEvent performed

Ok, here is my problem. Class B is a class that build a GUI ,which has a textField and button. class A has an instance of class B.Now I enter some value in the textfield, when I click the button, in class A I want to print out the value I just enter in the textfield, how can I achieve that?
Code below may better explain what I want to achieve:
public class A
{
B myB = new B();
(when the JButton was clicked,
how can I get the new textfield value here?)
}
public class B
{
JLabel myLabel;
JButton myButton;
public B()
{
getContentPane().setLayout(null);
myLabel = new JLabel();
myLabel.setLocation(0,0);
myLabel.setSize(100,30);
myLabel.setBackground( new Color(-6710887) );
myLabel.setText("");
getContentPane().add(myLabel);
myButton = new JButton();
myButton.setLocation(0,50);
myButton.setSize(100,30);
myButton.setBackground( new Color(-16737895) );
myButton.setText("Submit");
getContentPane().add(myButton);
myButton.addActionListener(this);
setSize(400,400);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
(how can I pass this "myLabel.getText()" value to class A when
this action performed?)
}
}
Can anybody help me finish this little program? Thanks in advance!
You need to expose the value in text field with a method in class B. Then class A can call that method. What it actually sounds like though is that class A (or something else) should be a ActionListener for your button.
However, a bigger problem is that you don't have a text field you just have a label in class B. This code is a good reason why you shouldn't use a GUI builder, especially when learning Swing.
Some reading:
http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html
http://docs.oracle.com/javase/tutorial/uiswing/events/
I often make an "App" class that ties all my GUI-builder-built components together. Any GUI builder worth anything lets you add getters to the generated source code. Add some getters to the GUI-built components to retrieve key elements of the GUI, then let the App class use the getters to interact with the components as necessary. This won't win any MVC/MVVM/MVP design awards, but it gets the job done, which ought to count for something.
public class App {
private B _b;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
App app = new App();
app.run();
}
});
}
void run() {
_b = new B();
_b.getMainButton().addActionListener(new MainButtonListener());
_b.setVisible(true);
}
private void handleMainButtonClicked() {
String mainText = _b.getMainTextArea().getText();
System.out.println("Button clicked; main text = " + mainText);
}
public class MainButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
handleMainButtonClicked();
}
}
}
public class B extends JFrame {
private JPanel _contentPane;
private JTextArea _jTextArea;
private JButton _jButton;
public B() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
_contentPane = new JPanel();
setContentPane(_contentPane);
_jTextArea = new JTextArea();
_contentPane.add(_jTextArea, BorderLayout.CENTER);
_jButton = new JButton("My Button");
_contentPane.add(_jButton, BorderLayout.SOUTH);
}
public JButton getMainButton() {
return _jButton;
}
public JTextComponent getMainTextArea() {
return _jTextArea;
}
}

Passing information between buttons

I have an assignment where I have to click a button 1 in panel 1 and change the information on button 2 in panel 2, however I cannot figure out how to pass the information.
I thought I might be able to pass the information from method b() from panel2 back to one but that's not working.
I'm pretty stuck and don't know how to move forward with the program. Any help is appreciated.
Panel1
public class MyJPanel1 extends JPanel implements ActionListener {
Student st1 = new student("Fred","Fonseca",44);
JButton j = new JButton(st1.getInfo());
JButton b1 = new JButton("..");
public myJPanel1() {
super();
setBackground(Color.yellow);
// the whatsUp of this student has to shown in the other panel
j.addActionListener(this);
add(j);
}
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
//=====================================
if (obj == j){
b1.setText(st1.whatsUp()); // Output on JButton in JPanel2
}
}
}
}
Panel2
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class myJPanel2 extends JPanel {
JButton j1 = new JButton("");
public void b(JButton b1) {
JButton j1 = b1;
}
public myJPanel2() {
super();
setBackground(Color.pink);
setLayout(new GridLayout(3,1));
add(j1);
// j1.setText(b1);
}
}
Create a method in MyJPanel2 which sets the text in JButton.
public class myJPanel2 extends JPanel {
JButton button = new JButton("");
...........
public void setButtonText(String text) {
button.setText(text);
}
}
In MyJPanel2, you need to store a reference of MyJPanel1. Then just call the setButtonText in the ActionListener
public class MyJPanel1 extends JPanel implements ActionListener {
private MyJPanel2 panel;
public MyJPanel1(MyJPanel2 panel) {
this.panel = panel;
}
public void actionPerformed(ActionEvent event) {
if (obj == j){
panel.setButtonText(yourText);
}
}
}
}
A couple things to keep in mind. Java is an Object Oriented language, meaning that you want define your Objects using Classes, and then reuse those objects as much as possible. If you have two panels, each one containing a button, then that is the perfect time to define the Class once
public class MyPanel extends JPanel{
protected JButton button;
public MyPanel(String buttonName){
button = new JButton(buttonName);
}
//etc etc etc
}
and then use the Class over and over
public class MyProgram {
protected MyPanel panel1;
protected MyPanel panel2;
public MyProgram(){
panel1 = new MyPanel("Button 1");
panel2 = new MyPanel("Button 2");
}
//etc etc
}
Now, once you have your program set up like this, it is very easy to communicate between the two panels, since in MyProgram you have both instances of your panels available.
So, lets say your MyPanel class had a method called setButtonText
public void setButtonText(String text){
button.setText(text);
}
You could call this method in your MyProgram in order to change the text on one of the buttons
myPanel1.setText("New Button 1 text");
But how do we know if the button in myPanel1 or myPanel2 was pushed? You can look into how Java uses ActionListener to communicate events between different objects.
Good luck!
If I write sea you don't have connected that two panels together. The best way to coonect them together is from thrid calass wher you declare this two clasess. And set this two classes eachOther.
Example:
class conecctor{
ClassA first;
ClassB secod;
public void init(){
{
first=new ClassA();
second=new ClassB();
first.setClasB(second);
second.setClasA(first);
}
}
class ClassA{
ClassB classB;
public void setClassB(ClassB classB){
this.classB=classB;
}
}
class ClassB{
ClassA classA;
public void setClassA(ClassA classA){
this.classA=classA;
}
}
And then when you have instances in each class you can call all public methods from evrywher.
Beter way is to create interface and just pass the interface (listener) steal you pass whole class if that clas implements interface but it its more clearly and other advatages.

Base and extended windows in Java using inheritance

I've got one class called WindowTemplate that is the base for other (more complex) windows. It is an abstract class and then I'm trying to use the "extend" trick to add more stuff to the new window, keeping the original "skeleton". That is my problem though, because if I run WindowTemplate.createWindow(); or a_Welcome.createWindow(); (they should be point to the same thing), I get my "base" window. But when I run a_Welcome window = new a_Welcome(); (what should be the base + new stuff) I get only the extra bits that I added without the original features. Here is my code:
package windows;
import java.awt.*;
import javax.swing.*;
public abstract class WindowTemplate extends JFrame {
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
public static void createWindow() {
JFrame myFrame = new JFrame("My first window");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myFrame.setSize(550, 450);
myFrame.setLocationRelativeTo(null);
// JLabel emptyLabel = new JLabel("");
// emptyLabel.setPreferredSize(new Dimension(550, 450));
// myFrame.getContentPane().setLayout(new CardLayout());
// myFrame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
// myFrame.pack();
}
}
the class with new window and some extra stuff (ignore a_):
package windows;
import java.awt.*;
import javax.swing.*;
public class a_Welcome extends WindowTemplate {
public a_Welcome() {
JPanel area = new JPanel();
JLabel text = new JLabel("One line another line and another line"); // , JLabel.CENTER);
// text.setBounds(80, 400, 400, 50);
add(area);
// area.setLayout(null);
area.add(text, new CardLayout());
// area.add(text); // , BorderLayout.CENTER);
Font font = new Font("SansSerif", Font.BOLD, 30);
text.setFont(font);
text.setForeground(Color.green);
area.setBackground(Color.darkGray);
area.setSize(550, 450);
}
}
// timer-after 5 seconds-go to the next window (countdown in the bottom right corner)
and the main:
package windows;
public class Launcher {
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// WindowTemplate.createWindow();
// a_Welcome.createWindow();
a_Welcome window = new a_Welcome();
window.setVisible(true);
}
});
}
}
Thanks for your help!
Static method createWindow() always creates a new JFrame which is not a superclass of the WindowTemplate. Constructor of the a_Window is adding components to the WindowTemplate which hasn't been initialized since the static createWindow() creates an independent frame.
I would suggest you to change the static createWindow() into WindowTemplate constructor and try running main once again.
package windows;
import java.awt.*;
import javax.swing.*;
public abstract class WindowTemplate extends JFrame {
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
public WindowTemplate () {
JFrame myFrame = new JFrame("My first window");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myFrame.setSize(550, 450);
myFrame.setLocationRelativeTo(null);
// JLabel emptyLabel = new JLabel("");
// emptyLabel.setPreferredSize(new Dimension(550, 450));
// myFrame.getContentPane().setLayout(new CardLayout());
// myFrame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
// myFrame.pack();
}
}
You have another JFrame defined in the static createWindow() method. This means that you are adding the components to this frame that is scoped to the createWindow() method only and in the constructor you are adding to the a_Welcome instance.
You should do something like this
public class BaseWindow() {
//Constructor
public BaseWindow() {
init();
}
public void init() {
//add basic components
}
}
public class SubClassWindow() {
public SubClassWindow() {
super();
}
#Override
public void init() {
super.init(); //important so you get the base stuff
//add other components
}
}
Code not tested.
Another approach you might consider would be to have a JFrame that is just a wrapper and compose the window by adding a panel. Let's say you want a toolbar at the top of every window you're creating. Each window would have different buttons on the toolbar and a different set of components at the bottom. This way you are doing composition instead of inheritance, because inheritance can get ugly later on. (For discussions on that point, see this, this, and this for starters)
That would look something like:
public interface AppPanel {
List<JButton> getToolbarButtons();
boolean okToClose();
JPanel getGui();
}
public MyPanel extends JPanel implements AppPanel {
//standard swing components stuff set up here
public List<JButton> getToolbarButtons() {
//set up buttons and their actions
return buttonList;
}
public boolean okToClose() {
//ask user if they want to save, etc.
return true;
}
public JPanel getGui() {
return this;
}
}
public AppFrame extends JFrame {
private AppPanel panel;
public static AppFrame createFrame(AppPanel panel) {
AppFrame frame = new AppFrame(panel);
return frame;
}
public AppFrame(AppPanel panel) {
super();
this.panel = panel;
add(panel.getGui(), someLayoutConstraints);
panel.getToolbarButtons(); //do stuff with the buttons
//...
this.addWindowListener(new WindowAdapter() {
public void WindowClosing(WindowEvent e) {
if (panel.isOkToClose()) {
setVisible(false);
}
}
});
}
}

Categories

Resources