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);
}
});
}
}
Related
new Scanner(new URL("SOME_URL.txt").openStream(), "UTF-8").useDelimiter("\\A").next();
Using this ^ I get the data from a .txt-File which I save in a String.
For my progress bar, I wondered if it would be possible for jobs like that (or in general for methods etc.) to count (or sth. like that) the time it needed to be finished. So that I can show in real time process time in my bar.
Is this somehow possible?
EDIT:
package app.gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.net.URL;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.io.IOUtils;
public class Updater {
private JFrame frame;
private static String rawG;
private static String versI;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
rawG = new Scanner(new URL("SOME_URL.txt").openStream(), "UTF-8").useDelimiter("\\A").next();
versI = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("version.txt"));
} catch (Exception e) {
System.out.println("error class Updater try/catch raw github");
}
if (Integer.parseInt(rawG.split("\\.")[0]) < Integer.parseInt(versI.split("\\.")[0])) {
System.out.println("Version check failure, update needed");
try {
Updater window = new Updater();
window.frame.setVisible(true);
} catch (Exception e) {
System.out.println("error class Updater try/catch initialize frame");
}
} else {
System.out.println("Version check correct, no update needed");
}
}
});
}
public Updater() {
initialize();
}
private void initialize() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.SOUTH);
panel.setLayout(new BorderLayout(0, 0));
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
panel.add(progressBar, BorderLayout.NORTH);
}
}
Is it possible? Yes. Is it possible when using Scanner.next() to read the contents of the URL? No.
You will need to read the bytes yourself, and count them:
URL url = new URL("SOME_URL.txt");
URLConnection conn = url.openConnection();
ByteBuffer buffer = ByteBuffer.allocate(conn.getContentLength());
EventQueue.invokeLater(() -> progressBar.setMaximum(buffer.limit()));
EventQueue.invokeLater(() -> progressBar.setValue(0));
try (ReadableByteChannel channel = Channels.newChannel(conn.getInputStream())) {
while (channel.read(buffer) >= 0) {
EventQueue.invokeLater(() -> progressBar.setValue(buffer.position()));
}
}
buffer.flip();
String rawG = StandardCharsets.UTF_8.decode(buffer).toString();
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.
I am new to programming, and created a little program to practice code. It is an authentication program where you type in a username and password, and only my specified username and password will work to make it show a picture. I typed all the code, and there was no error; but when I ran it and typed in the username and password, it failed to show the picture. Here is my code.
package main.Swing.com;
//imports
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.util.EventObject;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
//class that carries other classes and carries some variables
public class Main extends javax.swing.JFrame implements ActionListener, TextListener, InputMethodListener {
JButton Test = new JButton("TEST IF YOU HAVE ACCESS TO THIS");
JButton Cancel = new JButton("CANCEL");
JTextField username = new JTextField(15);
JTextField password = new JTextField(15);
String n = ("Nathan");
int nathannam;
int nathannamer;
JButton superman;
JButton supermanny;
//constructor class that has the jframe
public Main() {
super("Authenticator");
setSize(300, 220);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLookAndFeel();
//creating the pane and defining some labels
JPanel pane = new JPanel();
JLabel UsernameLabel = new JLabel("Username: ");
JLabel PasswordLabel = new JLabel("Password: ");
//adding all the components to the pane
pane.add(UsernameLabel);
pane.add(username);
pane.add(PasswordLabel);
pane.add(password);
pane.add(Test);
pane.add(Cancel);
//adding the pane
add(pane);
//adding a event listener to my JButton titled Test
Test.addActionListener(this);
//checking if the password variable and name variable are both
//correct by taking the values assigned to each of them later
//on in the code and adding them together and if they add together
//to the correct amount it should display a button, but it doesn't
//which is the problem I am having
if (nathannam + nathannamer == 24) {
ImageIcon superman = new ImageIcon("JButton.png");
JButton supermanny = new JButton(superman);
pane.add(supermanny);
}
//setting visibility to true
setVisible(true);
//end of constructor class
}
//start of class that checks if the username is correct
public void METHODPREFORMED(ActionListener evt) {
Object source = ((EventObject) evt).getSource();
//testing if username is equivalent to my name which is nathan
if (source == Test) {
String get = username.getText().toString();
String notation = "Nathan";
//if it is equivalent a variable will be assigned to nathanam
for (int i = 0; i < get.length(); i++) {
if (get.substring(i) == notation) {
int nathannam = 14;
//if it is not it will assign a wrong variable to nathannam
} else {
int nathannam = 15;
}
}
}
}
//testing if password variable is correct
public void ACTIONPREFORMED(ActionListener evt) {
Object source = ((EventObject) evt).getSource();
//testing if password is correct
if (source == Test) {
String got = password.getText().toString();
String notition = "iamnathan";
//if it is equivalent a variable will be assigned to nathanamer
for (int i = 0; i < got.length(); i++) {
if (got.substring(i) == notition) {
int nathannamer = 10;
//if it is not equivalent nathannamer will be assigned a wrong variable
} else {
int nathannamer = 15;
}
}
}
} //setting the nimbus setlookandfeel that was implemented in java 7
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} 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();
}
}
//adding the main method
public static void main(String[] args) {
setLookAndFeel();
Main main = new Main();
}
#Override
public void textValueChanged(TextEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void caretPositionChanged(InputMethodEvent event) {
// TODO Auto-generated method stub
}
#Override
public void inputMethodTextChanged(InputMethodEvent event) {
// TODO Auto-generated method stub
}
}//end of program
You never call your test method from your implementation of actionPerformed(). Here's a much simplified version of your program that checks username when you click on TestAccess.
Going forward, see How to Use Password Fields for a working example of using JPasswordField.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
/**
* #see
*/
public class Test {
private final JTextField username = new JTextField(15);
private final JButton test = new JButton("Test access");
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, 1));
f.add(username);
test.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("nathan".equalsIgnoreCase(username.getText()));
}
});
f.add(test);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Test().display();
});
}
}
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);
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();
}
});
}
}