Hy there.
I am trying to make a JPanel which reacts to certain events and plays a little animation. For example if I click on a button, it should flash red.(I need this to indicate when a file was successfully saved(green flash), or a error occurred(red flash).
I found some tutorials on animations, but I'm having a hard time changing it to fit my needs. For example most of the tutorials instantiate a Timer at the beginning. But I only need the timer to be active for that short amount of time where the flash is played and than stop. Also I need different animation types.(red flash, green flash...)
This is what I have got so far, which is basically nothing:
package MainPackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class StatusBar extends JPanel implements ActionListener{
Timer t = new Timer(10, this);
boolean stop = false;
Color color;
public void paintComponent (Graphics g) {
super.paintComponent(g);
setBackground(color);
}
public void confirm(){
color = new Color(46, 204, 113);
t.start();
}
public void warning(){
color = Color.red;
t.start();
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
Thanks in advance!
public class flashclass extends JFrame{
Thread th;
Color defaultColor, flashColor;
int i;
boolean success;
JPanel p;
public flashclass(){
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
success = false;
defaultColor = new Color(214,217,223);
p = new JPanel();
JButton rbtn = new JButton("Red flash");
JButton gbtn = new JButton("Green flash");
rbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
success = false;
flash(success);
}
});
gbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
success = true;
flash(success);
}
});
p.add(rbtn);
p.add(gbtn);
getContentPane().add(p);
}
public void flash(boolean success){
i=0;
if(!success){
flashColor = Color.red;
}
else{
flashColor = Color.green;
}
th = new Thread(new Runnable() {
#Override
public void run() {
while(i<10){
p.setBackground(flashColor);
i++;
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
p.setBackground(defaultColor);
}
}
});
th.start();
}
}
public static void main(String args[]){
new flashclass();
}
}
So here is the finished class:
New animations can be added easily. And they also do not interfere with each other. So multiple states can be triggered simultaneously.
The StatusBar.java
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JComponent;
import javax.swing.Timer;
public class StatusBar extends JComponent implements ActionListener{
int width;
int height;
boolean bLoad, bWarn, bConfirm, bError;
Timer timer;
Color bgColor;
int xPosLoad, alphaWarn, alphaConfirm, alphaError;
float cntWarn, cntConfirm, cntError;
int cntLoad;
final int barLength = 200;
public StatusBar(Color bg){
width = getWidth();
height = getHeight();
xPosLoad = -barLength;
alphaWarn = 0;
alphaConfirm = 0;
alphaError = 0;
bgColor = bg;
timer = new Timer(10, this);
this.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent event) {
width = getWidth();
height = getHeight();
}
});
}
#Override
protected void paintComponent(Graphics g) {
// Background
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
// loading
Graphics2D g2d = (Graphics2D)g;
GradientPaint gp = new GradientPaint(xPosLoad,0, new Color(0,0,0,0), xPosLoad+barLength, 0, new Color(200, 200, 255));
g2d.setPaint(gp);
g2d.fillRect(xPosLoad, 0, barLength, height);
// Green
g.setColor(new Color(20, 210, 60, alphaConfirm));
g.fillRect(0, 0, width, height);
// Yellow
g.setColor(new Color(255, 223, 0, alphaWarn));
g.fillRect(0, 0, width, height);
// Red
g.setColor(new Color(255, 0, 0, alphaError));
g.fillRect(0, 0, width, height);
}
#Override
public void actionPerformed(ActionEvent e) {
// step increase for all active components
boolean toggle = false;
if (bConfirm){
if(cntConfirm < 1){
cntConfirm += 0.01f;
alphaConfirm = lerp(cntConfirm, 255, true);
}else{
bConfirm = false;
cntConfirm = 0;
alphaConfirm = 0;
}
toggle = true;
}
if (bWarn){
if(cntWarn < 1){
cntWarn += 0.01f;
alphaWarn = lerp(cntWarn, 255, true);
}else{
bWarn = false;
cntWarn = 0;
alphaWarn = 0;
}
toggle = true;
}
if (bError){
if(cntError < 1){
cntError += 0.01f;
alphaError = lerp(cntError, 255, true);
}else{
bError = false;
cntError = 0;
alphaError = 0;
}
toggle = true;
}
if (bLoad){
if(cntLoad < 100){
cntLoad += 1;
xPosLoad = (cntLoad * (width + barLength)) / 100 - barLength;
}else{
cntLoad = 0;
xPosLoad = -barLength;
}
toggle = true;
}
repaint();
if (!toggle){
timer.stop();
}
}
private void startTimer(){
if (!timer.isRunning())
timer.start();
}
public void setBG(Color bg){
bgColor = bg;
System.out.println("Color: " + bgColor);
repaint();
}
// Green flash
public void confirm(){
// set values
bConfirm = true;
alphaConfirm = 255;
cntConfirm = 0;
startTimer();
}
//Yellow flash
public void warning(){
// restart values
bWarn = true;
alphaWarn = 255;
cntWarn = 0;
startTimer();
}
//Red Flash
public void error(){
// restart values
bError = true;
alphaError = 255;
cntError = 0;
startTimer();
}
//Blue load
public void loadStart(){
// restart values
bLoad = true;
xPosLoad = -barLength;
cntLoad = 0;
startTimer();
}
public void loadEnd(){
bLoad = false;
xPosLoad = -barLength;
}
private int lerp(float progress, int max, boolean inverse){
float x = progress;
float x2 = (float) Math.pow(x, 4);
float g = x + (1 - x);
float y = (float) ((float) x2 / (float)(Math.pow(g, 4)));
y = Math.min(y, 1);
y = Math.max(y, 0);
int res = (int) (y * max);
if (inverse){
res = max - res;
}
return res;
}
}
And the Example.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example extends JFrame{
public static void main(String[] args){
new Example("Stat Example");
}
public Example(String title){
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StatusBar stat = new StatusBar(Color.black);
stat.setPreferredSize(new Dimension(0, 10));
JPanel panel = new JPanel();
JButton bConfirm = new JButton("Confirm");
JButton bWarn = new JButton("Warning");
JButton bErr = new JButton("Error");
JButton bLoadS = new JButton("Start Loading");
JButton bLoadE = new JButton("End Loading");
panel.add(bConfirm);
panel.add(bWarn);
panel.add(bErr);
panel.add(bLoadS);
panel.add(bLoadE);
this.getContentPane().add(stat, BorderLayout.CENTER);
this.getContentPane().add(panel, BorderLayout.SOUTH);
this.pack();
this.setVisible(true);
// Listener
bConfirm.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.confirm();
}
});
bWarn.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.warning();
}
});
bErr.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.error();
}
});
bLoadS.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.loadStart();
}
});
bLoadE.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
stat.loadEnd();
}
});
}
}
Related
how can change this link code to Xamarin
or find another way to load an image with loading progress in Xamarin
I solved It
pic
public class MhnImgview:ImageView{public string Url;
private Context _context;
int mDuration;
int mProgress;
Paint mPaint = new Paint();
RectF mRectF = new RectF();
Color mBackgroundColor;
Color mPrimaryColor;
float mStrokeWidth;
public IOnProgressChangeListener MOnChangeListener; public interface IOnProgressChangeListener
{
void OnChange(int duration, int progress, float rate);
}
public void SetOnProgressChangeListener(IOnProgressChangeListener l)
{
MOnChangeListener = l;
}
protected MhnImgview(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public MhnImgview(Context context) : base(context)
{
}
public void SetMax(int max)
{
if (max < 0)
{
max = 0;
}
mDuration = max;
}
public int GetMax()
{
return mDuration;
}
public void SetProgress(int progress)
{
if (progress > mDuration)
{
progress = mDuration;
}
mProgress = progress;
MOnChangeListener?.OnChange(mDuration, progress, GetRateOfProgress());
Invalidate();
}
public int GetProgress()
{
return mProgress;
}
public void SetBackgroundColr(Color color)
{
mBackgroundColor = color;
}
public void SetPrimaryColor(Color color)
{
mPrimaryColor = color;
}
float GetRateOfProgress()
{
return (float)mProgress / mDuration;
}
public void SetCircleWidth(float width)
{
mStrokeWidth = width;
}
public async Task ShowImage()
{
var d = await GetImageBitmapFromUrl(Url);
SetImageBitmap(d);
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
int halfWidth = Width / 2;
int halfHeight = Height / 2;
int radius = halfWidth < halfHeight ? halfWidth : halfHeight;
radius = radius / 2;
float halfStrokeWidth = mStrokeWidth / 2;
mPaint.Color = mBackgroundColor;
mPaint.Dither = true;
mPaint.Flags = PaintFlags.AntiAlias;
mPaint.AntiAlias = true;
mPaint.StrokeWidth = mStrokeWidth;
mPaint.SetStyle(Paint.Style.Stroke);
canvas.DrawCircle(halfWidth, halfHeight, radius - halfStrokeWidth, mPaint);
mPaint.Color = mPrimaryColor;
mRectF.Top = halfHeight - radius + halfStrokeWidth;
mRectF.Bottom = halfHeight + radius - halfStrokeWidth;
mRectF.Left = halfWidth - radius + halfStrokeWidth;
mRectF.Right = halfWidth + radius - halfStrokeWidth;
canvas.DrawArc(mRectF, -90, GetRateOfProgress() * 360, false, mPaint);
canvas.Save();
}
private async Task<Bitmap> GetImageBitmapFromUrl(string imagename)
{
Bitmap imageBitmap = null;
var baseurl = imagename;
try
{
var url = baseurl;
using (var webClient = new WebClient())
{
webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
var imageBytes = await webClient.DownloadDataTaskAsync(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
catch (Exception ex)
{
var d = ex.Message;
}
return null;
}
private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
SetMax(100);
SetBackgroundColr(Color.Rgb(44,59,76));
SetPrimaryColor(Color.Rgb(236,104,88));
SetCircleWidth(7.5f);
SetProgress(e.ProgressPercentage);
}
public MhnImgview(Context context, IAttributeSet attrs) : base(context, attrs)
{
}
public MhnImgview(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
{
}
public MhnImgview(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes)
{
}
}
for use it
var img = FindViewById<MhnImgview>(Resource.Id.imgmhn);
img.Url = "http://www.neyrizcement.com/upload/3rcqesmc.jpg";
await img.ShowImage();
I would like to change my current JScrollpane to a new one. I would like it to change after I pressed my button and the method actionPerformed is called.
The problem I currently have is that it only paints the Jscroll at the beginning of the application, when i want to change it, it dosent work.(When the application is running).
What I do is:
In the beginning of the application I make a new JscrollPane and this one is empty. If the button is pressed: Show another JscrollPane with content.
if(btnPressed == true){
//set current empty jscroll pane to a filled one.
jscrollpane = View.createScrollPlane();
//View.createScrollPlane = This method fills the JscrollPane with text.
}
else { //show a empty one
jscrollpane = new JscrollPane();
}
I have tried:
- remove
- add
- revalidate
- repaint
And also:
JscrollPane.setViewPortView(JscrollPane);
I've looked to CardLayout but I would rather not and it dosent allow me since only empty containers can be changed to CardLayout. Currently its on GridBagLayout.
Thanks in advance
RE-edit: the Create-UI method dosent change the current empty Jscrollpanel to the new one. It only initialise it once (at the beginning) but dosent update the Jscroll panel. (when i tried to put it on false) it worked, the boolean did change to true but dosent update the jscroll panel.
package readDataPluginPackage;
import com.change_vision.jude.api.inf.AstahAPI;
import com.change_vision.jude.api.inf.project.ProjectAccessor;
import javafx.embed.swing.JFXPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
public class Application {
JPanel mainJPanel;
private JPanel leftJPanel;
private JPanel rightJPanel;
private JButton btnSynchronise;
private JButton btnPreview;
private JScrollPane JScrollPaneReport;
public JScrollPane JScrollPanePreview;
private boolean btnPreviewClicked = false;
public Application() {
$$$setupUI$$$();
btnPreview.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btnPreviewClicked = true;
JOptionPane.showMessageDialog(null, "Showing..." + btnPreviewClicked);
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
// if (btnPreview.isEnabled()) {
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
JOptionPane.showMessageDialog(null, "XML File Preview has been updated.");
createUIComponents();
// JScrollPanePreview.revalidate();
// JScrollPanePreview.repaint();
JOptionPane.showMessageDialog(null, "Components are created again.");
}
// }
});
btnSynchronise.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Synchronising...");
}
});
}
public static void main(String[] args) {
try {
//Save Astah Project as XML File
ProjectAccessor prjAccessor = AstahAPI.getAstahAPI().getProjectAccessor();
prjAccessor.open("C:\\Users\\delina\\generated\\test.asta");
prjAccessor.exportXMI("C:\\Users\\delina\\generatedXMI\\temp.xml");
prjAccessor.close();
//Show the most recent version of the xml file of the Astah Project
ReadXMLFile rd = new ReadXMLFile();
rd.showXMLFileLines();
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Application");
frame.setContentPane(new Application().mainJPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void createUIComponents() {
if (btnPreviewClicked == true) {
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
// JScrollPanePreview.setViewportView(JScrollPanePreview);
leftJPanel.remove(JScrollPanePreview);
ShowXMLFileView showXMLFileView = new ShowXMLFileView();
JScrollPane JScrollPanePreview = showXMLFileView.createLabelPane();
leftJPanel.add(JScrollPanePreview);
JScrollPanePreview.revalidate();
JScrollPanePreview.repaint();
JOptionPane.showMessageDialog(null, "JScrollPanel changed");
} else {
JScrollPanePreview = new JScrollPane();
}
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* #noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
mainJPanel = new JPanel();
mainJPanel.setLayout(new GridBagLayout());
leftJPanel = new JPanel();
leftJPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainJPanel.add(leftJPanel, gbc);
btnSynchronise = new JButton();
btnSynchronise.setText("Synchronise");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
leftJPanel.add(btnSynchronise, gbc);
btnPreview = new JButton();
btnPreview.setText("Preview");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
leftJPanel.add(btnPreview, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
leftJPanel.add(JScrollPanePreview, gbc);
JScrollPanePreview.setBorder(BorderFactory.createTitledBorder("XML File Preview"));
rightJPanel = new JPanel();
rightJPanel.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainJPanel.add(rightJPanel, gbc);
JScrollPaneReport = new JScrollPane();
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
rightJPanel.add(JScrollPaneReport, gbc);
JScrollPaneReport.setBorder(BorderFactory.createTitledBorder("Synchronise report"));
}
/**
* #noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return mainJPanel;
}
}
package readDataPluginPackage;
import com.change_vision.jude.api.inf.project.ProjectAccessor;
import com.change_vision.jude.api.inf.project.ProjectAccessorFactory;
import com.change_vision.jude.api.inf.project.ProjectEvent;
import com.change_vision.jude.api.inf.project.ProjectEventListener;
import com.change_vision.jude.api.inf.ui.IPluginExtraTabView;
import com.change_vision.jude.api.inf.ui.ISelectionListener;
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ShowUserInterface extends JPanel implements IPluginExtraTabView, ProjectEventListener {
public ShowUserInterface() {
initComponents();
}
private void initComponents() {
setLayout(new BorderLayout());
add(createLabelPane());
addProjectEventListener();
}
private void addProjectEventListener() {
try {
ProjectAccessor projectAccessor = ProjectAccessorFactory.getProjectAccessor();
projectAccessor.addProjectEventListener(this);
} catch (ClassNotFoundException e) {
e.getMessage();
}
}
private Container createLabelPane() {
JLabel label = new JLabel("AuguSoft Synchronise");
JScrollPane pane = new JScrollPane(label);
Method privateMethod = null;
Application app = null;
Object o = null;
JComponent jComponent = null;
try {
app = new Application();
privateMethod = Application.class.getDeclaredMethod("$$$setupUI$$$");
privateMethod.setAccessible(true);
o = privateMethod.invoke(app);
jComponent = app.$$$getRootComponent$$$();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return jComponent;
}
#Override
public void projectChanged(ProjectEvent e) {
}
#Override
public void projectClosed(ProjectEvent e) {
}
#Override
public void projectOpened(ProjectEvent e) {
}
#Override
public void addSelectionListener(ISelectionListener listener) {
}
#Override
public Component getComponent() {
return this;
}
#Override
public String getDescription() {
return "Show AuguSoft Synchronise here";
}
#Override
public String getTitle() {
return "AuguSoft View";
}
public void activated() {
}
public void deactivated() {
}
}
So, with doing nothing else but looking at you code, I noticed that in your createUIComponents method, you are shadowing the JScrollPanePreview property...
public class Application {
//...
public JScrollPane JScrollPanePreview;
//...
public Application() {..}
private void createUIComponents() {
if (btnPreviewClicked == true) {
//...
leftJPanel.remove(JScrollPanePreview);
ShowXMLFileView showXMLFileView = new ShowXMLFileView();
JScrollPane JScrollPanePreview = showXMLFileView.createLabelPane();
//...
} else {
JScrollPanePreview = new JScrollPane();
}
}
This means that the next time you come to replace the JScrollPanePreview, you won't have the correct reference to remove it.
To my mind (and I don't have you full code base or intention), I'd simply replace the JScrollPanePreview view port (besides, I'm not sure how you can assign a Container to a JScrollPane anyway :P)
private void createUIComponents() {
if (btnPreviewClicked == true) {
JScrollPanePreview.setViewportView(showXMLFileView.createLabelPane());
} else {
JScrollPanePreview = new JScrollPane();
}
}
Just as an observation ;)
I have been following this tutorial to learn how to implement Pinch Zoom and Pan capabilities into an app I am developing.
https://www.youtube.com/watch?v=BY8hLhu50po&list=PL9jCwTXYWjDJjDE_JxRozYGKGt8gbUXg7
Basically, he loads an image from the gallery and displays it in an image view that supports Zoom/Pan functionality.
I would like to preload an image into the image view rather than select one from the gallery. Ideally, I'd like to load an image from drawable.
The tutorial's app had a lot of extra features that I am trying to weed out.
First it opens a gallery. Then you select an image to display, and it displays it as a thumbnail inside of mImageView.
On Long Click, it hides mImageView and displays a maximized image inside of a second Image View. (MPinchZoomImageView)
At this point, the image supports zoom and pan functionality.
If I could, I'd like to skip the gallery and the first Image View and only use the PinchZoom Image View. I'm not sure how I'd do that.
Code:
ImageViewMainActivity
public class ImageViewMainActivity extends AppCompatActivity {
ImageView mImageView;
PinchZoomImageView mPinchZoomImageView;
private Uri mImageUri;
private static final int REQUEST_OPEN_RESULT_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_view_main);
mImageView = (ImageView) findViewById(R.id.imageView);
mPinchZoomImageView = (PinchZoomImageView) findViewById(R.id.pinchZoomImageView);
mImageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
pinchZoomPan();
return true;
}
});
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_OPEN_RESULT_CODE); // pass it a context of 0
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
View decorView = getWindow().getDecorView();
if(hasFocus) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if(requestCode == REQUEST_OPEN_RESULT_CODE && resultCode == RESULT_OK) {
if(resultData != null) {
mImageUri = resultData.getData();
Glide.with(this)
.load(mImageUri)
.into(mImageView);
}
}
}
private void pinchZoomPan() {
mPinchZoomImageView.setImageUri(mImageUri);
mImageView.setAlpha(0.f); // set mImageView invisible.
mPinchZoomImageView.setVisibility(View.VISIBLE);
}
}
PinchZoomImageView
public class PinchZoomImageView extends ImageView {
private Bitmap mBitmap;
private int mImageWidth;
private int mImageHeight;
private final static float mMinZoom = 1.f;
private final static float mMaxZoom = 4.f;
private float mScaleFactor = 1.f;
private ScaleGestureDetector mScaleGestureDetector;
private final static int NONE = 0;
private final static int PAN = 1;
private final static int ZOOM = 2;
private int mEventState;
private float mStartX = 0;
private float mStartY = 0;
private float mTranslateX = 0;
private float mTranslateY = 0;
private float mPreviousTranslateX = 0;
private float mPreviousTranslateY = 0;
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(mMinZoom, Math.min(mMaxZoom, mScaleFactor));
// invalidate();
// requestLayout();
return super.onScale(detector);
}
}
public PinchZoomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mScaleGestureDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mEventState = PAN;
mStartX = event.getX() - mPreviousTranslateX;
mStartY = event.getY() - mPreviousTranslateY;
break;
case MotionEvent.ACTION_UP:
mEventState = NONE;
mPreviousTranslateX = mTranslateX;
mPreviousTranslateY = mTranslateY;
break;
case MotionEvent.ACTION_MOVE:
mTranslateX = event.getX() - mStartX;
mTranslateY = event.getY() - mStartY;
break;
case MotionEvent.ACTION_POINTER_DOWN:
mEventState = ZOOM;
break;
}
mScaleGestureDetector.onTouchEvent(event);
if((mEventState == PAN && mScaleFactor != mMinZoom) || mEventState == ZOOM) { // called under the condition that window is zoomed i
invalidate();
requestLayout();
}
return true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int imageWidth = MeasureSpec.getSize(widthMeasureSpec);
int imageHeight = MeasureSpec.getSize(heightMeasureSpec);
int scaledWidth = Math.round(mImageWidth * mScaleFactor);
int scaledHeight = Math.round(mImageHeight * mScaleFactor);
setMeasuredDimension(
Math.min(imageWidth, scaledWidth),
Math.min(imageHeight, scaledHeight)
);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor);
// canvas.scale(mScaleFactor, mScaleFactor, mScaleGestureDetector.getFocusX(), mScaleGestureDetector.getFocusY());
if((mTranslateX * -1) < 0) {
mTranslateX = 0;
} else if ((mTranslateX * -1) > mImageWidth * mScaleFactor - getWidth()) {
mTranslateX = (mImageWidth * mScaleFactor - getWidth()) * -1;
}
if((mTranslateY * -1) < 0) {
mTranslateY = 0;
} else if ((mTranslateY * -1) > mImageHeight * mScaleFactor - getHeight()) {
mTranslateY = (mImageHeight * mScaleFactor - getHeight()) * -1;
}
canvas.translate(mTranslateX/mScaleFactor, mTranslateY/mScaleFactor);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.restore();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
public void setImageUri(Uri uri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
float aspecRatio = (float) bitmap.getHeight() / (float) bitmap.getWidth();
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
mImageWidth = displayMetrics.widthPixels;
mImageHeight = Math.round(mImageWidth * aspecRatio);
mBitmap = Bitmap.createScaledBitmap(bitmap, mImageWidth, mImageHeight, false);
invalidate();
requestLayout();
} catch (IOException e) {
e.printStackTrace();
}
}
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mobapptut.com.imageviewer.ImageViewMainActivity">
<ImageView
android:layout_width="200dp"
android:layout_height="150dp"
android:id="#+id/imageView"
android:layout_centerInParent="true" />
<mobapptut.com.imageviewer.PinchZoomImageView
android:visibility="invisible"
android:id="#+id/pinchZoomImageView"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Thank You
i use VLCJ 3.0.1, Plattform 3.5.2 and JNA 3.5.2 under Ubuntu 14.10.
I would like to create a simple Vlcj Mediaplayer with equalizer.
The problem is, i can play the *.mp3, but when i enable the equalizer and change the gain from any band, i can hear that gain from the band up to max high. I couldn't change it to lower gain. No effect from the Slider. Only when i change the gain to max or min, the effekt is off.
Here is the Code only for testing:
FesterTest.java
public static void main(String[] args) {
Canvas m_surface;
EmbeddedMediaPlayer m_mediaPlayer;
Equalizer m_equalizer;
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
m_surface = new Canvas();
m_surface.setBackground(Color.black);
m_surface.setBounds(0, 0, 1024, 600);
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
m_mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
m_mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(m_surface));
System.out.println(mediaPlayerFactory.isEqualizerAvailable());
m_equalizer = mediaPlayerFactory.newEqualizer();
System.out.println(LibVlcConst.MAX_GAIN);
System.out.println(LibVlcConst.MIN_GAIN);
System.out.println(LibVlcConst.MIN_VOLUME);
System.out.println(LibVlcConst.MAX_VOLUME);
JFrame f = new JFrame();
JPanel p = new JPanel();
f.add(p);
p.add(m_surface);
f.setVisible(true);
m_mediaPlayer.playMedia("/home/patrick/Dev/content/068-becky_g_-_shower.mp3");
EqualizerFrame frame = new EqualizerFrame(mediaPlayerFactory.getEqualizerBandFrequencies(), mediaPlayerFactory.getEqualizerPresetNames(), mediaPlayerFactory, m_mediaPlayer, m_equalizer);
frame.pack();
frame.setVisible(true);
}
and EqualizerFrame:
public class EqualizerFrame extends JFrame implements ChangeListener, ActionListener, ItemListener {
private static final String BAND_INDEX_PROPERTY = "equalizerBandIndex";
private final String dbFormat = "%.2fdB";
private final MediaPlayerFactory mediaPlayerFactory;
private final MediaPlayer mediaPlayer;
private final Equalizer equalizer;
private final SliderControl preampControl;
private final SliderControl[] bandControls;
private final JToggleButton enableButton;
private final JComboBox presetComboBox;
#SuppressWarnings({ "unchecked", "rawtypes" })
public EqualizerFrame(List<Float> list, List<String> presets, MediaPlayerFactory mediaPlayerFactory, MediaPlayer mediaPlayer, Equalizer equalizer) {
super("Equalizer");
this.mediaPlayerFactory = mediaPlayerFactory;
this.mediaPlayer = mediaPlayer;
this.equalizer = equalizer;
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
contentPane.setLayout(new BorderLayout(0, 4));
JPanel bandsPane = new JPanel();
bandsPane.setLayout(new GridLayout(1, 1 + list.size(), 2, 0));
preampControl = new SliderControl("Preamp", (int)LibVlcConst.MIN_GAIN, (int)LibVlcConst.MAX_GAIN, 0, dbFormat);
preampControl.getSlider().addChangeListener(this);
bandsPane.add(preampControl);
bandControls = new SliderControl[list.size()];
for(int i = 0; i < list.size(); i++) {
bandControls[i] = new SliderControl(formatFrequency(list.get(i)), (int)LibVlcConst.MIN_GAIN, (int)LibVlcConst.MAX_GAIN, 0, dbFormat);
bandControls[i].getSlider().putClientProperty(BAND_INDEX_PROPERTY, i);
bandControls[i].getSlider().addChangeListener(this);
bandsPane.add(bandControls[i]);
}
contentPane.add(bandsPane, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
controlsPane.setLayout(new BoxLayout(controlsPane, BoxLayout.X_AXIS));
enableButton = new JToggleButton("Enable");
enableButton.setMnemonic('e');
controlsPane.add(enableButton);
controlsPane.add(Box.createHorizontalGlue());
JLabel presetLabel = new JLabel("Preset:");
presetLabel.setDisplayedMnemonic('p');
controlsPane.add(presetLabel);
presetComboBox = new JComboBox();
presetLabel.setLabelFor(presetComboBox);
DefaultComboBoxModel presetModel = (DefaultComboBoxModel)presetComboBox.getModel();
presetModel.addElement(null);
for(String presetName : presets) {
presetModel.addElement(presetName);
}
presetComboBox.setRenderer(new DefaultListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(value != null) {
label.setText(String.valueOf(value));
}
else {
label.setText("--Select--");
}
return label;
}
});
controlsPane.add(presetComboBox);
contentPane.add(controlsPane, BorderLayout.SOUTH);
setContentPane(contentPane);
enableButton.addActionListener(this);
presetComboBox.addItemListener(this);
}
private String formatFrequency(float hz) {
if(hz < 1000.0f) {
return String.format("%.0f Hz", hz);
}
else {
return String.format("%.0f kHz", hz / 1000f);
}
}
#Override
public final void actionPerformed(ActionEvent e) {
boolean enable = enableButton.isSelected();
if(!enable) {
presetComboBox.setSelectedItem(null);
}
mediaPlayer.setEqualizer(enable ? equalizer : null);
}
#Override
public void stateChanged(ChangeEvent e) {
if(e.getSource() instanceof JSlider) {
JSlider slider = (JSlider)e.getSource();
Integer index = (Integer)slider.getClientProperty(BAND_INDEX_PROPERTY);
int value = slider.getValue();
// Band...
if(index != null) {
equalizer.setAmp(index, (value / 100f));
}
// Preamp...
else {
equalizer.setPreamp(value / 100f);
}
if(!applyingPreset) {
presetComboBox.setSelectedItem(null);
}
}
}
boolean applyingPreset;
#Override
public final void itemStateChanged(ItemEvent e) {
String presetName = (String)presetComboBox.getSelectedItem();
if(e.getStateChange() == ItemEvent.SELECTED) {
if(presetName != null) {
Equalizer presetEqualizer = mediaPlayerFactory.newEqualizer(presetName);
if(presetEqualizer != null) {
applyingPreset = true;
preampControl.getSlider().setValue((int)(presetEqualizer.getPreamp() * 100f)); // FIXME
float[] amps = presetEqualizer.getAmps();
for(int i = 0; i < amps.length; i++) {
bandControls[i].getSlider().setValue((int)(amps[i] * 100f));
}
applyingPreset = false;
}
}
}
}
}
I don't know what can i do an hope anybody can help me!!!!
Thanks
Patrick
For some reason you just keep moving left and I can't figure out why. The keyboard input reading isn't the problem because moving in any other direction works perfectly. Ignore the isClipped() method as I'm not done with it yet. Thanks for the help.
main class
package Genisis;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.*;
import org.newdawn.slick.state.*;
import org.newdawn.slick.tiled.TiledMap;
public class Play extends BasicGameState
{
int mouseX;
int mouseY;
Level testLevel;
boolean[][] blocked;
MainCharacter mc;
public Play(int state)
{
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException
{
gc.setMouseCursor("res/sprites/Cursor.png", 0, 0);
try {
testLevel = new Level(0, 0, "res/maps/testmap.tmx");
} catch (FileNotFoundException e) {
System.out.println("Failed to load map.");
e.printStackTrace();
}
mouseX = Mouse.getX();
mouseY = gc.getHeight() - Mouse.getY();
mc = new MainCharacter(50, 50, new Image("res/sprites/mcg.png"));
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws
SlickException
{
testLevel.render(mc.x, mc.y);
mc.render(mouseX, mouseY);
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws
SlickException
{
mc.move(gc, testLevel);
mc.render(gc.getWidth()/2, gc.getHeight()/2);
testLevel.render(mc.x, mc.y);
}
public int getID()
{
return 1;
}
public void spawnMC(float spwnMCX, float spwnMCY)
{
testLevel.render(spwnMCX, spwnMCY);
testLevel.render(spwnMCX, spwnMCY);
}
public void spawnOC()
{
//todo
}
}
Player class
package Genisis;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
public class MainCharacter extends Player
{
public MainCharacter(float newX, float newY, Image newSprite) throws SlickException
{
sprite = newSprite;
x = newX;
y = newY;
}
public void move(GameContainer gc, Level map)
{
Input in = gc.getInput();
if(in.isKeyDown(Input.KEY_W))
if(map.isClipped(x, y + 1))
y += 1;
if(in.isKeyDown(Input.KEY_D))
if(map.isClipped(x + 1, y))
x -= 1;
if(in.isKeyDown(Input.KEY_S))
if(map.isClipped(x, y - 1))
y -= 1;
if(in.isKeyDown(Input.KEY_A));
if(map.isClipped(x - 1, y))
x += 1;
}
public void render(float mX, float mY)
{
float xDist = mX - (500 + (sprite.getWidth() / 2));
float yDist = mY - (250 + (sprite.getHeight() / 2));
double angleToTurn = Math.toDegrees(Math.atan2(yDist, xDist));
sprite.setRotation((float)angleToTurn);
sprite.draw(500, 250);
}
}
level class
package Genisis;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;
import org.newdawn.slick.tiled.TiledMap;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Level
{
//height of background (in tiles)
public int height;
//width of background (in tiles)
public int width;
public boolean[][] clipped;
public TiledMap map;
public Level(int newHeight, int newWidth, String path) throws
FileNotFoundException, SlickException
{
map = new TiledMap(path);
clipped = new boolean[map.getHeight()][map.getWidth()];
for(int i = 0; i < map.getHeight(); i++)
for(int j = 0; i < map.getWidth(); i++)
{
if("true".equals(map.getTileProperty(map.getTileId(i, j,
0), "blocked", "false")))
clipped[i][j] = false;
}
}
//render map
public void render(float mcX, float mcY)
{
map.render((int)(mcX), (int)(mcY));
}
//return height of level (in pixels)
public int getHeight()
{
return map.getHeight();
}
//return width of level (in pixels)
public int getWidth()
{
return map.getWidth();
}
public boolean isClipped(float charX, float charY)
{
//return clipped[(int)(charX / 50)][(int)(charY / 50)];
return true;
}
}
Found the problem. There is an extra semicolon (it's always a semicolon -_-) after the if statement for moving left.
if(in.isKeyDown(Input.KEY_A));
if(map.isClipped(x - 1, y))
x += 1;