GUI JFrame background color change - user-interface

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) {}
}

Related

Okhttp parse and recyclerview fragment?

I've a issue on using a list_state out of the Okhttp, when I try to pass it in adapter it result empty.
I can't understand because all variables used inside onResponse do not be passed outside of it.
I've tried to set a recyclerview and adapter inside onResponse but got and error on it and ap crash.
The code I've used is below anyone can help me?.
Sorry for my English.
public class dashboard_device extends Fragment implements ListOwner{
RecyclerView mRecicleView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
ArrayList<String> lista_show;
ArrayList<String> lista_state = new ArrayList<String> ();
ArrayList<String> lista_prestate = new ArrayList<String> ();
String p,d;
String myResponse = null;
List<risposta_json> posts;
public dashboard_device() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate (R.layout.dashboard_device_layout, container, false);
final ArrayList<String> lista_show = new ArrayList<String> ();
dashboard_DB db1 = new dashboard_DB (getContext ());
//recupero datbase DB
db1.open();
Cursor c = db1.ottieniTuttidati();
if (c.moveToFirst()) {
do {
lista_show.add (c.getString(2));
} while (c.moveToNext());
}
db1.close();
//fine recupero dati da db
// Inflate the layout for this fragment
GestioneDB db = new GestioneDB(getContext ());
db.open();
Cursor c1 = db.ottieniTuttidati();
if (c1.moveToFirst()) {
do {
p = c1.getString(1);
d = c1.getString(2);
} while (c1.moveToNext());
}
db.close();
//fine recupero dati da db
final String url = p;
String token=d;
OkHttpClient client = new OkHttpClient ();
Request request = new Request.Builder()
.url("https://"+url+"/api/states")
.addHeader("Authorization", "Bearer " + token)
.build();
client.newCall(request).enqueue(new Callback () {
#Override
public void onFailure(Call call, IOException e) {e.printStackTrace();}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
myResponse = response.body().string();
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
String jsonOutput = myResponse;
Type listType = new TypeToken<List<risposta_json>> (){}.getType();
posts = gson.fromJson(jsonOutput, listType);
// Log.d("MYRESPONSE", String.valueOf (myResponse));
//attributes = gson.fromJson (myResponse, risposta_json.class);
for (int i = 0; i<lista_show.size (); i++) {
for (int l = 0; l<posts.size ();l++) {
if (posts.get (l).getAttributes ().getFriendly_name ()!=null && posts.get (l).getAttributes ().getFriendly_name ().equalsIgnoreCase (lista_show.get (i))) {
lista_state.add (posts.get (l).getState ());
}
}
}
}
}
});
Log.d("STATI", String.valueOf (lista_state));
mRecicleView = container.findViewById (R.id.Reclycler_View);
mRecicleView.setHasFixedSize (true);
mLayoutManager = new GridLayoutManager (getContext (),3);
mAdapter = new adapter_dash (lista_show,lista_state, getContext (),dashboard_device.this);
mRecicleView.setLayoutManager (mLayoutManager);
mRecicleView.setAdapter (mAdapter);
runanimation1(mRecicleView,0);
Log.d("LISTA SHOW", String.valueOf (lista_show));
return fragmentView;
}
private void runanimation1(RecyclerView mRecicleView, int type) {
Context context=mRecicleView.getContext ();
LayoutAnimationController controller = null;
if(type==0)
controller = AnimationUtils.loadLayoutAnimation (context,R.anim.layout_animation);
mRecicleView.setLayoutAnimation (controller);
mRecicleView.getAdapter ().notifyDataSetChanged ();
mRecicleView.scheduleLayoutAnimation ();
}
#Override
public void push(ArrayList<String> list) {
}
}
Solved using
.getactivity().runOnUiThread (new Runnable) ect.... Ect...

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

It takes a long time to load large data in recyclerview

I have 11 text files each containing 50-60 lines. I have read all the files and showed in the recyclerview. I used asynctask to track the progress through the progress bar. I have used log too to see the read lines. I have found that reading is taking short time but after reading, it takes 5-6 seconds to show data in the recyclerview. Why is this causing? What should i do to handle this? Why should i do if there are thousands of text files?
Codes reading files and binding
AsyncTask<Void,Void,Void> task = new AsyncTask<Void, Void, Void>() {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(GrammerDetails.this,
"Loading", "Please Wait for a while");
}
#Override
protected Void doInBackground(Void... voids) {
getFromFilesbagdhara(id,realm);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("first_bagdhara",false);
editor.apply();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
inflateData(listGrammerItem);
progressDialog.dismiss();
}
}.execute();
private void getFromFilesbagdhara(String id, Realm realm) {
String directory = "Grammer/Bagdhara";
AssetManager man = getAssets();
BufferedReader reader = null;
try {
String[] files = man.list(directory);
for (int i =0;i<files.length;i++){
String fileName = files[i];
reader = new BufferedReader(
new InputStreamReader(getAssets().open(directory+"/" + fileName),
"UTF-8"));
String line;
Log.e("File",files[i]);
while ((line = reader.readLine()) != null) {
Log.e("line",line);
// String[] text = line.split(" ");
String a = line.substring(0,line.indexOf("(")-1);
String b = line.substring(line.indexOf("(")+1,line.indexOf(")"));
String wordOne = a;
// String dummyTwo = text[1];
String wordTwo = b; //dummyTwo.substring(1,dummyTwo.length()-1);
final ClassGrammerItem classGrammerItem = new ClassGrammerItem(wordOne,wordTwo,id);
listGrammerItem.add(classGrammerItem);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
}
private void inflateData(RealmList<ClassGrammerItem> listGrammerItem) {
AdapterGrammerItem adapter = new AdapterGrammerItem(listGrammerItem, GrammerDetails.this);
recyclerView.setAdapter(adapter);
}
Adapter:
public class AdapterGrammerItem extends RecyclerView.Adapter<AdapterGrammerItem
.ViewHolderAdapterRecycler> {
RealmList<ClassGrammerItem> activityList = new RealmList<ClassGrammerItem>();
Context context;
private LayoutInflater layoutInflater;
public AdapterGrammerItem(RealmList<ClassGrammerItem> activityList, Context context) {
this.activityList = activityList;
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
#Override
public AdapterGrammerItem.ViewHolderAdapterRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.recycler_grammer_item, parent, false);
AdapterGrammerItem.ViewHolderAdapterRecycler viewHolder = new AdapterGrammerItem.ViewHolderAdapterRecycler(view);
return viewHolder;
}
#Override
public void onBindViewHolder(AdapterGrammerItem.ViewHolderAdapterRecycler holder, int position) {
ClassGrammerItem currentItem = activityList.get(position);
holder.wordOne.setText(currentItem.getWordOne());
holder.wordTwo.setText(currentItem.getWordTwo());
}
#Override
public int getItemCount() {
return activityList.size();
}
public class ViewHolderAdapterRecycler extends RecyclerView.ViewHolder {
MyTextView wordOne, wordTwo;
public ViewHolderAdapterRecycler(View itemView) {
super(itemView);
wordOne = (MyTextView) itemView.findViewById(R.id.wordOne);
wordTwo = (MyTextView) itemView.findViewById(R.id.wordTwo);
}
}
}

VLCJ Equalizer work not correctly

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

IO streams to JPanel, GUI with InputStream and OutputStream in a JPanels JTextField and JTextArea

I'm trying to write a GUI where the user sees the System output in a JTextArea and where he writes the input in a JTextField, both object inside a JPanel.
How do I do to connect the System output stream to the JTextArea and the System input stream to the JTextField? I have googled and searched these forums but havnt found the solution. I would be very happy if someone could help me with this.
I have a Master class that calls the JPanel with the GUI, and I will have work executed in different threads later on, but right now I struggle with the basic issue of connecting IO streams to the JPanel. Down below is the 2 classes:
public class MainTest {
public static void main(String[] args) throws IOException {
JPanelOUT testpanel = new JPanelOUT();
JFrame frame = new JFrame();
frame.add(testpanel);
frame.setVisible(true);
frame.pack();
/*
System.setOut(CONVERT TEXTAREA TO AN OUTPUTSTREAM SOMEHOW??(JPanelOUT.textArea)));
System.setIn(CONVERT STRING TO AN INPUTSTREAM SOMEHOW?? JPanelOUT.textField);
*/
String text = Sreadinput();
System.out.println(text);
}
public static String Sreadinput() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(JPanelOUT.is));
String input=in.readLine();
return input;
}
}
public class JPanelOUT extends JPanel implements ActionListener {
protected static JTextField textField;
protected static JTextArea textArea;
public static InputStream is;
private final static String newline = "\n";
public JPanelOUT() throws UnsupportedEncodingException, FileNotFoundException {
super(new GridBagLayout());
JLabel label1 = new JLabel("OUTPUT:");;
JLabel label2 = new JLabel("INPUT:");;
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
textArea.setBackground(Color.black);
textArea.setForeground(Color.white);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(500,200));
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(label1, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
add(label2, c);
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
String WelcomeText1 = "Hello and welcome to the TEST";
String WelcomeText2 = "Trying to get the input field below to become the System.in and this output";
String WelcomeText3 = "field to become the System.out (preferrably both with UTF-8 encoding where";
String WelcomeText4 = "the scrollpane automatically scrolls down to the last output line)!";
textArea.append(WelcomeText1 + newline + newline + WelcomeText2 + newline + WelcomeText3 + newline + WelcomeText4 + newline + newline);
String text = textField.getText();
is =new ByteArrayInputStream(text.getBytes("UTF-8"));
}
public void actionPerformed(ActionEvent evt) {
String text2 = textField.getText();
textArea.append(text2 + newline);
textField.selectAll();
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
i am new to java, trying to deal with the streams, too :)
Sorry for bad English I am from Russia.
May be this code will help you.
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public MyPrintStream myPrintStream;
public NewJFrame()throws FileNotFoundException{
initComponents();
this.myPrintStream = new MyPrintStream("string");
}
private class MyPrintStream extends PrintStream {
MyPrintStream(String str)throws FileNotFoundException{
super(str);
}
public void println(String s){
textArea1.append(s+'\n');
}
} .. continuation class code
Main method:
public static void main(String args[]){
/* Set the Nimbus look and feel... */
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run(){
try{
NewJFrame myJFrame = new NewJFrame();
myJFrame.setVisible(true);
System.setOut(myJFrame.myPrintStream);
System.out.println("its work");
System.out.println("its work2");
System.out.print("str"); //does not work, need to override
}catch (FileNotFoundException e){System.out.println (e.getMessage());}
}
});

Resources