sorting the elements of a jlist - java

I am trying to sort a JList when pressing the sort button but I can't figure it out how.
This is my code:
Song class:
package song;
public class Song implements Comparable<Song>{
private String name;
private String artist;
public Song(String name, String artist){
this.name = name;
this.artist = artist;
}
public String getName(){
return name;
}
public String getArtist(){
return artist;
}
public void setArtist(String artist){
this.artist = artist;
}
public void setName(String name){
this.name = name;
}
public int compareTo(Song s){
return this.name.compareTo(s.getName());
}
public String toString(){
return name + " " + artist;
}
}
List Model:
package song;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.AbstractListModel;
public class ListModel extends AbstractListModel{
ArrayList<Song> songs;
public ListModel(ArrayList<Song> array){
songs = array;
}
public int getSize(){
return songs.size();
}
public Object getElementAt(int index){
return (Song)songs.get(index);
}
public ArrayList<Song> getSongList(){
return songs;
}
public void setList(ArrayList<Song> array){
this.songs = array;
}
public void getSortedList(ArrayList<Song> array){
Collections.sort(array);
songs = array;
}
}
App class:
package song;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
public class App extends JFrame{
JFrame frame;
JList<Song> list;
ArrayList<Song> songList;
ListModel songModelList;
private static final String FILE = "songs.txt";
JPanel loadPanel, addBtnPanel;
JButton btnLoad, btnSort, btnAdd, btnSave;
JTextField txtArtist, txtName;
public static void main(String[] args){
App a = new App();
}
public App(){
frame = new JFrame("Playlist");
loadPanel = createLoadPanel();
loadPanel.setBackground(Color.BLUE);
JPanel btnPanel = createButtonPanel();
btnPanel.setBackground(Color.ORANGE);
frame.getContentPane().add(btnPanel,BorderLayout.EAST);
frame.getContentPane().add(loadPanel,BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
// frame.pack();s
frame.setVisible(true);
}
public JPanel createButtonPanel(){
JPanel panel = new JPanel();
btnLoad = new JButton("Load List");
btnSort = new JButton("Sort list");
btnAdd = new JButton("Add");
btnSort.addActionListener(new ActionListener() { //here is the action listener for the button used for sorting
#Override
public void actionPerformed(ActionEvent e) {
// Collections.sort(songList);
// songModelList.setList(songList);
songModelList.getSortedList(songList);
list.updateUI();
}
});
btnLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
loadPanel.setVisible(true);
}
});
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addBtnPanel = createAddPanel();
}
});
panel.add(btnLoad);
panel.add(btnSort);
panel.add(btnAdd);
return panel;
}
public JPanel createAddPanel(){
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(3,2));
JLabel lblName = new JLabel("Name");
JLabel lblArtist = new JLabel("Artist");
txtName = new JTextField(15);
txtArtist = new JTextField(15);
panel.add(lblName);
panel.add(txtName);
panel.add(lblArtist);
panel.add(txtArtist);
btnSave = new JButton("Save");
panel.add(btnSave);
btnSave.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = txtName.getText();
String artist = txtArtist.getText();
Song s = new Song(name, artist);
songModelList.getSongList().add(s);
list.updateUI();
}
});
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.setVisible(true);
frame.setSize(new Dimension(300,100));
return panel;
}
public JPanel createLoadPanel(){
JPanel LoadPanel = new JPanel();
list = new JList<Song>();
songList = loadFromFile();
songModelList = new ListModel(songList);
songList = new ArrayList<Song>();
list.setModel(songModelList);
list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
LoadPanel.add(list);
LoadPanel.setVisible(false);
return LoadPanel;
}
public ArrayList<Song> loadFromFile(){
ArrayList<Song> array = new ArrayList<Song>();
try{
BufferedReader reader = new BufferedReader(new FileReader(FILE));
String line = null;
while((line = reader.readLine()) != null){
String[] parts = line.split(" - ");
if(parts.length == 2){
String name = parts[0];
String artist = parts[1];
Song s = new Song(name, artist);
array.add(s);
}
else{
System.out.println("Invalid line!");
}
}
reader.close();
}catch(IOException e){
System.out.println("File not found");
e.printStackTrace();
}
return array;
}
}
So, the JList desplays the elements in the order they are added. But if the user wants to sort them I made a sort button and when the button is pressed the JList shows the elements in sorted order. How do I manage to do that? I tried over and over again but it doesn't work.

Just add method sort() to ListModel:
public void sort(){
Collections.sort(songs);
fireContentsChanged(this, 0, songs.size());
}
And fix btnSort action:
btnSort.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
songModelList.sort();
}
});

In your model, try using a TreeSet<Song> and then create a Comparator<Song> and pass it into the constructor of your TreeSet<Song>. It will automatically sort all the elements as elements are added.

You need to call the appropriate fire* method of the list model when you have modified the contents. Call fireContentsChanged(this, 0, songs.size() - 1) in getSortedList(). (Which, by the way, is confusingly named).

Related

how can i capture data from one class and pass it around all classes

i have a multi class program, with each class having its own GUI, my task is to capture details from a class called dataInput and the data must be captured into variables of a class called studentRecords, i must capture about 10 records comprised of name, surname, student number and tests from 1-4, i have a class called RecordsMenu which have Buttons that call the different classes, for example, when i click dataInput button it calls the DataInput class, in the datainput class i must capture data into records class, then i must go back to recordsMenu screen, from there! when i click for example, the display Button , i must be able to see the data i captured, the problem i have is that, when ever i go back to the main screen , all the data i captured get lost and it print nulls when i test whether it captured or not, i will appreciate any kind of help, my code is below.this must be done with out using files, thank you
[here is the picture of the main screen of my application][1]
enter code here
[1]: https://i.stack.imgur.com/I6JyI.jpg
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;
public class InputDetails extends JPanel
{
JLabel title,name,surname,studentno,tests,t1,t2,t3,t4;
JTextField nametxf,surnametxf,studentnotxf,t1txf,t2txf,t3txf,t4txf;
JButton submit,home;
JPanel buttons, mainPanel, labels;
public InputDetails()
{
// title
title = new JLabel("Records Menu",SwingConstants.CENTER);
title.setForeground(Color.BLUE);
Font newLabelFont =new Font("Serif",Font.BOLD,70);
title.setFont(newLabelFont);
// buttons and actions
submit = new JButton("Submit");
submit.addActionListener(new Handler());
home = new JButton("Home");
home.addActionListener(new Handler());
//labels
name = new JLabel("Name");
surname = new JLabel("Surname");
studentno= new JLabel("Student Number");
tests = new JLabel("Tests");
// tests
t1 = new JLabel("Test 1");
t2 = new JLabel("Test 2");
t3 = new JLabel("Test 3");
t4 = new JLabel("Test 4");
//textfields
nametxf = new JTextField(10);
surnametxf = new JTextField(10);
studentnotxf = new JTextField(10);
t1txf= new JTextField(10);
t2txf= new JTextField(10);
t3txf= new JTextField(10);
t4txf= new JTextField(10);
buttons = new JPanel(new GridLayout(1,2,5,5));
buttons.add(submit);
buttons.add(home);
// fields
labels = new JPanel(new GridLayout(7,1,5,5));
labels.add(name);
labels.add(nametxf);
labels.add(surname);
labels.add(surnametxf);
labels.add(studentno);
labels.add(studentnotxf);
labels.add(t1);
labels.add(t1txf);
labels.add(t2);
labels.add(t2txf);
labels.add(t3);
labels.add(t3txf);
labels.add(t4);
labels.add(t4txf);
//
mainPanel = new JPanel(new BorderLayout(5,5));
mainPanel.add(title,BorderLayout.NORTH);
mainPanel.add(labels,BorderLayout.WEST);
mainPanel.add( buttons,BorderLayout.SOUTH);
add(mainPanel);
}
class Handler implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
if(click.getSource()==home)
{
// back to main view
mainPanel.setVisible(false);
add(new RecordsMenu());
}
else if(click.getSource()==submit)
{
String name,surname,studentno;
int test1,test2,test3,test4;
name = nametxf.getText();
surname = surnametxf.getText();
studentno=studentnotxf.getText();
test1 =Integer.parseInt(t1txf.getText());
test2 = Integer.parseInt(t2txf.getText());
test3 = Integer.parseInt(t3txf.getText());
test4 = Integer.parseInt(t4txf.getText());
StudentRecords records = new StudentRecords(name,surname,studentno,test1,test2,test3,test4);
}
}
}
}
import java.io.*;
import javax.swing.JOptionPane;
public class StudentRecords {
String name , Surname, studentno;
int test1,test2,test3,test4;
FileWriter records;
PrintWriter out;
public StudentRecords(String Name, String Surname,String StudentNo,int t1, int t2, int t3, int t4)
{
setName(Name);
setSurname(Surname);
setStudentno(StudentNo);
setTest1(t1);
setTest2(t2);
setTest3(t3);
setTest4(t4);
// saveRecords();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getStudentno() {
return studentno;
}
public void setStudentno(String studentno) {
this.studentno = studentno;
}
public int getTest1() {
return test1;
}
public void setTest1(int test1) {
this.test1 = test1;
}
public int getTest2() {
return test2;
}
public void setTest2(int test2) {
this.test2 = test2;
}
public int getTest3() {
return test3;
}
public void setTest3(int test3) {
this.test3 = test3;
}
public int getTest4() {
return test4;
}
public void setTest4(int test4) {
this.test4 = test4;
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.*;
public class ReadFile extends JPanel{
private JButton read,back;
private JTextArea desplay;
private JLabel title;
private JPanel mainpanel, buttons;
String record,student1,student2,student3,student4,student5,student6,student7,student8,student9,student10;
public ReadFile()
{
// title
title = new JLabel("Read File Contents",SwingConstants.CENTER);
Font newLabelFont =new Font("Serif",Font.BOLD,30);
title.setFont(newLabelFont);
// textarea
desplay = new JTextArea();
// buttons
read = new JButton("Open");
read.addActionListener(new Handler());
back = new JButton("back to main");
back.addActionListener(new Handler());
// panel
buttons = new JPanel(new GridLayout(1,2,5,5));
buttons.add(read);
buttons.add(back);
mainpanel = new JPanel(new BorderLayout(5,5));
mainpanel.add(title,BorderLayout.NORTH);
mainpanel.add(desplay,BorderLayout.CENTER);
mainpanel.add(buttons,BorderLayout.SOUTH);
add(mainpanel);
}
class Handler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent click) {
if(click.getSource()==read)
{
JFileChooser chooser = new JFileChooser();
Scanner input = null;
if(chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
try {
input = new Scanner(selectedFile);
while(input.hasNextLine())
{
record = input.nextLine();
desplay.append(record);
desplay.append("\n");
}
}catch(IOException fileerror) {
JOptionPane.showMessageDialog(null, "you have an error");
}
}
}
else if(click.getSource()==back)
{
mainpanel.setVisible(false);
add(new RecordsMenu());
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Search extends JPanel
{
DisplayDetails d = new DisplayDetails();
JLabel title,stdn;
JTextField studentno;
JPanel mainp,details,buttons;
JButton search,home;
Scanner input;
File records;
String key;
String line;
boolean wordfound = false;
public Search()
{
// title
title = new JLabel("Search a Student",SwingConstants.CENTER);
Font newLabelFont =new Font("Serif",Font.BOLD,30);
title.setFont(newLabelFont);
stdn = new JLabel("Student Number");
studentno = new JTextField(10);
//
search = new JButton("Search");
search.addActionListener(new Handler());
home = new JButton("Home");
mainp = new JPanel(new BorderLayout());
details = new JPanel(new GridLayout(1,2));
details.add(stdn);
details.add(studentno);
buttons = new JPanel(new GridLayout(1,2));
home.addActionListener(new Handler());
buttons.add(search);
buttons.add(home);
mainp.add(title,BorderLayout.NORTH);
mainp.add(details,BorderLayout.WEST);
mainp.add(buttons,BorderLayout.SOUTH);
add(mainp);
}
class Handler implements ActionListener
{
public void actionPerformed(ActionEvent button)
{
if(button.getSource()==search)
{
// define the key
key = studentno.getText();
if(key.matches("^2\\d{8}"))
{
File file =new File("StudentRecords.txt");
Scanner in;
try {
in = new Scanner(file);
while(in.hasNextLine())
{
line=in.nextLine();
if((line.contains(key))) {
wordfound=true;
break;
}
}
if((wordfound)) {
System.out.println(line);
mainp.setVisible(false);
add(d);
d.display.setText(line);
JOptionPane.showMessageDialog(null,"found");
}
else
{
JOptionPane.showMessageDialog(null,"not found");
}
in.close();
} catch(IOException e) {
}
}
else if(!(key.matches("^2\\d{8}")))
{
JOptionPane.showMessageDialog(null,"incorrect student number");
}
}
else if(button.getSource()==home)
{
mainp.setVisible(false);
add(new RecordsMenu());
}
}
}
// methods
public void RecordFOund()
{
}
public void notFound()
{
}
}
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame
{
public Frame()
{
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
add(new RecordsMenu());
// add(new Search());
setVisible(true);
}
}
try this
In the getter methods of the StudentRecords Class make them {return this.variable;}
as an example in the public int getTest1(){return this.test1;}

MVC Pattern JButton ActionListener not Responding

So I'm trying to create a simple test program where the user can enter something into a JTextField, click the "add" JButton, and a JTextArea will add the users string to the the JTextArea (continuously appending with new line).
I added the actionListener for the button and have a stateChanged and an update method, but nothing happens when I click the add button. No errors either. Could someone please point me in the right direction?
Here's my code:
MVCTester (main)
public class MVCTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
MVCController myMVC = new MVCController();
MVCViews myViews = new MVCViews();
myMVC.attach(myViews);
}
}
MVCController
import java.util.ArrayList;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MVCController {
MVCModel model;
ArrayList<ChangeListener> listeners;
public MVCController(){
model = new MVCModel();
listeners = new ArrayList<ChangeListener>();
}
public void update(String input){
model.setInputs(input);
for (ChangeListener l : listeners)
{
l.stateChanged(new ChangeEvent(this));
}
}
public void attach(ChangeListener c)
{
listeners.add(c);
}
}
MVCModel
import java.util.ArrayList;
public class MVCModel {
private ArrayList<String> inputs;
MVCModel(){
inputs = new ArrayList<String>();
}
public ArrayList<String> getInputs(){
return inputs;
}
public void setInputs(String input){
inputs.add(input);
}
}
MVCViews
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MVCViews implements ChangeListener {
private JTextField input;
private JTextArea echo;
private ArrayList<String> toPrint = new ArrayList<String>();
MVCController controller;
MVCViews(){
controller = new MVCController();
JPanel myPanel = new JPanel();
JButton addButton = new JButton("add");
echo = new JTextArea(10,20);
echo.append("Hello there! \n");
echo.append("Type something below!\n");
myPanel.setLayout(new BorderLayout());
myPanel.add(addButton, BorderLayout.NORTH);
input = new JTextField();
final JFrame frame = new JFrame();
frame.add(myPanel, BorderLayout.NORTH);
frame.add(echo, BorderLayout.CENTER);
frame.add(input, BorderLayout.SOUTH);
addButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
controller.update(input.getText());
}
});
frame.pack();
frame.setVisible(true);
}
#Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
toPrint = controller.model.getInputs();
for(String s: toPrint){
echo.append(s + "\n");
}
}
}
This is my first time trying to follow MVC format, so there might be issues with the model itself as well. Feel free to point them out. Thank you for your help!
The controller within the GUI is not the same controller that is created in main. Note how many times you call new MVCController() in your code above -- it's twice. Each time you do this, you're creating a new and distinct controller -- not good. Use only one. You've got to pass the one controller into the view. You can figure out how to do this. (hint, a setter or constructor parameter would work).
hint 2: this could work: MVCViews myViews = new MVCViews(myMVC);
one solution:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MVCTester {
public static void main(String[] args) {
MVCController myMVC = new MVCController();
MVCViews myViews = new MVCViews(myMVC);
myMVC.attach(myViews);
// myViews.setController(myMVC); // or this could do it
}
}
class MVCController {
MVCModel model;
ArrayList<ChangeListener> listeners;
public MVCController() {
model = new MVCModel();
listeners = new ArrayList<ChangeListener>();
}
public void update(String input) {
model.setInputs(input);
for (ChangeListener l : listeners) {
l.stateChanged(new ChangeEvent(this));
}
}
public void attach(ChangeListener c) {
listeners.add(c);
}
}
class MVCModel {
private ArrayList<String> inputs;
MVCModel() {
inputs = new ArrayList<String>();
}
public ArrayList<String> getInputs() {
return inputs;
}
public void setInputs(String input) {
inputs.add(input);
}
}
class MVCViews implements ChangeListener {
private JTextField input;
private JTextArea echo;
private ArrayList<String> toPrint = new ArrayList<String>();
MVCController controller;
MVCViews(final MVCController controller) {
// !! controller = new MVCController();
this.controller = controller;
JPanel myPanel = new JPanel();
JButton addButton = new JButton("add");
echo = new JTextArea(10, 20);
echo.append("Hello there! \n");
echo.append("Type something below!\n");
myPanel.setLayout(new BorderLayout());
myPanel.add(addButton, BorderLayout.NORTH);
input = new JTextField();
final JFrame frame = new JFrame();
frame.add(myPanel, BorderLayout.NORTH);
frame.add(echo, BorderLayout.CENTER);
frame.add(input, BorderLayout.SOUTH);
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (controller != null) {
controller.update(input.getText());
}
}
});
frame.pack();
frame.setVisible(true);
}
public void setController(MVCController controller) {
this.controller = controller;
}
#Override
public void stateChanged(ChangeEvent e) {
if (controller != null) {
toPrint = controller.model.getInputs();
for (String s : toPrint) {
echo.append(s + "\n");
}
}
}
}

Use wait() in Java

I need to create a new JFrame in a new Thread.. When I close the JFrame I need to return a String.
The problem is that the wait() method "doesn't wait" the "notify()" of new Thread.
Thank's for your answer.
import java.awt.Button;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class FinestraTesto extends Thread {
JLabel jdescr;
JTextArea testo;
JPanel pannelloTasti;
JButton bottoneInvio;
JButton bottoneAnnulla;
JFrame finestraTestuale;
JPanel panAll;
static Boolean pause = true;
String titolo;
String descrizione;
private static String testoScritto = "";
public String mostra() {
// Create a new thread
Thread th = new Thread(new FinestraTesto(titolo, descrizione));
th.start();
synchronized (th) {
try {
// Waiting the end of th.
th.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return testoScritto;
}
public void run() {
synchronized (this) {
System.out.println("Fatto 1 thread");
finestraTestuale = new JFrame(titolo);
finestraTestuale.setPreferredSize(new Dimension(600, 200));
finestraTestuale.setSize(600, 200);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
finestraTestuale.setLocation(
dim.width / 2 - finestraTestuale.getSize().width / 2,
dim.height / 2 - finestraTestuale.getSize().height / 2);
panAll = new JPanel();
panAll.setLayout(new BoxLayout(panAll, BoxLayout.Y_AXIS));
bottoneInvio = new JButton("Conferma");
bottoneAnnulla = new JButton("Annulla");
pannelloTasti = new JPanel();
testo = new JTextArea();
testo.setPreferredSize(new Dimension(550, 100));
testo.setSize(550, 100);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(testo);
jdescr = new JLabel(descrizione);
jdescr.setPreferredSize(new Dimension(550, 50));
jdescr.setSize(550, 50);
pannelloTasti.setLayout(new BoxLayout(pannelloTasti,
BoxLayout.X_AXIS));
pannelloTasti.add(bottoneInvio);
pannelloTasti.add(bottoneAnnulla);
panAll.add(jdescr);
panAll.add(scrollPane);
panAll.add(pannelloTasti);
finestraTestuale.add(panAll);
bottoneInvio.addActionListener(new ActionListener() {
#Override
/**
* metodo attivato quando c'è un'azione sul bottone
*/
public void actionPerformed(ActionEvent arg0) {
testoScritto = testo.getText();
pause = false;
finestraTestuale.show(false);
// send notify
notify();
}
});
bottoneAnnulla.addActionListener(new ActionListener() {
#Override
/**
* metodo attivato quando c'è un'azione sul bottone
*/
public void actionPerformed(ActionEvent arg0) {
pause = false;
testoScritto = "";
finestraTestuale.show(false);
// send notify
notify();
}
});
finestraTestuale.show();
}
}
public FinestraTesto(String titolo, String descrizione) {
this.titolo = titolo;
this.descrizione = descrizione;
}
}
You would better to use Synchronizers instead of wait and notify. They're more preferable because of simplicity and safety.
Given the difficulty of using wait and notify correctly, you should
use the higher-level concurrency utilities instead.
Effective Java (2nd Edition), Item 69
I solved with this class:
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
private JTextArea testo;
public CustomDialog(String title,String descrizione)
{
components = new ArrayList<>();
setTitle(title);
setMessageType(JOptionPane.PLAIN_MESSAGE);
addMessageText(descrizione);
testo = new JTextArea();
testo.setPreferredSize(new Dimension(550, 100));
testo.setSize(550, 100);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(testo);
addComponent(scrollPane);
setRootPane(null);
setOptions(new String[] { "Send", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
components.add(new JLabel(messageText));
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public String show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
if(selection == 0)
return testo.getText();
else
return null;
}
}

Create dynamically multiple panels in a GUI

In my GUI, after importing an Excel file, I need to create a variable amount of panels/tabs. The amount depends on the number of rows imported from the Excel file. I need to show the information contained in row in a different panel, with a couple of buttons to move between all the tabs. For example, if the Excel file contains 6 rows:
Field1: user1
Field2: user1Age
< [1/6] >
So, I can move through the different panels, by clicking on the arrows:
Field1: user2
Field2: user2Age
< [2/6] >
One more consideration: Excel file import is not the only way to get information, it must be possible to manually add information. Therefore, after starting the GUI there must be at least one panel, and if the user decides to import an Excel file, then multiple panels must be created.
I need just a hint to start coding. And of course I am open to other possibilities.
Here is a sample code that should get you started (you will need to reorganize a bit the code). Although there are 1000 dummy users, it only uses a single panel to display the information:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestMultiplePanels {
private final UserList userList;
private User currentUser;
private JTextField name;
private JTextField age;
private JTextField index;
private JButton prev;
private JButton next;
public TestMultiplePanels(UserList userList) {
this.userList = userList;
}
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel userPanel = new JPanel(new BorderLayout());
JPanel userInfoPanel = new JPanel(new GridBagLayout());
JPanel buttonPanel = new JPanel(new FlowLayout());
JLabel nameLabel = new JLabel("Name");
JLabel ageLabel = new JLabel("Age");
name = new JTextField(30);
age = new JTextField(5);
index = new JTextField(5);
index.setEditable(false);
prev = new JButton("<");
prev.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentUser(userList.previous(currentUser));
}
});
next = new JButton(">");
next.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setCurrentUser(userList.next(currentUser));
}
});
GridBagConstraints gbcLabel = new GridBagConstraints();
gbcLabel.anchor = GridBagConstraints.EAST;
GridBagConstraints gbcField = new GridBagConstraints();
gbcField.anchor = GridBagConstraints.WEST;
gbcField.gridwidth = GridBagConstraints.REMAINDER;
userInfoPanel.add(nameLabel, gbcLabel);
userInfoPanel.add(name, gbcField);
userInfoPanel.add(ageLabel, gbcLabel);
userInfoPanel.add(age, gbcField);
buttonPanel.add(prev);
buttonPanel.add(index);
buttonPanel.add(next);
userPanel.add(userInfoPanel);
userPanel.add(buttonPanel, BorderLayout.SOUTH);
setCurrentUser(userList.getUsers().get(0));
frame.add(userPanel);
frame.pack();
frame.setMinimumSize(frame.getPreferredSize());
frame.setVisible(true);
}
private void setCurrentUser(User user) {
currentUser = user;
name.setText(user.getUserName());
age.setText(String.valueOf(user.getAge()));
index.setText(user.getIndex() + "/" + userList.getCount());
next.setEnabled(userList.hasNext(user));
prev.setEnabled(userList.hasPrevious(user));
}
public static class UserList {
private List<User> users;
private List<User> unmodifiableUsers;
public UserList() {
super();
this.users = load();
unmodifiableUsers = Collections.unmodifiableList(users);
}
public int getCount() {
return users.size();
}
public List<User> getUsers() {
return unmodifiableUsers;
}
private List<User> load() {
List<User> users = new ArrayList<TestMultiplePanels.User>();
for (int i = 0; i < 1000; i++) {
User user = new User();
user.setUserName("User " + (i + 1));
user.setAge((int) (Math.random() * 80));
user.setIndex(i + 1);
users.add(user);
}
return users;
}
public boolean hasNext(User user) {
return user.getIndex() - 1 < users.size();
}
public boolean hasPrevious(User user) {
return user.getIndex() > 1;
}
public User next(User user) {
if (hasNext(user)) {
return users.get(user.getIndex());
} else {
return null;
}
}
public User previous(User user) {
if (hasPrevious(user)) {
return users.get(user.getIndex() - 2);
} else {
return null;
}
}
}
public static class User {
private String userName;
private int age;
private int index;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
public static void main(String[] args) {
final UserList userList = new UserList();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestMultiplePanels testMultiplePanels = new TestMultiplePanels(userList);
testMultiplePanels.initUI();
}
});
}
}
You can create the panels dynamically using an ArrayList, which I think is flexible enough for that and easily manageable. To handle panels display, you can use a CardLayout. Hope it helps
ArrayList<JPanel> panelGroup = new ArrayList<JPanel>();
for (int i=0;i<numberOfPanelsToCreate;i++){
panelGroup.add(new JPanel());
}

Display all deserialized Objects in JTable in JAVA

i want to show all objects in a table.
i have a folder named /menschen which contains files like this: "firstname.lastname.ser"
package adressverwaltung;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
// FILE
import java.io.*;
import java.util.*;
import java.util.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.HeadlessException;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
*
* #author
*/
public class Adressverwaltung {
JFrame mainWindow;
final File folder = new File("menschen");
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Adressverwaltung verweiss = new Adressverwaltung();
verweiss.main();
}
public void main() {
mainWindow = new JFrame();
mainWindow.setBounds(0, 0, 800, 400);
mainWindow.setLocationRelativeTo(null);
mainWindow.setLayout(null);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setResizable(false);
mainWindow.setVisible(true);
mainWindow.setLayout(new FlowLayout());
menu();
}
public String deserialize(String m, int field) {
try {
FileInputStream fin = new FileInputStream("menschen\\" + m);
ObjectInputStream ois = new ObjectInputStream(fin);
Person n = (Person) ois.readObject();
ois.close();
switch (field) {
case 1:
return n.vorname;
case 2:
return n.nachname;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void table(String[][] alle) {
String[] columnNames = {
"Vorname", "Nachname"
};
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(alle, columnNames);
f.add(new JScrollPane(table));
f.pack();
f.setVisible(true);
}
private static void serialize(Person m) {
try {
FileOutputStream fileOut =
new FileOutputStream("menschen\\" + m.vorname + "." + m.nachname + ".ser");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(m);
out.close();
fileOut.close();
} catch (IOException i) {
}
}
public void menu() {
JPanel list = new JPanel();
list.setBorder(BorderFactory.createLineBorder(Color.black));
list.setPreferredSize(new java.awt.Dimension(400, 360));
list.setBackground(Color.white);
mainWindow.add(list);
// Wir lassen unseren Dialog anzeigen
mainWindow.setVisible(true);
int ButtonWidth = 100;
int ButtonHeight = 30;
int ButtonTop = 10;
JButton Button1 = new JButton("List all");
JButton Button3 = new JButton("Search");
Button1.setBounds(10, ButtonTop, ButtonWidth, ButtonHeight);
Button3.setBounds(230, ButtonTop, ButtonWidth, ButtonHeight);
list.add(Button1);
list.add(Button3);
mainWindow.add(list);
createForm();
Button1.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
list(folder);
}
});
}
public void list(final File folder) {
String[][] rowData = new String[3][];
int r = 0;
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
} else {
String name = fileEntry.getName();
rowData[r][0] = deserialize(name, 1);
rowData[r][1] = deserialize(name, 2);
r++;
}
}
table(rowData);
}
private void createForm() {
JPanel p = new JPanel();
p.setLayout(new GridLayout(3, 2));
JButton b = new JButton("Neue Person!");
JLabel vornameLabel = new JLabel("Vorname:");
final JTextField vorname = new JTextField();
JLabel nachnameLabel = new JLabel("Nachname:");
final JTextField nachname = new JTextField();
p.add(vornameLabel);
p.add(vorname);
p.add(nachnameLabel);
p.add(nachname);
p.add(b);
p.setBorder(BorderFactory.createLineBorder(Color.black));
p.setPreferredSize(new java.awt.Dimension(300, 100));
p.setBackground(Color.white);
mainWindow.add(p);
// Wir lassen unseren Dialog anzeigen
mainWindow.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Person m = new Person(vorname.getText(), nachname.getText());
serialize(m);
JOptionPane.showMessageDialog(null, vorname.getText() + "." + nachname.getText() + ".ser abgespeichert.", "Tutorial 2", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
And this is my Person class:
package adressverwaltung;
/**
*
* #author Mahshid
*/
class Person implements java.io.Serializable {
// Allgemeine Kontaktinformationen:
public String vorname;
public String nachname;
// Adresse
public String strasse;
public int hausnummer;
public int postleitzahl;
public String ort;
public String land;
// Telefon
public int mobil;
public int festnetz;
// Email & Kommentar
public String mail;
public String kommentar;
Person(String vorname, String nachname) {
this.vorname = vorname;
this.nachname = nachname;
}
}
I think there is a problem in list() function. this is my first java code so please don't be surpriced if you see any big mistakes :)
By creating a 2D array like this:
String[][] rowData = new String[3][];
you are creating an array where where all the "column" data is not initialized. You can check this for yourself by doing:
for (String[] s: rowData) {
System.out.println(s);
}
Therefore attempting to assign any of the outer array elements to a single String is impossible:
rowData[r][0] = deserialize(name, 1);

Categories