ScrollArea and ScrollBar not working - java

I've been trying to make a java swing based application to retrieve tweets from a user by using twitter4j..the code seems to be working when pretend on the console but not adding ..i've tried adding the scroll area and scroll bar to help with text wrapping and longer texts but it seems to be not working..
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import twitter4j.*;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
public class mainTwitter {
public static void main(String args[])
{
List<Status> statuses=null;
String user;
try{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("*************")
.setOAuthConsumerSecret("*************")
.setOAuthAccessToken("*************")
.setOAuthAccessTokenSecret("*************");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
if(args.length==1)
{
user=args[0];
statuses=twitter.getUserTimeline(user);
}
else
{
user = twitter.verifyCredentials().getScreenName();
statuses = twitter.getUserTimeline();
}
System.out.println("Showing "+user+"'s user timeline.");
/*
for(Status status: statuses)
{
System.out.println("#"+status.getUser().getScreenName()+"-"+status.getText());
}*/
}
catch(Exception e)
{
e.printStackTrace();
}
JFrame mainFrame = new JFrame("Twitter Montior");
mainFrame.setLocationByPlatform(true);
mainFrame.setLocation(360, 80);
JPanel tPanel = new JPanel();
JPanel bPanel = new JPanel();
mainFrame.setLayout(null);
///////////////////////////////////////////////////////////////////////////////
//Top Panel
JTextField t1 = new JTextField("Twitter Monitor!!");
t1.setBackground(Color.yellow);
t1.setHorizontalAlignment(JTextField.CENTER);
t1.setEditable(false);
Font new_f = new Font("Serif", Font.PLAIN, 30);
t1.setFont(new_f);
JTextArea userInfo=new JTextArea();
Font font2 = new Font("Serif", Font.PLAIN, 20);
userInfo.setFont(font2);
userInfo.setLineWrap(true);
userInfo.setWrapStyleWord(true);
userInfo.setBackground(Color.LIGHT_GRAY);
userInfo.setEditable(false);
userInfo.setLineWrap(true);
JScrollPane scrollArea = new JScrollPane(userInfo);
scrollArea.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JScrollBar bar = new JScrollBar();
scrollArea.add(bar);
tPanel.add(scrollArea);
JButton retrieve = new JButton("Click");
tPanel.setLayout(null);
t1.setBounds(150, 2, 250, 30);
userInfo.setBounds(0,34,700,260);
retrieve.setBounds(260, 300, 50, 20);
tPanel.add(retrieve);
tPanel.add(t1);
tPanel.add(userInfo);
///////////////////////////////////////////////////////////////////////////////
///Bottom Panel..
///////////////////////////////////////////////////////////////////////////////
tPanel.setBounds(0, 0, 700, 350);
bPanel.setBounds(0,352,700,248);
handler h = new handler(statuses, userInfo);
retrieve.addActionListener(h);
mainFrame.add(tPanel);
mainFrame.add(bPanel);
mainFrame.setSize(700, 600);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
}
class handler implements ActionListener
{
List<Status> statuses2;
JTextArea t;
handler(List<Status> statuses1, JTextArea f)
{
statuses2=statuses1;
t=f;
}
#Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if(s=="Click")
{
for(Status status: statuses2)
{
System.out.println("#"+status.getUser().getScreenName()+"-"+status.getText());
t.setText("#"+status.getUser().getScreenName()+"-"+status.getText());
t.setText("\n");
}
}
}
}

I think your main problem is that you use null layout, and you need to choose size and place of every components inside mainFrame and your panels. In my opinion is very bad idea and it is generally not recommended. It would be much simpler to write it with use of BorderLayout for JFrame, and other for your JPanels. But it is up to you.
It this particular case, in my opinion your scrollArea is not working because:
You add userInfo twice, first to scrollArea, then to tPanel directly. So what you see when you run program, is userInfo in tPanel, because components could be added to only one container.
You use a null layout so it is necessary to setBounds() for every component inside container with such layout settings, but you didn't setBounds() for scrollArea.
So the quickest way to make it work:
delete line tPanel.add(userInfo);,
change scrollArea.setBounds(0,34,700,260); for userInfo.setBounds(0,34,700,260); - it is enough to change component it relete to,
After those changes it should work.
Aditional comments:
you dont't need to add JScrollBar to JScrollPane, it has it by itself,
the mainFrame.setLocationByPlatform(true); line is not working and it is not necessary, becouse you setLocation() of mainFrame manually and use null layout,
you use userInfo.setLineWrap(true); twice, you can delete one line,

Related

Java swing jtextarea on a tab does not fill out the tab, cannot get it to fill even with scrollbar added

So I'm using the Oracle tabbed example to create a Java swing application to help retrieve quick data from an internal database for a very small company and I'm very new at Java (decent scripting, though). My problem is that retrieved data from the database goes outside tab boundariesenter image description here. From reading a question, I learned I should use a textarea, so I modified to use a text area but then I could not scroll. I fixed the scroll, but now the data is just in a small window on the tab. I can enlarge the tab, I have my scrolls, but I cannot fill out the text area.
This is the gridlayout from the documentation example:
super(new GridLayout(8, 40));
This is the pane that displays the information where inv is an array list defined as follows:
ArrayList<String> inv = new ArrayList<String>();
The data is pulled into the pane with the following code (note that the dimension does not change the text area, in fact, I do not believe this has any effect on the code at all so it is commented out during my testing:
JComponent panel2 = makeTextPanel(inv.toString());
//panel2.setPreferredSize(new Dimension(100, 50));
tabbedPane.addTab("Customers", null, panel2,
"Displays Customer Details");
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
} catch (SQLException sqlException) {
System.out.println(sqlException);
}
This is the code for the panel using scroll tab, text area, etc. which is a modified version of the copied code:
//Add the tabbed pane to this panel.
add(tabbedPane);
//The following line enables to use scrolling tabs.
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}
protected JComponent makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JTextArea filler = new JTextArea(text, 100, 50);
JScrollPane scroll = new JScrollPane (filler,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//filler.setHorizontalAlignment(JTextArea.CENTER);
panel.setLayout(new GridLayout(1, 1));
//panel.add(filler);
panel.add(scroll);
return panel;
}
The tabbed pane is then displayed using the original code which I did not make any changes:
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TabbedPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new TabbedPane(), BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
The question is, how can I get the text area to fill out the pane instead of just being 1/4 the size (regardless of how I resize the window either in the code or the GUI? The documentation doesn't seem to offer me much (based on searches) that work as I am already setting the scrollbar in the textarea like the documentation specifies. I tried setLineWrap(true) like another question but that was of no help either. See the image for an example of the issue I'm having. Any thoughts?
I'd use a BorderLayout to control the layout of the JScrollPane so it can automatically fill the available space.
You can control the JTextArea's visible size via it's rows and columns properties
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
// Replace this with your text retrieval process
List<String> text = new ArrayList<String>(128);
try (BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/StarWarANewHope.txt")))) {
String line = null;
while ((line = br.readLine()) != null) {
text.add(line);
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
// Use this to format the results for the text area
StringJoiner joiner = new StringJoiner("\n");
for (String line : text) {
joiner.add(line);
}
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Customers", null, new TestPane(joiner.toString()), "Displays customer details");
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tabbedPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane(String text) {
JTextArea filler = new JTextArea(text, 25, 25);
filler.setWrapStyleWord(true);
filler.setLineWrap(true);
JScrollPane scroll = new JScrollPane(filler);
//filler.setHorizontalAlignment(JTextArea.CENTER);
setLayout(new BorderLayout());
//panel.add(filler);
add(scroll);
}
}
}
If you continue to have issues, consider providing a minimal reproducible example, it takes out the guess work and generally results in better answers for more details

To add Scroller in JFrame which have JPanel Dynamic

I have two files, one is Main.java and the second is frame.java.
I'm creating a desktop application so I want to add scrollpane as needed vertically or horizontally in Main.java file.
Frame.java throws the JPanel object which is being catched by Main.java and dynamically loaded into JFrame.
So anyone please tell me, how can I add the scrollpane or scrollbar. Which is best, I don't know. Thank you..
Main.java:
package pack;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
JPanel pn = null;
JFrame mainFrame = null;
frame login = new frame();
mainFrame = new JFrame("Prem");
mainFrame.setLayout(new BorderLayout());
mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);
mainFrame.setSize(500,500);
mainFrame.setLocationRelativeTo(null);
pn=login.getLogin();
mainFrame.add(pn,BorderLayout.CENTER);
mainFrame.setVisible(true);
}
public Main() {
super();
}
}
This is second file which throws the panel object from method frame.java
package pack;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.AbstractAction;
import java.awt.*;
import java.awt.event.*;
public class frame {
JPanel pane = null,pane1=null;
JTextField userText=null,passText=null;
JLabel userLabel =null,passLabel=null,errorLabel=null;
JButton submitLogin = null;
public frame()
{
pane = new JPanel();
pane.setLayout(null);
}
public JPanel getLogin()
{
userLabel = new JLabel("UserName");
pane.add(userLabel);
userLabel.setBounds(5,10,100, 30);
userText = new JTextField();
pane.add(userText);
userText.setBounds(110,10,120,30);
passLabel = new JLabel("PassWord");
pane.add(passLabel);
passLabel.setBounds(5,60,100, 30);
passText = new JTextField();
pane.add(passText);
passText.setBounds(110,60,120,30);
errorLabel = new JLabel("");
pane.add(errorLabel);
errorLabel.setBounds(5,150,180,30);
submitLogin = new JButton("Submit");
pane.add(submitLogin);
submitLogin.setBounds(80,110,90,30);
submitLogin.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e)
{
if(submitLogin.getActionCommand() == "Submit")
{
if(userText.getText().isEmpty() || passText.getText().isEmpty())
{
errorLabel.setText("Enter UserName And Password");
}
else
{
//connection
}
}
else
{
System.exit(0);
}
}
});
return pane;
}
}
You have several issues with that code including:
You don't show us in your code where you're trying to use a JScrollPane or even where it's needed. If you show us your attempt to use this, we'll get a much better understanding of your problem.
You are using a null layout and setBounds(...), something you should avoid at almost all costs, and something which absolutely must be avoided if you want to use a JScrollPane, since JScrollPane's do not work well with null layouts. Instead read up on and use layout managers.
You're comparing Strings using the == operator. You don't want to compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.
You can find links to the Swing tutorials and other Swing resources here: Swing Info
You can find the layout manager tutorial here: Layout Manager Tutorial.
You can learn about "nesting" layouts here.
You can find specific information on how to use JScrollPanes here: JScrollPane Tutorial.
The basic use of them is that you will want to add your scrollable component to the JScrollPane's viewport, and then add the JScrollPane to the GUI. The specifics of how to do this will all depend on your needs, something we don't yet know, but again is very well explained in the tutorials that I've linked to above.

JPanel size not being set

I'm currently working on an irc bot and today I would like to create a GUI for it.
I'm trying to create a column layout that has two parts, left and right.
The left side will show console output, the right will contain all the controls (joining channels, commands etc).
I'm having issues creating the two columns. I have a JPanel that is the whole width and height of the window and has a border of 10 pixels, and then I have two panels within that; left and right.
The left and right panels are for some reason taking the whole size of the window, and the right panel is overlapping everything.
Here's an example picture: http://i.imgur.com/lc4vHVH.png
The white is the right panel, it should only be half the size and have an identical but black panel on the left of it.
Here's my current code, sorry if it's messy, new to the whole Swing GUI.. Thanks for any help.
package tk.TaylerKing.GribbyBot;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import com.alee.laf.WebLookAndFeel;
import com.alee.laf.menu.WebMenuBar;
import com.alee.laf.menu.WebMenuItem;
import com.alee.laf.panel.WebPanel;
import com.alee.laf.rootpane.WebFrame;
public class GribbyBot extends WebFrame {
private static final long serialVersionUID = 4641597667372956773L;
public static HashMap<String, ArrayList<String>> connections = new HashMap<String, ArrayList<String>>();
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(WebLookAndFeel.class.getCanonicalName());
SwingUtilities.invokeLater(new Runnable(){
public void run(){
GribbyBot gb = new GribbyBot();
gb.setVisible(true);
}
});
}
public GribbyBot(){
WebPanel panel = new WebPanel();
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.setPreferredSize(new Dimension(780, 580));
WebMenuBar menu = new WebMenuBar();
WebMenuItem file = new WebMenuItem("Exit");
file.setMnemonic(KeyEvent.VK_E);
file.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(file);
setJMenuBar(menu);
WebPanel left = new WebPanel();
left.setPreferredSize(new Dimension(380, 580));
left.setBackground(Color.BLACK);
WebPanel right = new WebPanel();
right.setPreferredSize(new Dimension(380, 580));
right.setBackground(Color.WHITE);
add(panel);
panel.add(left);
panel.add(right);
setTitle("GribbyBot");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
}
}
On a side note, all the variables that are prefixed with "Web" are the same as Swing, but it's a custom GUI.
Override JComponent#getPreferredSize() instead of using setPreferredSize()
Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
If extremely needed in case of Performing Custom Painting then try in this way:
Sample code:
final JPanel panel = new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
// your custom painting code here
}
#Override
public Dimension getPreferredSize() {
return new Dimension(40, 40);
}
};
Why are using setPreferredSize() method whereas you can achieve this design easily using any proper layout such as BoxLayout, GridLayout, BorderLayout etc.
Read more about layout How to Use Various Layout Managers
EDIT
try JPanel panel = new JPanel(new GridLayout(1,2));

Blank JFrame and No JPanel appeared but already added

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 ******
}

Java / Swing / WebcamCapture : When I disable a JLabel, an other image appears

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.)

Categories