Can anyone help me? Whenever I ran the codes below, it always returns a blank frame, I don't know where I did wrong. Can you guys help me debug this? I already added the components to the panel, and the panel to the frame, but still it returns a blank output.
Here is the output I'm getting:
While this is what is required.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.BoxLayout;
import java.awt.GridLayout;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JRadioButton;
/**
*
* #author Chareux
*/
//Declaring Variables
public class TestUI {
private JFrame frm_main;
private JPanel sr_pnl;
private JLabel sr_lbl;
private JLabel sr_lbl2;
private JLabel ret_optn_lbl;
private JLabel ret_rsn_lbl;
private ButtonGroup ret_ops;
private JTextField sr_txtnum;
private JTextField sr_ret_txtrsn;
private JButton sr_start;
private JRadioButton ret_optn_rdbn_y;
private JRadioButton ret_optn_rdbn_n;
public TestUI(){
start();
}
public void start(){
//Creating the JFrame
frm_main = new JFrame("Service Desk SR Tool");
frm_main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm_main.setSize(500,450);
frm_main.setLocationRelativeTo(null);
frm_main.setResizable(false);
frm_main.setVisible(true);
// the Panel
sr_pnl = new JPanel();
//Components
sr_lbl = new JLabel("SERVICE DESK SR TIMER!");
sr_lbl2 = new JLabel("SR number: ");
sr_txtnum = new JTextField("Enter SR number here..",20);
ret_optn_lbl = new JLabel("Returning Ticket?");
ret_optn_rdbn_y = new JRadioButton("Yes");
ret_optn_rdbn_n = new JRadioButton("No");
ret_rsn_lbl = new JLabel("Reason: ");
sr_ret_txtrsn = new JTextField("Enter Reason number here..",20);
sr_start = new JButton("START!");
//adding the Components to the panel
sr_pnl.add(sr_lbl);
sr_pnl.add(sr_lbl2);
sr_pnl.add(sr_txtnum);
sr_pnl.add(ret_optn_lbl);
sr_pnl.add(ret_optn_rdbn_y);
sr_pnl.add(ret_optn_rdbn_n);
sr_pnl.add(ret_rsn_lbl);
sr_pnl.add(sr_ret_txtrsn);
sr_pnl.add(sr_start);
frm_main.add(sr_pnl,BorderLayout.CENTER);
//ButtonGroup for the radio button
ret_ops = new ButtonGroup();
ret_ops.add(ret_optn_rdbn_y);
ret_ops.add(ret_optn_rdbn_n);
}
public static void main(String[] args) {
new TestUI();
}
}
I'd recommend to use a nested or compound layout for this task. See further tips in comments in the source.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class SRTool {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new GridLayout(0,1,6,6));
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
// show the BG
gui.setBackground(Color.CYAN);
// center the label text
gui.add(new JLabel(
"Service Desk SR Tool", SwingConstants.CENTER));
// create a lyout that can center multiple components
FlowLayout layout = new FlowLayout(FlowLayout.CENTER,5,5);
JPanel srPanel = new JPanel(layout);
gui.add(srPanel);
srPanel.add(new JLabel("SR:"));
srPanel.add(new JTextField(8));
JPanel returnTicketPanel = new JPanel(layout);
gui.add(returnTicketPanel);
returnTicketPanel.add(new JLabel("Returning Ticket?"));
returnTicketPanel.add(new JCheckBox());
JPanel reasonPanel = new JPanel(layout);
gui.add(reasonPanel);
reasonPanel.add(new JLabel("Reason:"));
reasonPanel.add(new JTextField(14));
JPanel buttonPanel = new JPanel(layout);
gui.add(buttonPanel);
buttonPanel.add(new JButton("Start!"));
JFrame f = new JFrame("Demo");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See https://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
Add frm_main.validate() in the end of start()
public void start(){
/*
...
Same As Above
...
*/
frm_main.add(sr_pnl,BorderLayout.CENTER);
//ButtonGroup for the radio button
ret_ops = new ButtonGroup();
ret_ops.add(ret_optn_rdbn_y);
ret_ops.add(ret_optn_rdbn_n);
frm_main.validate(); // Add this line ******
}
Related
I can't seem to find a solution online for why I'm getting this error on attempted run
I'm working on making a simple test system for a different program when are button press will yield value in a text box. I would like them to be on different lines to make it cleaner, so I looked into layouts. I decided a Box Layout would fit me best. I looked at different examples before attempting this and my code ended up looking like this, (apologies for the messy code)
Update
Got the box layout error to disappear but the code will not center them on the panel/frame. The label and button align left while the textfield becomes very large. I don't need it todo that
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import static javax.swing.BoxLayout.Y_AXIS;
import static javax.swing.SwingConstants.CENTER;
public class button extends JFrame {
static JFrame f;
static JButton b;
static JLabel l;
// main class
public static void main(String[] args)
{
// create a new frame to stor text field and button
f = new JFrame("panel");
BoxLayout layout = new BoxLayout(f, BoxLayout.Y_AXIS);
f.setLayout(layout);
// create a label to display text
l = new JLabel("panel label");
b = new JButton("button1");
JTextField textArea = new JTextField(5);
textArea.setEditable(false);
//textArea.append("Hello World");
// create a panel to add buttons
JPanel p = new JPanel();
// add buttons and textfield to panel
f.add(p);
f.setSize(300, 300);
p.add(l);
p.add(b);
p.setBackground(Color.white);
p.add(textArea);
f.show();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Random r = new Random();
textArea.setText(String.valueOf(r));
}
});
}
}
Error
Exception in thread "main" java.awt.AWTError: BoxLayout can't be shared
at java.desktop/javax.swing.BoxLayout.checkContainer(BoxLayout.java:461)
at java.desktop/javax.swing.BoxLayout.invalidateLayout(BoxLayout.java:245)
at java.desktop/javax.swing.BoxLayout.addLayoutComponent(BoxLayout.java:278)
at java.desktop/java.awt.Container.addImpl(Container.java:1152)
at java.desktop/java.awt.Container.add(Container.java:1029)
at java.desktop/javax.swing.JFrame.addImpl(JFrame.java:553)
at java.desktop/java.awt.Container.add(Container.java:436)
at button.main(button.java:36)
I would like the three items to all to be stacked one on top of another with a space between them. The order doesn't matter right now.
Swing was first added to the JDK in 1998 and has undergone a lot of changes since. Unfortunately, when you read Web pages about Swing, it is not obvious when that page was last updated. Consequently you may be learning outdated techniques for writing Swing code.
First of all, according to the code you posted, class button does not need to extend class JFrame since you use a static variable as your application's JFrame. Also, JFrame is a top-level container which makes it a special kind of container and not the same kind of continer as a JPanel. You need to set the layout manager for your JPanel and then add the JLabel, JTextField and JButton to that JPanel. And then add the JPanel to the JFrame.
Calling method pack() of class JFrame will automatically set the preferred sizes for the components inside the JFrame. It appears in the code below.
Please also look at Java coding conventions which allows others to more easily read and understand your code. And note that, according to these conventions, I renamed your class from button to Buttons and also because there are already several class in the JDK named Button.
Here is my rewrite of your code...
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class Buttons implements Runnable {
public void run() {
createAndShowGui();
}
private void createAndShowGui() {
JFrame f = new JFrame("Box");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel p = new JPanel();
BoxLayout layout = new BoxLayout(p, BoxLayout.Y_AXIS);
p.setLayout(layout);
JLabel l = new JLabel("panel label");
JTextField textField = new JTextField(5);
JButton b = new JButton("button1");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Random r = new Random();
textField.setText(String.valueOf(r.nextBoolean()));
}
});
p.add(l);
p.add(textField);
p.add(b);
f.add(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
Buttons instance = new Buttons();
EventQueue.invokeLater(instance);
}
}
I am developing a simple application, and am currently working on the gui design using Swing. In my program I have a JPanel which I would like to have a background color black like so:
JPanel playerPanel = new JPanel();
playerPanel.setOpaque(true);
playerPanel.setBackground(Color.BLACK);
This code works fine. However, the problem is when I assign a Layout Manager to the panel:
JPanel playerPanel = new JPanel();
playerPanel.setOpaque(true);
playerPanel.setBackground(Color.BLACK);
playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.PAGE_AXIS));
For some reason, this makes the black color of the panel go away. This happens no matter where I place the .setLayout(...) command, before or after the .setBackground(...) and .setOpaque(true).
Why is this, and how do I work around this? How do I keep a black JPanel that uses a BoxLayout manager?
Verify that your panel's content is not obscuring the altered background. Resize the example below, which I've artificially enlarged, to see the effect.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.Random;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* #see https://stackoverflow.com/a/57785802/230513
*/
public class BoxTest {
public static final Random random = new Random();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new BoxTest().create();
}
});
}
void create() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBackground(Color.BLACK);
panel.add(Box.createVerticalGlue());
for (int i = 0; i < 4; i++) {
panel.add(new VariablePanel());
panel.add(Box.createVerticalGlue());
}
JFrame f = new JFrame("BoxTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setSize(f.getWidth(), f.getHeight() + 64);
}
}
/**
* A VariablePanel has a label showing its current size,
* as well as a variable number of text items.
*/
class VariablePanel extends JPanel {
private static final String text =
"Sed ut perspiciatis unde omnis iste natus error sit.";
private final JLabel sizeLabel = new JLabel("Size:");
public VariablePanel() {
this.setLayout(new GridLayout(0, 1));
this.add(sizeLabel);
int count = BoxTest.random.nextInt(5) + 1;
for (int i = 0; i < count; i++) {
this.add(new JLabel(text));
}
this.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
int w = e.getComponent().getWidth();
int h = e.getComponent().getHeight();
sizeLabel.setText("Size: " + w + "\u00d7" + h);
}
});
}
}
Swing components (except JLabel) are opaque by default. This means:
you don't need playerPanel.setOpaque(true)
most components you add to the panel will be opaque and cover the background of your playerPanel.
Also, the BoxLayout respects the maximum size of any component you add to the panel. So if you add a component:
like a JButton which has a defined maximum size, you will see the button on top of the playerPanel and the background will surround the button.
like a JPanel, which does not have a defined maximum size, the panel will be resized to fill the entire area of the playerPanel and you won't see the background of the playerPanel.
If you want to see the background of the playerPanel show through a component added to the playerPanel, then you need to use setOpaque(false) on the component. For example:
JPanel child = new JPanel();
child.setOpaque( false );
playerPanel.add( child );
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have been given an assignment whereby I need to create a tool that analyses a field of text and then outputs a couple of statistics about said body of text via a button click. I seem to have most of the basic framework up but am struggling with getting my two labels that are averageLength and totalWords inside my JPanel and also on getting said JPanel below where I enter my body of text. Any help would be much appreciated. Code is here:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextStatisticsPanel extends JPanel
{
//Field for block of text
private JTextArea userText;
//Button to calculate Statistics
private JButton stats;
//Label for where statistics are shown and statistics
private JLabel averageLength, totalWords;
public TextStatisticsPanel(){
//creating the area for user text with wrapped text
userText = new JTextArea();
userText.setWrapStyleWord(true);
userText.setLineWrap(true);
//create button
stats = new JButton("Update Text Statistics");
//Listener for button
stats.addActionListener(new ButtonListener());
//Tilted border creater
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));
statPanel.setOpaque(false);
//Create Scroller
JScrollPane scroller = new JScrollPane(userText);
scroller.setPreferredSize(new Dimension (350, 400));
scroller.setBorder(BorderFactory.createTitledBorder ("Enter the text below"));
//Add the statistics labels
averageLength = new JLabel("The average length of the words: ");
totalWords = new JLabel("The total number of words: ");
//add GUI
add(statPanel);
add(scroller);
add(averageLength);
add(totalWords);
setBackground(new java.awt.Color(202, 225, 255));
setPreferredSize(new Dimension (400, 600));
add(stats);
}
// When button is pressed do :
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == stats){
//Call statUpdate Method
statUpdate();
}
}
// Create statUpdate Method
private void statUpdate()
{
//Grab text user inputed
String text = userText.getText();
//Split the text by each space to find the number of words
String[] words = text.split(" ");
//Calculation for average
float average = (text.length() - words.length)/words.length;
//
averageLength.setText(String.valueOf(average));
totalWords.setText(String.valueOf(words.length));
System.out.println(averageLength);
System.out.println(totalWords);
}
}
}
OK so as to try and use MCVE, this is part of the relevent code however I am still unable to work out the root of the problem.
The code for my second panel is :
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));
statPanel.setOpaque(false);
SO as per my understanding this is me creating a second panel among my app. The problem however is that this is being placed in a seemingly random location and is not wrapping around the two labels I wish to be inside this panel and I am unsure how to fix this problem.
The main class code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JFrame;
public class TextStatistics {
public static void main(String[] args) {
JFrame frame = new JFrame("Text Statistics Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextStatisticsPanel panel = new TextStatisticsPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Providing a visual example to show the code I believe is the problem and the problem I am encountering
Problem Visualised
Here's the GUI I put together.
These are the major changes I made.
I put the JFrame code in a Runnable, so I could start the Swing application with a call to the SwingUtilities invokeLater method. The invokeLater method ensures that the Swing components are created and updated on the Event Dispatch thread. Oracle and I require that everyone starts their Swing applications on the Event Dispatch thread.
I defined several new JPanels in your TextStatisticsPanel class and used two Swing layout managers, BorderLayout and BoxLayout. Study the link in the previous sentence. By study, I mean spend at least two to three weeks of 8 hour days absorbing all of the ins and outs of the Swing layout managers.
I added JTextFields to hold the calculated values. That's what JTextFields are for.
I fixed the integer division in your statUpdate method.
Here's the code. I put everything together in one file so it would be easier to upload. You should put the classes in separate files.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TextStatistics {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Text Statistics Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextStatisticsPanel panel = new TextStatistics().new TextStatisticsPanel();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}
public class TextStatisticsPanel extends JPanel {
private static final long serialVersionUID = 9049744714586970558L;
// Field for block of text
private JTextArea userText;
// Button to calculate Statistics
private JButton stats;
// Label for where statistics are shown and statistics
private JLabel averageLength, totalWords;
private JTextField averageLengthField, totalWordsField;
public TextStatisticsPanel() {
// creating the area for user text with wrapped text
userText = new JTextArea();
userText.setWrapStyleWord(true);
userText.setLineWrap(true);
// create button
stats = new JButton("Update Text Statistics");
stats.setAlignmentX(JButton.CENTER_ALIGNMENT);
// Listener for button
stats.addActionListener(new ButtonListener());
// Tilted border creater
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory
.createTitledBorder("Text Statistics"));
statPanel.setLayout(new BoxLayout(statPanel, BoxLayout.PAGE_AXIS));
statPanel.setOpaque(false);
// Create Scroller
JScrollPane scroller = new JScrollPane(userText);
scroller.setPreferredSize(new Dimension(350, 400));
scroller.setBorder(BorderFactory
.createTitledBorder("Enter the text below"));
// Add the statistics labels
averageLength = new JLabel("The average length of the words: ");
averageLength.setOpaque(false);
averageLengthField = new JTextField(10);
averageLengthField.setEditable(false);
averageLengthField.setOpaque(false);
totalWords = new JLabel("The total number of words: ");
totalWords.setOpaque(false);
totalWordsField = new JTextField(10);
totalWordsField.setEditable(false);
totalWordsField.setOpaque(false);
// add GUI
setLayout(new BorderLayout());
statPanel.add(stats);
statPanel.add(Box.createVerticalStrut(10));
JPanel lengthPanel = new JPanel();
lengthPanel.setOpaque(false);
lengthPanel.add(averageLength);
lengthPanel.add(averageLengthField);
statPanel.add(lengthPanel);
statPanel.add(Box.createVerticalStrut(10));
JPanel wordsPanel = new JPanel();
wordsPanel.setOpaque(false);
wordsPanel.add(totalWords);
wordsPanel.add(totalWordsField);
statPanel.add(wordsPanel);
add(statPanel, BorderLayout.SOUTH);
add(scroller, BorderLayout.CENTER);
setBackground(new java.awt.Color(202, 225, 255));
}
// When button is pressed do :
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == stats) {
// Call statUpdate Method
statUpdate();
}
}
// Create statUpdate Method
private void statUpdate() {
// Grab text user inputed
String text = userText.getText();
// Split the text by each space to find the number of words
String[] words = text.split(" ");
// Calculation for average
float average = ((float) text.length() - words.length)
/ words.length;
//
averageLengthField.setText(String.valueOf(average));
totalWordsField.setText(String.valueOf(words.length));
}
}
}
}
I have wrote a java program, it has a CardLayout with a JPanel for each card.
The JPanel contains long text, I just need to implement a little "search bar" that just search for specified text on the viewed JPanel.
It simply has to highlight the searched text inside the JPanel.
In order to make it clearer, I'm talking about something like the Chrome's of Firefox's search bar (ctrl-f) but that works just for one JPanel in my program.
Here is a picture.
Is it possible? How can I do that?
Thanks
Easiest way is to create a small search JPanel that is positioned above your text JPanel. Both JPanels would be inside of another JPanel. I'd use a JTextField and a JButton, because I like the user in control of when to search.
Here's one of my GUI's with a search JPanel.
And here's the code to create the search JPanel. Note that I used a JPanel. You only extend Swing components when you want to override one of the component methods.
package gov.bop.cobol.paragraph.structure.view;
import gov.bop.cobol.paragraph.structure.model.ParagraphStructureModel;
import gov.bop.cobol.paragraph.structure.thread.SearchActionThread;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SearchPanel {
protected JPanel panel;
protected JTextField findTextField;
protected ParagraphStructureFrame frame;
protected ParagraphStructureModel model;
public SearchPanel(ParagraphStructureFrame frame,
ParagraphStructureModel model) {
this.frame = frame;
this.model = model;
createPartControl();
}
protected void createPartControl() {
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
JLabel findLabel = new JLabel("Search:");
panel.add(findLabel);
panel.add(Box.createRigidArea(new Dimension(6, 0)));
findTextField = new JTextField(30);
panel.add(findTextField);
panel.add(Box.createRigidArea(new Dimension(6, 0)));
JButton findButton = new JButton("Search");
findButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
String s = findTextField.getText().toUpperCase().trim();
if (!s.equals("")) {
findTextField.setText(s);
Thread thread = new Thread(new SearchActionThread(frame,
model, s));
thread.start();
}
}
});
panel.add(findButton);
}
public JPanel getPanel() {
return panel;
}
}
I come to you because I have a strange issue, for which I don't find any solution...
I build an application using a webcam, in order to take some photographs.
I use WebcamCapture to do that, and I don't encounter any issues with it.
The only "weird" thing that happens is the following :
I use a JDialog in which I make photograph. In its JFrame parent, I display those photographs in JLabel.
Then, i need to disable those JLabel, and I do that by calling a method which disable all components. The weird thing is, when I disable JLabel, the JLabel display the last image capture by the webcam. Not the last photographs, but really the last captured image.
It's seems that BufferedImage (used by WebcamPanel) are linked to the issue.
Here is the SSCE :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
#SuppressWarnings("serial")
public class CameraFrame extends JFrame implements ActionListener{
public Webcam webcam;
Boolean enabled = true;
CameraFrame frame;
private JButton btnSaveVerso;
private JLabel lblVerso;
private JButton btnEnable;
private JButton btnQuit;
private JPanel mainPanel;
private WebcamPanel streamPanel;
public static void main(String[] args){
CameraFrame frame = new CameraFrame();
frame.setVisible(true);
}
public CameraFrame() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setMinimumSize(new Dimension(800, 600));
setPreferredSize(new Dimension(800,600));
buildPanel();
setContentPane(mainPanel);
}
});
}
public void buildPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
Border blackline = BorderFactory.createLineBorder(Color.black, 1, true);
webcam = Webcam.getDefault();
webcam.open();
streamPanel = new WebcamPanel(webcam);
streamPanel.setPreferredSize(new Dimension(webcam.getViewSize()));
streamPanel.setMaximumSize(new Dimension(webcam.getViewSize()));
btnSaveVerso = new JButton("Take pic");
btnSaveVerso.setActionCommand("take");
btnSaveVerso.addActionListener(this);
lblVerso = new JLabel("Here will be the pic taken by the camera");
lblVerso.setBorder(blackline);
btnEnable = new JButton("Disable");
btnEnable.setActionCommand("disable");
btnEnable.addActionListener(this);
btnQuit = new JButton("Quit");
btnQuit.setActionCommand("quit");
btnQuit.addActionListener(this);
mainPanel.add(streamPanel);
mainPanel.add(btnSaveVerso);
mainPanel.add(lblVerso);
mainPanel.add(btnEnable);
mainPanel.add(btnQuit);
}
#Override
public void actionPerformed(final ActionEvent e) {
Thread newThread = new Thread(){
public void run(){
if(e.getActionCommand().equals("take")){
ImageIcon icon = new ImageIcon(webcam.getImage().getScaledInstance(100, 150, Image.SCALE_SMOOTH ));
lblVerso.setIcon(new ImageIcon(icon.getImage()));
lblVerso.revalidate();
lblVerso.repaint();
}
else if(e.getActionCommand().equals("disable")){
if(enabled){
lblVerso.setEnabled(false);
enabled = false;
btnEnable.setText("Enable");
}
else{
lblVerso.setEnabled(true);
enabled = true;
btnEnable.setText("Disable");
}
}
}
};
newThread.run();
if(e.getActionCommand().equals("quit")){
webcam.close();
this.setVisible(false);
}
}
}
I hope you will compile it without issues. Don't forget to link the librairies.
Thanks in advance
I finally resolved the problem : you simply need to close the webcam after each pictures, as follows :
BufferedImage picture = webcam.getImage();
webcam.close();
webcam.open();
... Do what you need with picture
(You don't even need to convert BufferedImage picture in an other type.)