Basic MVC based Swing application - java

So I hit the following problem: I want to initializate the Swing constructor with a controller instance from my App class. That is the place I init the repo and controller. When i want to pass to the swing Gui class, the controller parameter I realized it has its own main method.
Could you please check the code and tell me if this is the correct approach? 'Cause I'm uncertain, and i can't find a basic example from a TUI app to a GUI app. Thank you!
App.java
package app;
import repository.*;
import view.View_gui;
import controller.*;
public class App{
RepoInterface ri;
ControllerInterface c;
View_gui gui;
public App() {
ri = new Repo();
c = new Controller(ri);
gui = new View_gui(c);
}
public static void main(String[] args) {
App app = new App();
}
}
View_gui.java
package view;
import controller.*;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.BorderLayout;
import java.awt.Label;
import java.awt.Panel;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JSeparator;
import javax.swing.JPanel;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.GridLayout;
public class View_gui {
private JFrame frame;
private static ControllerInterface ci; //added the variable
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
View_gui window = new View_gui(ci); // parametrizied
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public View_gui(ControllerInterface c) {
ci = c; // add + param by me
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("Countries");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblNewLabel = new JLabel("Country");
JLabel lblCapital = new JLabel("Capital");
JLabel lblArea = new JLabel("Area");
}
}

Related

JAVA - Gui class won't open from another Gui Class

Gui class closes the one I'm currently in but doesn't open my main menu gui class.
JButton btnNewButton_1 = new JButton("Main Menu");
btnNewButton_1.setFont(new Font("Tahoma", Font.BOLD, 13));
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Main_GUI mainGUI = new Main_GUI();
dispose();
}
});
main code that lists it set as visible, really not sure what is making it not work.main code that lists it set as visible, really not sure what is making it not work.
package GUI;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import javax.swing.ImageIcon;
import java.awt.Color;
import javax.swing.JLabel;
public class Main_GUI extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main_GUI frame = new Main_GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/

I want to maintain session on my below Java Swing application

I am developing one java swing application for task remainder.Please find the below code for the same.But the problem is i am not able to maintain session here since i am using ScheduledExecutorService class which will help to trigger this Swing app one hour once.When triggering new one all changes has been made in previous session of app is gone.
Kindly help me on this and let me know how can i use session on my Swing application.
Example : If you run the below app yon can see two buttons when we click on button it will change color to "green" and status change to "Done" but when the application trigger after one minute all changes were erased launching as new one.
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.Timer;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class Taskschdeuler {
private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
final Runnable beeper = new Runnable()
{
public void run()
{
// do anything here that you want to execute in a scheduler.
Task r=new Task();
}
};
final ScheduledFuture<?> beeper1 = scheduler.scheduleAtFixedRate(beeper, 0, 1, TimeUnit.MINUTES);
}
}
class Task extends JFrame implements ActionListener
{
JButton b1,b2,b3;
JLabel l1,l2;
public Task()
{
l1=new JLabel("Pending");
l2=new JLabel("Pending");
b1=new JButton("AVM DART");
b2=new JButton("HANDSHAKE");
b3=new JButton("Remind me later!!");
add(b1);
add(l1);
add(b2);
add(l2);
add(b3);
b1.setBackground(Color.PINK);
b2.setBackground(Color.PINK);
b3.setBackground(Color.CYAN);
b1.setPreferredSize(new Dimension(200, 50));
b2.setPreferredSize(new Dimension(200, 50));
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() -300;
int y = 500;
setLocation(x, y);
setLayout(new FlowLayout());
setVisible(true);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(e.getSource()==b1)
{
if (((Component)source).getBackground().equals(Color.GREEN))
{
((Component)source).setBackground(Color.PINK);
l1.setText("Pending");
}
else
{
((Component)source).setBackground(Color.GREEN);
l1.setText(" Done");
}
}
if(e.getSource()==b2)
{
if (((Component)source).getBackground().equals(Color.GREEN))
{
((Component)source).setBackground(Color.PINK);
l2.setText("Pending");
} else
{
((Component)source).setBackground(Color.GREEN);
l2.setText(" Done");
}
}
if(e.getSource()==b3)
{
setVisible(false);
}
}
}

how to add jpanel to jpanel in java

I have a problem when i add a jpanel to existing jpanel!
i want jlist at center loction and jbuttom in south location!
i can see the jlist, but the jbuttom won't show on!
I'm using Eclipse 3.0 version.
this is my code:
package classes;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class JPanelDecorator extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private JList<String> list = null;
private JButton Change=null;
public JPanelDecorator()
{
super();
setLayout(new BorderLayout());
setSize(450 ,400);
String animals_list[] = new String[AquaPanel.swims.size()];
LinkedList<Swimmable> ir = new LinkedList<Swimmable>(AquaPanel.swims);
for(int i=0;i<ir.size();i++)
{
animals_list[i]=(i+1+". "+ir.get(i).toString());
}
list = new JList<String>(animals_list );
list.setFont(new Font("Tahoma",Font.BOLD,15));
list.setSize(450, 300);
add(list,BorderLayout.CENTER);
Change = new JButton("Change Color");
Change.addActionListener(this);
add(Change,BorderLayout.CENTER);
repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
please help!
You have a subtle bug. In the constructor of JPanelDecorator you have :
public JPanelDecorator()
{
//....
add(list,BorderLayout.CENTER);
//...
add(Change,BorderLayout.CENTER); // center again...
//...
}
But what you need is this:
public JPanelDecorator()
{
//....
add(list,BorderLayout.CENTER);
//...
add(Change,BorderLayout.SOUTH); // south
//...
}

Jung Factory For Custom Object

I'm new to jung and i need help on how to learn. I searched a lot of places, but i haven't found a step by step guide. Im trying to create a gui that will add vertexes only if they selected the right menu, and entered a proper name.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JMenu;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import org.apache.commons.collections15.Factory;
public class demo3 {
Graph<State,Transition> g;
Factory<State>stateList;
Factory<Transition>linelist;
ArrayList<State>states = new ArrayList<State>();
ArrayList<Transition>lines = new ArrayList<Transition>();
private static JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
initialize();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
demo3 sgv = new demo3();
Layout<State, Transition> layout = new StaticLayout(sgv.g);
layout.setSize(new Dimension(300,300));
VisualizationViewer<State,Transition> vv = new VisualizationViewer<State,Transition>(layout);
vv.setPreferredSize(new Dimension(350,350));
demo3 window = new demo3();
EditingModalGraphMouse gm = new EditingModalGraphMouse(vv.getRenderContext(),
sgv.stateList, sgv.linelist);
vv.setGraphMouse(gm);
gm.setMode(ModalGraphMouse.Mode.EDITING);
frame.getContentPane().add(vv);
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public demo3() {
g = new SparseMultigraph<State, Transition>();
stateList = new Factory<State>() {
public State create() {
State newState = new State();
states.add(newState);
return newState;
}
};
linelist = new Factory<Transition>(){
public Transition create(){
Transition line = new Transition();
lines.add(line);
return line;
}
};
}
/**
* Initialize the contents of the frame.
*/
private static void initialize() {;
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnAddStateOr = new JMenu("Add State or Transition");
menuBar.add(mnAddStateOr);
JPanel panel = new JPanel();
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
String stateName = JOptionPane.showInputDialog("Enter the value of the state");
State newState = new State(Integer.parseInt(stateName));
}
});
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
I need to know how to label each circle based on the state name they enter. Also any tips for learning JUNG would help.

JDialog unmovable form JTable cell editor

I have customized the JTable cell editor in order to allow enter data from JDialog frame. I have used an editable combobox for that, I have added an ActionListener for combobox to display The dialog.
I have got my JDialog visible, but I want to make it unmovable, so the user can't move it.
Here is my code so far,
package VIEW;
import VIEW.statManager.SearchProduitEvent;
import VIEW.statManager.SearchProduitEventListener;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.table.TableCellEditor;
import javax.swing.text.JTextComponent;
public class ProduitCellEditor extends AbstractCellEditor implements TableCellEditor,ActionListener, SearchProduitEventListener {
private JComboBox combo;
private SearchProduitUi searchProduitUi;
private String value = "value";
public ProduitCellEditor() {
combo = new JComboBox();
combo.setEditable(true);
combo.setActionCommand("combo");
searchProduitUi = new SearchProduitUi();
searchProduitUi.setSearchProduitEventListener(this);
searchProduitUi.setSize(500,300);
searchProduitUi.setLocationRelativeTo(combo);
}
#Override
public Object getCellEditorValue() {
return value;
}
#Override
public Component getTableCellEditorComponent(JTable jtable, Object o, boolean bln, int i, int i1) {
return combo;
}
public void actionPerformed(ActionEvent event) {
Point comboPosition = combo.getLocationOnScreen();
searchProduitUi.setLocationRelativeTo(combo);
searchProduitUi.setLocation(comboPosition.x ,comboPosition.y + combo.getHeight());
searchProduitUi.setVisible(true);
}
#Override
public void searchDialogEventOccured(SearchProduitEvent ev) {
value = ev.getProduit().getDesignation();
fireEditingStopped();
}
}
JDialog#setUndecorated will remove the frame decorations, including the close/minimise/maximise controls and make it impossible for the user to move the window.
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test1 {
public static void main(String[] args) {
new Test1();
}
public Test1() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JPanel content = new JPanel(new GridBagLayout());
content.setBorder(new EmptyBorder(8, 8, 8, 8));
JLabel label = new JLabel("Hello world");
content.add(label);
JDialog dialog = new JDialog();
dialog.setUndecorated(true);
dialog.setTitle("Testing");
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.setContentPane(content);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
});
}
}

Categories