VLCJ Equalizer work not correctly - vlcj

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

Related

Replace current JScrollPane to another JScrollPane in JPanel

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

ImageUri from Drawable Folder

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

GUI JFrame background color change

I've revisited this post. I have been able to upload the text file, create a GUI, populate the GUI with JRadioButtons that are labeled from the text file...
Now, I cannot get the background to change color when the JRadioButton is selected! I know that it has something to do with the ActionListener, but how do I fix this? The color needs to be implemented from the hex color code.
public class FP extends JFrame implements ActionListener {
TreeMap<String, String> buttonMap = new TreeMap <>();
// Constructor
#SuppressWarnings("empty-statement")
public FP() throws IOException {
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setBorder(new TitledBorder("Pick a Radio Button!"));
JRadioButton[] btnArray = new JRadioButton[20];
ButtonGroup btnGroup = new ButtonGroup();
BufferedReader reader;
reader = new BufferedReader(new FileReader("src/colors.txt"));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] pair = currentLine.split("\\s+");
buttonMap.put(pair[0],pair[1]);
currentLine = reader.readLine();
}
//check retrieving values from the buttonMap
for(Map.Entry<String,String> entry : buttonMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
for (int i = 0; i<20; i++){
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
JRadioButton rb = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(rb);
btnGroup.add(rb);
rb.addActionListener(this);
}
}
//private final JRadioButton btnMale = new JRadioButton("Male")
Collection bMapIt = buttonMap.entrySet();
Iterator it = bMapIt.iterator();
System.out.println("Colors and codes");
while(it.hasNext())
System.out.println(it.next());
}
#Override
public void actionPerformed(ActionEvent e) {
setBackground(Color.decode(buttonMap.get(e)));
}
public static void main(String[] args) throws IOException {
FP frame = new FP();
frame.setVisible(true);
frame.setSize(350, 240);
frame.setTitle("Final Project");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
for (int i = 0; i<1; i++){
btnArray[i] = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(btnArray[i]);
btnGroup.add(btnArray[i]);
btnArray[i].addActionListener((ActionEvent e) -> {
String btnColor = buttonMap.get(((JRadioButton) e.getSource()).getText());
String hexColor = entry.getValue();
System.out.println(hexColor);
panel.setBackground(Color.decode("#"+hexColor));
});
}
}
This with the addition of class....
#Override
public void actionPerformed(ActionEvent e) {}
}

could not resample from BGR24 to YUV420P in Xuggler

I'm trying convert sequantial images to video file.
But, this source makes error in encoding video.
public class Image2Video {
private static final double FRAME_RATE = 20;
private static final int SECONDS_TO_RUN_FOR = 20;
private static final String outputFilename = "C:/image/myVideo.mp4";
private static Dimension screenBounds;
private static Map<String, File> imageMap = new HashMap<String, File>();
public static void main(String[] args) {
final IMediaWriter writer = ToolFactory.makeWriter(outputFilename);
screenBounds = Toolkit.getDefaultToolkit().getScreenSize();
writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_MPEG4,screenBounds.width / 2, screenBounds.height / 2);
File folder = new File("C:/image");
File[] listOfFiles = folder.listFiles();
int indexVal = 0;
for (File file : listOfFiles) {
if (file.isFile()) {
indexVal++;
System.out.println("file.getName() :"+file.getName());
imageMap.put(file.getName(), file);
}
}
for (int index = 1; index <= listOfFiles.length; index++) {
BufferedImage screen = getImage(index);
BufferedImage bgrScreen = convertToType(screen, BufferedImage.TYPE_3BYTE_BGR);
writer.encodeVideo(0, bgrScreen, 300*index, TimeUnit.MILLISECONDS);
}
writer.close();
System.out.println("Video Created");
}
public static BufferedImage convertToType(BufferedImage sourceImage, int targetType) {
BufferedImage image;
if (sourceImage.getType() == targetType) {
image = sourceImage;
}
else {
image = new BufferedImage(sourceImage.getWidth(),
sourceImage.getHeight(), targetType);
image.getGraphics().drawImage(sourceImage, 0, 0, null);
}
return image;
}
private static BufferedImage getImage(int index) {
try {
String fileName=index+".jpeg";
System.out.println("fileName :" + fileName);
File img = imageMap.get(fileName);
BufferedImage in=null;
if (img != null) {
System.out.println("img :"+img.getName());
in = ImageIO.read(img);
}else
{
System.out.println("++++++++++++++++++++++++++++++++++++++index :" + index);
img = imageMap.get(1);
in = ImageIO.read(img);
}
return in;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
This is happening becz your images are not of the exact same width, height.
Try to run the program with images of similar dimensions, you can see that the problem goes away.
You could convert your images to same width/height before feeding them to this program.

Simple animation through use of paintComponent

I'm trying to make a small square move across the top of the panel. I'm not worried about the seamlessness of the animation or flicker or anything like that. It appears that in the while-loop, repaint() isn't repeatedly calling the paintComponent. Thoughts?
public class NodeMove extends JFrame {
boolean running = true;
public NodeMove() {
widgetNode panel = new widgetNode();
add(panel);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
Runnable node = new widgetNode();
Thread thread1 = new Thread(node);
thread1.start();
}
class widgetNode extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private int x = 30;
private int y = 30;
public widgetNode() {
}
public void run(){
while(running){
nodeUpdate();
repaint();
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
}
}
public void nodeUpdate(){
x += 4;
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawRect(x, y, 30, 30);
}
}
public static void main(String[] args) {
NodeMove frame = new NodeMove();
for(int i = 0; i < 50; i++){
frame.repaint();
}
}
}

Resources