I want to maintain session on my below Java Swing application - java

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);
}
}
}

Related

Why does key listener works only once if I trigger the action setVisible(true) / action setVisible(false)?

I'm trying to display a Jpanel that is added into a Jframe,for making this is i created a variable that turns on or off when ENTER is pressed, I even tried to make a counter that counts times Enter is pressed but it stops working after one call, but if i remove the setVisible(); part the counter keeps being incremented. Please help.I leave the code here:
package test;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import game.Component;
public class Panel {
public boolean chat=Listener.chat;
public static void main(String[]args) {
JFrame frame = new JFrame();
frame.setTitle("Finestra di test per il gioco");
frame.setResizable(false);
frame.getContentPane().setBackground(Color.CYAN);
Dimension di = new Dimension(500,30);
frame.setBounds(0, 0, 500, 500);
frame.setResizable(false);
JPanel chatLayer=new JPanel();
chatLayer.setBounds(0, 0, 500, 500);
chatLayer.setBackground(Color.GREEN);
JTextField barra_chat=new JTextField();
barra_chat.setPreferredSize(di);
chatLayer.add(barra_chat);
frame.add(chatLayer);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Listener li=new Listener(chatLayer);
barra_chat.addKeyListener(li);
frame.validate();
frame.setVisible(true);
}
}
package test;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import test.Component;
public class Listener implements KeyListener{
int x=0;
JPanel pan = new JPanel();
public static boolean chat=true;
public Listener(JPanel pan) {
this.pan=pan;
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int key=e.getKeyCode();
switch(key) {
case KeyEvent.VK_ENTER:
if(!chat) {
pan.setVisible(true);
chat=true;
System.out.println(chat);
x+=1;
System.out.println(x);
}else {
pan.setVisible(false);
chat=false;
System.out.println(chat);
x+=1;
System.out.println(x);
}
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}

Inserting images into using java swing

I'm trying to insert an image into resource folder and use it to display in frame. But I'm getting this error :
Type Mismatch: can't convert from java.awt.Image to project.image
Here is a example using an image icon from the default java resources.
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon(test.class.getResource("/com/sun/java/swing/plaf/windows/icons/Question.gif")));
lblNewLabel.setBounds(112, 60, 151, 126);
frmTitle.getContentPane().add(lblNewLabel);
the code above will add a question mark image on your application, like this image. You can of course change it to whatever you would like.
Hope this simple sample helps you...
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.util.Arrays;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class FloorPlaner extends JFrame {
protected BufferedImage wall;
public FloorPlaner(){
super("FloorPlaner");
try {
wall = ImageIO.read(new File ("wall.png")); //Load a wall
} catch(IOException bug) { //Create a wall image
wall=new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB);
Graphics2D wg=wall.createGraphics();
wg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
wg.setColor(Color.BLACK);
wg.fillRect(0,0,20,20);
System.out.println(bug);
}
requestFocus();
setContentPane(new DrawingPane());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setResizable(true);
setVisible(true);
while (true) {
repaint();
try {
Thread.sleep(40); //25 FPS
} catch(InterruptedException bug) {
Thread.currentThread().interrupt();
System.out.println(bug);
}
}
}
class DrawingPane extends JPanel { //Where you actually draw on
public void paintComponent(Graphics g) { //Drawing method
g.drawImage(wall,0,0,null);
}
}
public static void main(String args[]) {
new FloorPlaner(); //Start it
}
}

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
//...
}

How to put JComboBox into an Applet

I have this code below. How do I make this JComboBOx run in an Applet? I'm trying to create an applet that allows the user to select a font and type in that font in a JTextArea. I have been searching for answers and made little progress. The error java.lang.reflect.InvocationTargetException keeps popping up. If you need more specifics please just comment.
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Font_Chooser extends JApplet {
JLabel jlbPicture;
public Font_Chooser(){
// Create the combo box, and set first item as Default
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] names = ge.getAvailableFontFamilyNames();
final JComboBox comboTypesList = new JComboBox(names);
comboTypesList.setSelectedIndex(0);
comboTypesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox jcmbType = (JComboBox) e.getSource();
String cmbType = (String) jcmbType.getSelectedItem();
jlbPicture.setIcon(new ImageIcon(""
+ cmbType.trim().toLowerCase() + ".jpg"));
System.out.println(comboTypesList.getSelectedItem());
//Font myFont = new Font((String)comboTypesList.getSelectedItem(), Font.BOLD, 12);
}
});
// Set up the picture
jlbPicture = new JLabel(new ImageIcon(""
+ names[comboTypesList.getSelectedIndex()] + ".jpg"));
jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
jlbPicture.setPreferredSize(new Dimension(177, 122 + 10));
// Layout the demo
setLayout(new BorderLayout());
add(comboTypesList, BorderLayout.NORTH);
add(jlbPicture, BorderLayout.SOUTH);
}
public static void main(String s[]) {
JFrame frame = new JFrame("JComboBox Usage Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new Font_Chooser());
frame.pack();
frame.setVisible(true);
}
}

Hide a JButton (image) after click

I've create a program with a JButton(image) and a normal image, now if you click the normal button a image will show, now i have program that the JButton(image) will hide if you click the normal button but i dont work and i get a fault code
package View;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import Controller.HideController;
import Controller.HomeController;
import Controller.SelectieController;
public class Selectie extends JFrame{
private static String Vermeer = "Vermeer";
private JLabel label, label1, label2;
private JButton keeper, kruis;
private JPanel panel;
private Container window = getContentPane();
public Selectie()
{
initGUI();
}
public void initGUI()
{
setLayout(null);
setTitle("Jari");
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.RED);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(266, 0, 266, 800);
label1.setBackground(Color.BLACK);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(532, 0, 266, 800);
label2.setBackground(Color.RED);
label2.setOpaque(true);
window.add(label2);
JLabel foto = new JLabel();
label1.add(foto);
kruis = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
kruis.setBorderPainted(false);
kruis.setBounds(40, 150, 188, 188);
label1.add(kruis);
keeper = new JButton("1. "+""+" Kenneth Vermeer");
Cursor cur = keeper.getCursor();
keeper.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
keeper.setBounds(20, 50, 186, 12);
keeper.setFocusable(false);
keeper.setBorderPainted(false);
keeper.setContentAreaFilled(false);
keeper.setFont(new Font("Arial",Font.PLAIN,17));
keeper.setForeground(Color.WHITE);
keeper.setActionCommand(Vermeer);
label.add(keeper);
SelectieController s1 = new SelectieController(keeper);
keeper.addActionListener(s1);
}
HideController h1 = new HideController(keeper, kruis);
{
keeper.addActionListener(h1);
}
}
The action listener class:
package Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
public class HideController implements ActionListener {
private JButton keeper, logo;
private static String Vermeer = "Vermeer";
public HideController(JButton vermeer, JButton kruis)
{
keeper = vermeer;
logo = kruis;
//Kenneth Vermeer
try
{
keeper.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
logo.setVisible(false);
}
public void actionPerformed(ActionEvent event)
{
String actionCommand = event.getActionCommand();
// Kenneth Vermeer
if (Vermeer.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
logo.setVisible(false);
}
});
}
}}
I hope someone could help me, thanks
If you want the button gone you can use window.remove(keeper). If you want no image but still want the button to be there, you can try logo = null, which will set the icon on logo to nothing, leaving you with a white box. If you are coding on Windows, you can add a background color with keeper.setBackgroundColor(Color.Blue) or whatever color your background is, however the Mac OS's look and feel will not allow this for some reason. (you can change the look and feel with, but that is fairly complicated) If you have a more complex background i would suggest taking a sample from the right point with a screenshot (with the button commented out in the code) and setting logo to that image.

Categories