In my application we use CrossPlatform L&F (metal) and we want to launch the main JFrame maximized. When executing I find the windows toolbar hidden. This does not happen if I use System L&F.
Why is this so? Is there any way to avoid this?
Code excerpt to force Metal L&F is:
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (ClassNotFoundException ex) {
code to catch this exception;
} catch (InstantiationException ex) {
code to catch this exception;
} catch (IllegalAccessException ex) {
code to catch this exception;
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
code to catch this exception;
}
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
and method to maximize window is as follows:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
setExtendedState(JFrame.MAXIMIZED_BOTH);
return;
}
Many Thanks in advance
It seems that it is a known issue when you call:
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
See this link: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4737788
It also shows a workaround by subclassing JFrame and return appropriate maximum bounds. Here is a demo code of this workaround:
import java.awt.Frame;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.OceanTheme;
public class TestJFrame {
private void initUI() {
final JFrame frame = new JFrame(TestJFrame.class.getSimpleName()) {
private Rectangle maxBounds;
#Override
public Rectangle getMaximizedBounds() {
return maxBounds;
}
#Override
public synchronized void setMaximizedBounds(Rectangle maxBounds) {
this.maxBounds = maxBounds;
super.setMaximizedBounds(maxBounds);
}
#Override
public synchronized void setExtendedState(int state) {
if (maxBounds == null && (state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
Insets screenInsets = getToolkit().getScreenInsets(getGraphicsConfiguration());
Rectangle screenSize = getGraphicsConfiguration().getBounds();
Rectangle maxBounds = new Rectangle(screenInsets.left + screenSize.x, screenInsets.top + screenSize.y, screenSize.x
+ screenSize.width - screenInsets.right - screenInsets.left, screenSize.y + screenSize.height
- screenInsets.bottom - screenInsets.top);
super.setMaximizedBounds(maxBounds);
}
super.setExtendedState(state);
}
};
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}
});
JLabel label = new JLabel("some label in the middle");
label.setHorizontalAlignment(JLabel.CENTER);
frame.add(label);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestJFrame().initUI();
}
});
}
}
Alternatively, don't call JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
Related
I want to change the color of JTextField to red after typing something in it, and then after a second return to a default white background. I tried this outside the listener, and it worked, but when it comes to being a part of a listener, it doesn't (it just skips setting the red color). This is weird for me..
public class Test {
JFrame frame;
JTextField field;
public Test() {
frame = new JFrame();
field = new JTextField("A");
field.addKeyListener(new KeyBListener());
frame.getContentPane().add(field);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) { new Test(); }
private class KeyBListener implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
try {
field.setBackground(Color.RED);
Thread.sleep(1000);
field.setBackground(Color.WHITE);
} catch (InterruptedException es) { es.printStackTrace(); }
}
#Override
public void keyPressed(KeyEvent e) { }
#Override
public void keyReleased(KeyEvent e) { }
}
}
Try creating a separate Thread that listens to color change on the JTextField then changes it back. In this case at least you will not block the main Thread, although I'm not sure it's the most efficient way.
public Main() {
frame = new JFrame();
frame.setSize(800, 600);
field = new JTextField("A");
field.addKeyListener(new KeyBListener());
frame.getContentPane().add(field);
frame.pack();
frame.setVisible(true);
new Thread(() -> {
while(true) {
if(field.getBackground().equals(Color.RED))
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
field.setBackground(Color.WHITE);
}
}).start();
}
Your previous solution was working because it was executed from the AWT itself.
The keyTyped() method is executed on the Event dispatch thead (EDT), so you have to move the painting actions back to the AWT.
Have a look on SwingUtilities.invokeLater() (non-blocking) or SwingUtilities.invokeAndWait() (blocking), see
Oracle Doc
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
field.setBackground(Color.RED);
Thread.sleep(1000);
field.setBackground(Color.WHITE);
} catch (InterruptedException es) {
es.printStackTrace();
}
}
});
You can spawn a different thread in which you do the color manipulation. That ensures that the color manipulation is not happening inside EDT.
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class Test {
JFrame frame;
JTextField field;
AtomicBoolean isColorChangeOn = new AtomicBoolean();
public Test() {
frame = new JFrame();
field = new JTextField("A");
field.addKeyListener(new KeyBListener());
frame.getContentPane().add(field);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
isColorChangeOn.set(false);
}
public static void main(String[] args) {
new Test();
}
private class KeyBListener implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
if(!isColorChangeOn.get()) {
isColorChangeOn.set(true);
Runnable setcolor = ()->{
try {
System.out.println("color changing");
field.setBackground(Color.RED);
Thread.sleep(1000);
field.setBackground(Color.WHITE);
isColorChangeOn.set(false);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
};
new Thread(setcolor).start();
}
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
}
I am trying to make a simple barcode scanner project for fun. And I've run into a slight problem. I am using zXing and Webcam Capture for this.
Even if a Barcode is present in the picture, Java keeps telling me none is found through the NotFoundException. I look for a frame every time webcamImageObtained is run (which I assume is every frame?) and then I look for a barcode in the frame that I captured.
I took this picture with that webcam (Ironically using the code hah):
When I hover over this barcode it reports about 30 images per second and otherwise about 7-8 when it looks at me from my screen (if that means anything).
Whenever I find a code, I want to add it to a JList (not accounting for duplicates and the likes yet).
I call this code every time webcamImageObtained(WebcamEvent we) fires:
#Override
public void webcamImageObtained(WebcamEvent we) {
BufferedImage myImage;
try {
myImage = webcam.getImage();
LuminanceSource source = new BufferedImageLuminanceSource(myImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap);
DefaultListModel dlm = (DefaultListModel) list.getModel();
dlm.addElement(result.toString());
list.setModel(dlm);
} catch (NotFoundException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ChecksumException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (FormatException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the entire class:
package sandbox_webcam;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamDiscoveryEvent;
import com.github.sarxos.webcam.WebcamDiscoveryListener;
import com.github.sarxos.webcam.WebcamEvent;
import com.github.sarxos.webcam.WebcamListener;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamPicker;
import com.github.sarxos.webcam.WebcamResolution;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
public class AdvancedWebcamPanelExample extends JFrame implements Runnable, WebcamListener, WindowListener, UncaughtExceptionHandler, ItemListener, WebcamDiscoveryListener {
private Webcam webcam = null;
private WebcamPanel panel = null;
private WebcamPicker picker = null;
private JButton button = null;
private JList list = null;
private ActionListener buttonListener = null;
private com.google.zxing.Reader reader = new com.google.zxing.MultiFormatReader();
#Override
public void run() {
Webcam.addDiscoveryListener(this);
setTitle("Java Webcam Capture POC");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
addWindowListener(this);
picker = new WebcamPicker();
picker.addItemListener(this);
webcam = picker.getSelectedWebcam();
if (webcam == null) {
System.out.println("No webcams found...");
System.exit(1);
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.addWebcamListener(AdvancedWebcamPanelExample.this);
panel = new WebcamPanel(webcam, false);
panel.setFPSDisplayed(true);
buttonListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (webcam != null) {
BufferedImage image = webcam.getImage();
JFileChooser filechooser = new JFileChooser();
int saveValue = filechooser.showDialog(button, "Save");
if (saveValue == JFileChooser.APPROVE_OPTION) {
try {
File f = filechooser.getSelectedFile();
ImageIO.write(image, "png", new File(f.getAbsolutePath() + ".png"));
System.out.println("Picture saved at: " + f.getAbsolutePath());
} catch (IOException ex) {
System.err.println("Failed to save the picture!");
ex.printStackTrace();
}
}
} else {
System.err.println("no webcam found to take a picture");
}
}
};
button = new JButton("Snap a Picture!");
button.addActionListener(buttonListener);
list = new JList();
list.setMinimumSize(new Dimension(200,this.getHeight()));
add(picker, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
add(list, BorderLayout.EAST);
pack();
setVisible(true);
Thread t = new Thread() {
#Override
public void run() {
panel.start();
}
};
t.setName("example-starter");
t.setDaemon(true);
t.setUncaughtExceptionHandler(this);
t.start();
}
#Override
public void webcamOpen(WebcamEvent we) {
System.out.println("webcam open");
}
#Override
public void webcamClosed(WebcamEvent we) {
System.out.println("webcam closed");
}
#Override
public void webcamDisposed(WebcamEvent we) {
System.out.println("webcam disposed");
}
#Override
public void webcamImageObtained(WebcamEvent we) {
BufferedImage myImage;
try {
myImage = webcam.getImage();
LuminanceSource source = new BufferedImageLuminanceSource(myImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap);
DefaultListModel dlm = (DefaultListModel) list.getModel();
dlm.addElement(result.toString());
list.setModel(dlm);
} catch (NotFoundException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ChecksumException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (FormatException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void windowOpened(WindowEvent e) {
// do nothing
}
#Override
public void windowClosing(WindowEvent e) {
// do nothing
}
#Override
public void windowClosed(WindowEvent e) {
webcam.close();
}
#Override
public void windowIconified(WindowEvent e) {
System.out.println("webcam viewer paused");
panel.pause();
}
#Override
public void windowDeiconified(WindowEvent e) {
System.out.println("webcam viewer resumed");
panel.resume();
}
#Override
public void windowActivated(WindowEvent e) {
// do nothing
}
#Override
public void windowDeactivated(WindowEvent e) {
// do nothing
}
#Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println(String.format("Exception in thread #s", t.getName()));
e.printStackTrace();
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem() != webcam) {
if (webcam != null) {
panel.stop();
remove(panel);
webcam.removeWebcamListener(this);
webcam.close();
webcam = (Webcam) e.getItem();
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.addWebcamListener(this);
System.out.println("selected " + webcam.getName());
panel = new WebcamPanel(webcam, false);
panel.setFPSDisplayed(true);
add(panel, BorderLayout.CENTER);
pack();
Thread t = new Thread() {
#Override
public void run() {
panel.start();
}
};
t.setName("example-stopper");
t.setDaemon(true);
t.setUncaughtExceptionHandler(this);
t.start();
}
}
}
#Override
public void webcamFound(WebcamDiscoveryEvent event) {
if (picker != null) {
picker.addItem(event.getWebcam());
}
}
#Override
public void webcamGone(WebcamDiscoveryEvent event) {
if (picker != null) {
picker.removeItem(event.getWebcam());
}
}
}
Am I missing something about how this library scans for a barcode?
EDIT
Not sure this helps much..
Mar 02, 2015 10:04:34 PM sandbox_webcam.AdvancedWebcamPanelExample webcamImageObtained
SEVERE: null
com.google.zxing.NotFoundException
Throws exception here:
Result result = reader.decode(bitmap);
There is a different question which has some available answers: Android zxing NotFoundException
As James said, it is a good idea to try with bar codes on different media (paper/screen) if it is not working, and in different circumstances and lighting conditions. Particularly ensure that you have enough light, and that the FPS of the camera is high enough while it is pointed at the barcode.
For debugging, one could also convert the BinaryImage back into a viewable format and check whether the barcode is actually visible after conversion to black-and-white.
The following code opens a JInternalFrame when a button is clicked. But I want this window to be opened once, so if the user clicks that button again it will not open another frame instead it would bring to the front the window whether it is iconified, behind another window, etc. I have tried a couple of ways mainly using a counter, but the problems is once the frame is closed it doesn't open it again either. Is there another easy way to do this, cause I am not able to make it work properly. Thanks in advance.
Below is the code I am working on:
public class About implements ActionListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
int count =0;
MyInternalFrame frame;
public About(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
System.out.println(count);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
count += 1;
if(count == 1){
frame = new MyInternalFrame("SAD Imaging");
count +=1;
try {
in = new BufferedReader(new FileReader("SADInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Tarea = new JTextArea();
//System.out.println(file);
Tarea.setText(file);
Font f = new Font("TimesNewRoman", Font.ROMAN_BASELINE, 16);
Tarea.setFont(f);
Tarea.setBackground(Color.white);
Tarea.setAlignmentX(SwingConstants.CENTER);
Tarea.setEditable(false);
JPanel panel = new JPanel();
panel.add(Tarea);
panel.setBackground(Color.white);
//scroll = new JScrollPane(Tarea);
scroll = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.add(scroll);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
else if(count > 1){
try {
//frame.setIcon(true);
frame.setMaximum(true);
frame.toFront();
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Basically, you just need to check to see if the frame is null or not. If it is, you create an instance, if it's not, you bring it to the front, for example
#Override
public void actionPerformed(ActionEvent arg0) {
if (frame == null || (frame.getParent() == null && !frame.isIconifiable())) {
// Your exitsing code
} else {
frame.setIcon(false);
frame.setSelected(true);
frame.moveToFront();
}
You can also use an InteralFrameListener to the frame so you can detect when the frame is closed, so you null the internal reference, for example...
frame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
frame = null;
}
});
Updated with runnable example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestInternalFrame {
public static void main(String[] args) {
new TestInternalFrame();
}
private JInternalFrame imageFrame;
private JDesktopPane desktop;
public TestInternalFrame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JMenu fileMenu = new JMenu("File");
JMenuItem newMenu = fileMenu.add("Show...");
newMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (imageFrame == null || imageFrame.isClosed()) {
imageFrame = new JInternalFrame("Image");
imageFrame.setIconifiable(true);
imageFrame.setMaximizable(true);
imageFrame.setClosable(true);
imageFrame.setResizable(true);
JLabel label = new JLabel(new ImageIcon("..."));
imageFrame.add(label);
imageFrame.pack();
desktop.add(imageFrame);
imageFrame.setLocation(0, 0);
imageFrame.setVisible(true);
}
try {
imageFrame.setIcon(false);
imageFrame.setSelected(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
imageFrame.moveToFront();
}
});
desktop = new JDesktopPane();
JMenuBar mb = new JMenuBar();
mb.add(fileMenu);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(mb);
frame.add(desktop);
frame.setSize(1200, 900);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
i am trying to make a simple reaction test in java.
when the screen turns green i press space witch is supposed to change te boolean "clicked into false and stop the loop that measures time.
in reality the key listner does nothing.
am i adding the keay listener to the right compnent( jpanel panel)?
is there any other problems?
import java.awt.Color;
import java.awt.RenderingHints.Key;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class mainCheck {
// //////////////////////////////////////
public static void timeKeeper() {
boolean clicked=false;
long time = 10000;
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
panel.setBackground(Color.GREEN);
while (time > 0 && !clicked) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
time--;
}
panel.setBackground(Color.gray);
long time2= 10000-time;
JLabel x = new JLabel("" +time2+"");
panel.add(x);
}
// //////////////////////////////////////
static boolean clicked;
JFrame frame;
static JPanel panel;
public mainCheck() {
frame = new JFrame();
panel = new JPanel();
clicked = false;
Handler handler = new Handler();
frame.addKeyListener(handler);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
// //////////////////////////////////////
public static void main(String[] args) {
mainCheck f = new mainCheck();
panel.getActionMap();
f.timeKeeper();
}
// //////////////////////////////////////
public class Handler implements KeyListener {
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
clicked = false;
System.out.println("space pressed");
}
}
}
}
do not use Thread.sleep(5000); block Event Dispatch Thread and during sleep you can lost all events to the already visible Swing GUI
use Swing Timer instead
Thread.sleep(1); could be proper delay for space enviroment, non_human, very short period attacking latency in Native OS (8-14miliseconds, depends of Native OS)
JLabel x = new JLabel("" +time2+""); and panel.add(x); in AWT/Swing isn't any notifiers that some, any, part of JComponents are removed or added, have to notify used LayoutManager (JPanel has FlowLayout in API) by using methods revalidate and repaint, e.g.
.
JLabel x = new JLabel("" +time2+"");
panel.add(x);
panel.revalidate();
panel.repaint();
Swing GUI should be created on Initial Thread
don't to use KeyListener use KeyBindings instead, otherwise you (are focus hunter) would need to set panel.seFocusable(true);
The problem is that you "e.getKeyCode()" always is "0" so
change for "e.getKeyChar()" and "(char)32"
the other problem is in that you put clicked = false and must be
"true"
And the last problem you have is in "timeKeeper()" you have to erase "boolean" because it is already declarated
Bad
public static void timeKeeper() {
boolean clicked=false
....}
Good
public static void timeKeeper() {
clicked=false
....}
This is the correct code:
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
public class mainCheck {
// //////////////////////////////////////
public static void timeKeeper() {
clicked=false;
long time = 10000;
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
panel.setBackground(Color.GREEN);
while (time > 0 && !clicked) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
time--;
}
panel.setBackground(Color.gray);
long time2= 10000-time;
JLabel x = new JLabel("" +time2+"");
panel.add(x);
}
// //////////////////////////////////////
static boolean clicked;
JFrame frame;
static JPanel panel;
Handler handler = new Handler();
public mainCheck() {
frame = new JFrame();
panel = new JPanel();
clicked = false;
frame.addKeyListener(handler);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
// //////////////////////////////////////
public static void main(String[] args) {
mainCheck f = new mainCheck();
panel.getActionMap();
f.timeKeeper();
}
// //////////////////////////////////////
public class Handler implements KeyListener {
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == (char)32) {
clicked = true;
System.out.println("space pressed");
}
}
}
}
It's a really bad idea to use Thread.sleep() to decrement the time value.
Use a Timer object instead:
public void myTimer(){
Timer myTimer = new Timer(delay, new ActionListener(){
public void actionPerformed(ActionEvent e){
//Stuff to do
}
});
}
Where delay is the amount of time you delay the timer. You start the timer with myTimer.start();
I am having some problems with my program. I have a GUI that shows a live image from a webcam (using [jvacv][1]) in one side, and the captured image in the other. To capture the image, I have a button. One problem is that the captured image is refreshing only if I close and open the program again. The other is that I want to capture a 1080p image from webcam, but live image at 640x480.
Here is the code:
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.FrameGrabber.Exception;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
public class Final
{
private VideoPanel videoPanel = new VideoPanel();
private ImagePanel imagePanel = new ImagePanel();
private JButton jbtCapture = new JButton("Captura");
private JRadioButton jbtAutoCap = new JRadioButton("Captura Automatica");
private FrameGrabber vision;
private BufferedImage image;
private IplImage gimage;
public class VideoPanel extends JPanel
{
public VideoPanel()
{
vision = new OpenCVFrameGrabber(0);
try
{
vision.start();
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
try {
image = vision.grab().getBufferedImage();
if (image != null)
{
g.drawImage(image, 0, 0, 640, 480, null);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
class ImagePanel extends JPanel
{
private BufferedImage image;
public ImagePanel()
{
try {
image = ImageIO.read(new File("image001.bmp"));
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(image != null)
{
g.drawImage(image,5,0,640,480, null);
}
}
}
private void displayGUI()
{
JFrame janela = new JFrame();
JPanel jpButton = new JPanel();
jpButton.setLayout(null);
jbtCapture.setBounds(145,0,110,30);
jpButton.add(jbtCapture);
jbtAutoCap.setBounds(0, 5, 140, 23);
jpButton.add(jbtAutoCap);
janela.setLayout(null);
videoPanel.setBounds(5, 5, 640, 480);
janela.add(videoPanel);
imagePanel.setBounds(705,5,640,480);
janela.add(imagePanel);
jpButton.setBounds(5, 500, 670, 40);
janela.add(jpButton);
janela.setSize(1366,730);
janela.setVisible(true);
jbtCapture.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try {
gimage = vision.grab();
cvSaveImage("image001.bmp", gimage);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
new Final().displayGUI();
}
});
}
}