Event Handling Swing components - java

I'm trying to learn Java bit by bit, recreating an application I completed in Python - a library control software, very basic. I am having problems, though, with Event Handling, primarily because (I think) I went full-blown in to Swing without knowing much about it, but figuring it out as I went.
Here's my code, so far:
public class SEHBV extends JFrame{
public SEHBV(){
super("SEHBV Biblio 2.0");
ImageIcon img = new ImageIcon("books.ico");
setIconImage(img.getImage());
JPanel p_ini, locar, devolver, buscar, administrar;
JLabel l_dia, l_mes, l_ano, loca_cs, loca_cl, loca_prazo, loca_cb, locado_state;
JTextField dia, mes, ano, loca_cs_tf, loca_cl_tf, loca_prazo_tf, loca_cb_tf, devolve_cod;
JTextArea loca_prazo_data, loca_oper_res, mostra_multa;
JButton data, loca_cb_bt, loca_commit, ver_multa;
JList<String> loca_s_res, loca_cb_res, atrasos, locados;
p_ini = new JPanel(new GridBagLayout());
GridBagConstraints i = new GridBagConstraints();
l_dia = new JLabel("Dia: ");
l_mes = new JLabel("Mês: ");
l_ano = new JLabel("Ano: ");
dia = new JTextField(6);
mes = new JTextField(6);
ano = new JTextField(6);
data = new JButton("Afirmar Data");
atrasos = new JList<String>();
atrasos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
atrasos.setLayoutOrientation(JList.VERTICAL);
atrasos.setVisibleRowCount(10);
JScrollPane scroll_atrasos = new JScrollPane(atrasos);
atrasos.setBackground(Color.WHITE);
atrasos.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
i.fill = GridBagConstraints.HORIZONTAL;
i.gridx = 0;
i.gridy = 0;
p_ini.add(l_dia, i);
i.gridx = 1;
p_ini.add(dia, i);
i.gridx = 2;
p_ini.add(l_mes, i);
i.gridx = 3;
p_ini.add(mes, i);
i.gridx = 4;
p_ini.add(l_ano, i);
i.gridx = 5;
p_ini.add(ano, i);
i.gridx = 6;
p_ini.add(data, i);
i.gridy = 1;
i.gridx = 0;
i.gridwidth = 7;
p_ini.add(scroll_atrasos, i);
//GUI Locação
locar = new JPanel(new GridBagLayout());
GridBagConstraints l = new GridBagConstraints();
l.gridx = 0;
l.gridy = 0;
JPanel loca_socios = new JPanel(new FlowLayout());
JPanel loca_oper = new JPanel(new GridBagLayout());
GridBagConstraints o = new GridBagConstraints();
JPanel loca_busca = new JPanel(new GridBagLayout());
GridBagConstraints b = new GridBagConstraints();
locar.add(loca_socios, l); //Busca de Sócios na janela de Locação
loca_s_res = new JList<String>();
loca_s_res.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
loca_s_res.setLayoutOrientation(JList.VERTICAL);
loca_s_res.setModel(Runner.nome_socios);
loca_s_res.setVisibleRowCount(25);
JScrollPane scroll_loca_s = new JScrollPane(loca_s_res);
loca_s_res.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
loca_socios.add(scroll_loca_s);
l.gridx = 1;
locar.add(loca_oper, l); //Locação propriamente dita
o.weighty = 1;
o.weightx = 1;
o.anchor = GridBagConstraints.NORTHWEST;
o.insets = new Insets(1,1,1,1);
loca_cs = new JLabel("Código do Sócio: ");
o.fill = GridBagConstraints.HORIZONTAL;
o.gridx = 0;
o.gridy = 0;
loca_oper.add(loca_cs, o);
loca_cs_tf = new JTextField(5);
loca_cs_tf.setEditable(false);
loca_cs_tf.setBackground(Color.WHITE);
o.fill = GridBagConstraints.BOTH;
o.gridx = 1;
o.gridy = 0;
loca_oper.add(loca_cs_tf, o);
loca_cl = new JLabel("Código do Livro: ");
o.fill = GridBagConstraints.BOTH;
o.gridx = 0;
o.gridy = 1;
loca_oper.add(loca_cl, o);
loca_cl_tf = new JTextField(5);
o.fill = GridBagConstraints.BOTH;
o.gridx = 1;
o.gridy = 1;
loca_oper.add(loca_cl_tf, o);
loca_prazo = new JLabel("Prazo para devolução (em dias): ");
o.fill = GridBagConstraints.BOTH;
o.gridx = 0;
o.gridy = 2;
loca_oper.add(loca_prazo, o);
loca_prazo_tf = new JTextField(5);
o.fill = GridBagConstraints.BOTH;
o.gridx = 1;
o.gridy = 2;
loca_oper.add(loca_prazo_tf, o);
loca_prazo_data = new JTextArea();
loca_prazo_data.setBackground(getForeground());
o.gridx = 0;
o.gridy = 3;
o.gridwidth = 3;
loca_oper.add(loca_prazo_data, o);
loca_commit = new JButton("Realizar Locação");
o.fill = GridBagConstraints.BOTH;
o.gridx = 0;
o.gridy = 4;
o.gridwidth = 3;
loca_oper.add(loca_commit, o);
loca_oper_res = new JTextArea();
loca_oper_res.setBackground(getForeground());
o.gridy = 5;
loca_oper.add(loca_oper_res, o);
l.gridx = 2;
locar.add(loca_busca, l);
loca_cb = new JLabel("Chave de Busca: ");
b.fill = GridBagConstraints.HORIZONTAL;
b.gridx = 0;
b.gridy = 0;
loca_busca.add(loca_cb, b);
loca_cb_tf = new JTextField(20);
b.fill = GridBagConstraints.HORIZONTAL;
b.gridx = 1;
b.gridy = 0;
loca_busca.add(loca_cb_tf, b);
loca_cb_bt = new JButton("Busca Rápida");
b.fill = GridBagConstraints.HORIZONTAL;
b.gridx = 2;
b.gridy = 0;
loca_busca.add(loca_cb_bt, b);
loca_cb_res = new JList<String>();
loca_cb_res.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
loca_cb_res.setLayoutOrientation(JList.VERTICAL);
b.fill = GridBagConstraints.HORIZONTAL;
loca_cb_res.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
b.gridx = 0;
b.gridy = 1;
b.gridwidth = 3;
b.gridheight = 2;
loca_cb_res.setVisibleRowCount(25);
JScrollPane scroll_loca_cb = new JScrollPane(loca_cb_res);
loca_cb_res.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
loca_busca.add(scroll_loca_cb, b);
// Other Tabs of the GUI
//GUI Geral
JTabbedPane tp = new JTabbedPane();
tp.addTab("Página inicial (Alt+I)", null, p_ini, "pág. inicial");
tp.addTab("Locação (Alt+L)", locar);
tp.addTab("Devolução (Alt+D)", devolver);
tp.addTab("Busca Avançada (Alt+B)", buscar);
tp.addTab("Administração (Alt+A)", administrar);
tp.setMnemonicAt(0, KeyEvent.VK_I);
tp.setMnemonicAt(1, KeyEvent.VK_L);
tp.setMnemonicAt(2, KeyEvent.VK_D);
tp.setMnemonicAt(3, KeyEvent.VK_B);
tp.setMnemonicAt(4, KeyEvent.VK_A);
add(tp);
}
So, lets say I'm trying to handle the clicking of the loca_commit JButton. I'm trying to create an Event Handler - according to Java tutorials and other StackOverflow questions/answers - but the handler does not identify loca_commit. Right now I'm just trying to get it to work, then I'll use it for calling a method, but if I can't make it create a pop up, well, you get my point.
So, my code for the handler so far is this:
private class LocaHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource()==loca_commit)
string=String.format("Botão Apertado");
JOptionPane.showMessageDialog(null, string);
}
Can you guys shed a light here?

The core issue is probably one of context, the LocaHandler probably doesn't have any context to SEHBV or the loca_commit button, so you can't reference it (it's out of context).
There are couple of ways you might fix this...
You could...
Pass a reference of loca_commit to the instance of LocaHandler, but unless you intended to make use of LocaHandler to handle multiple actions, it really doesn't make sense, which means...
You could...
Make LocaHandler responsible for only doing one thing, what ever loca_commit needs it to. This leads you into the realm of the Actions API
How ever...
You could...
Make use of the actionCommand property support of JButton and ActionEvent
loca_commit = new JButton("Realizar Locação");
loca_commit.setActionCommand("locaCommit");
//...
private class LocaHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if("locaCommit".equals(event.getActionCommand()))
string=String.format("Botão Apertado");
JOptionPane.showMessageDialog(null, string);
}
This means that you could use the same instance of LocaHandler to handle multiple commands (by expanding the if statement)
My personal preference is to use the Actions API or anonymous classes, focusing on the handlers to a single responsibility, if done well, it will increase the reusability of the classes

One way of making it work is to attach action listener on button after initializing it. In your case, try the following:
loca_commit = new JButton("Realizar Locação");
//other code
loca_commit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello");
}
});
loca_oper.add(loca_commit, o);
Remember, this is just one way of doing it. There are multiple other ways to achieve the same result.

Related

How to use JButton in Java

I'm trying to create a hangman game using the Swing class and Graphics class for a APCS class I have.
I created a JButton that would take the guess typed in by the user and either add it to the "misses" or fill in all of the corresponding letters in the word. I have a separate txt file where I pick a random word from.
When I run the program, all of the components show up, but the button does not do anything. I have been working on this for a few days and don't know what I am doing wrong. I have only learnt how to use the Swing class recently, so it may be a stupid mistake for all I know. I have put all of the code down below.
public class Hangman extends JFrame {
DrawPanel panel = new DrawPanel();
Graphics g = panel.getGraphics();
JTextField guess;
JTextField outputWord;
JTextField missesString;
boolean play;
JButton button = new JButton();
String output = "";
String word;
int misses = 0;
public Hangman() {
int again = 0;
String[] dictionary = new String[1000];
In words = new In("words.txt");
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
app.setSize(500, 500);
for (int i = 0; i < 1000; i++) {
dictionary[i] = words.readLine();
}
do {
int num = (int) (Math.random() * 1000);
word = dictionary[num].toLowerCase();
String answer = word;
word = "";
for (int i = answer.length(); i > 0; i--) {
word = word + "*";
}
int length = answer.length();
app.setLayout(new BorderLayout());
JLabel letter = new JLabel();
letter.setFont(new Font("Arial", Font.BOLD, 20));
letter.setText("Enter Your guess");
guess = new JTextField(10);
JLabel output = new JLabel();
output.setFont(new Font("Arial", Font.BOLD, 20));
output.setText("The Word is");
outputWord = new JTextField(30);
outputWord.setText(word);
outputWord.setEditable(false);
JLabel misses = new JLabel();
misses.setFont(new Font("Arial", Font.BOLD, 20));
misses.setText("Misses:");
missesString = new JTextField(52);
missesString.setEditable(false);
button = new JButton("Guess");
button.addActionListener(new ButtonListener());
JPanel panels = new JPanel();
panels.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.add(letter);
panel1.add(guess);
panel1.add(button);
JPanel panel2 = new JPanel();
panel2.add(output);
panel2.add(outputWord);
JPanel panel3 = new JPanel();
panel3.add(misses);
panel3.add(missesString);
app.add(panel1, BorderLayout.NORTH);
app.add(panel2, BorderLayout.EAST);
app.add(panel3, BorderLayout.SOUTH);
app.add(panels);
app.setVisible(true);
again = JOptionPane.showConfirmDialog(null, "Do you want to play again?");
} while (again == JOptionPane.YES_OPTION);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == guess) {
output = "";
}
for (int i = 0; i <= word.length() - 1; i++) {
if (guess.getText().equalsIgnoreCase(word.substring(i, i + 1))) {
output = output.substring(0, i) + guess + output.substring(i + 1, word.length() - 1);
outputWord.setText(output);
} else {
misses++;
missesString.setText(missesString.getText() + guess + " ");
}
}
}
}
}
The components show up perfectly on the screen, it is only the button that is giving me a hard time by not working as expected.

How to browse a file one folder to other folder and check size or dimenction copy it to another location

I have one Jtextfield and two Jbutton one button for browse image and other for copy image. first of all i want click on browse button then select a image then full path and image name show in text field then i click on upload button and image copy in specific folder.
Use file object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Register extends JFrame implements ActionListener
{
JTextField pro_pic_text;
JLabel pro_pic_lbl;
JButton browse_btn,upload_btn;
public Register()
{
setLayout(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.insets = new Insets(5,3,5,3);
pro_pic_lbl = new JLabel("Profile Picture :");
gbc1.gridx = 0;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(pro_pic_lbl,gbc1);
pro_pic_text = new JTextField(30);
pro_pic_text.setEditable(false);
gbc1.gridx = 1;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 3;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(pro_pic_text,gbc1);
browse_btn = new JButton("Browse...");
browse_btn.addActionListener(this);
gbc1.gridx = 4;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.NONE;
gbc1.anchor = GridBagConstraints.WEST;
add(browse_btn,gbc1);
upload_btn = new JButton("Upload");
upload_btn.addActionListener(this);
gbc1.gridx = 5;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.NONE;
gbc1.anchor = GridBagConstraints.WEST;
add(upload_btn,gbc1);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == browse_btn)
{
FileDialog fd = new FileDialog(new LibrarySystem(), "Choose Profile Picture",FileDialog.LOAD);
fd.show();
if(fd.getFile()==null&&pro_pic_text.getText().toString().trim().equals(""))
{
JOptionPane.showMessageDialog(this,"Choose your Profile Picrure","Warning",JOptionPane.WARNING_MESSAGE);
}
else
{
File ff1 = new File(fd.getFile());
String ffname = ff1.getName();
int aa = ffname.indexOf(".");
fftype = ffname.substring(aa+1);
if(fftype.equals("png") || fftype.equals("PNG") || fftype.equals("JPEG") || fftype.equals("jpeg") || fftype.equals("JPG") || fftype.equals("jpg"))
{
fileName = fd.getDirectory() + fd.getFile();
File ff2 = new File(fileName);
if(ff2.length()<=51300)
{
pro_pic_text.setText(fileName);
}
else
{
JOptionPane.showMessageDialog(this,"File size larger then 50kb not allowed","Warning",JOptionPane.WARNING_MESSAGE);
pro_pic_text.setText("");
}
}
else
{
JOptionPane.showMessageDialog(this,"Choose JPEG, JPG or PNG File","Warning",JOptionPane.WARNING_MESSAGE);
pro_pic_text.setText("");
}
}
}
else if(ae.getSource() == upload_btn)
{
pro_pic = pro_pic_text.getText().toString().trim();
if(pro_pic.equals(""))
{
JOptionPane.showMessageDialog(this,"First Choose your Profile Picrure","Warning",JOptionPane.WARNING_MESSAGE);
}
else
{
String cpro_pic = "src/profile pic/"+ffname+"."+fftype;
File ff1 = new File(pro_pic);
File ff2 = new File(cpro_pic);
iscopy = ff1.renameTo(ff2);
if(iscopy)
{
pro_pic_text.setText(cpro_pic);
}
else
{
JOptionPane.showMessageDialog(this,"Error in Photo Upload..!","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
use this
should be work

Problems on .JAR file with JTable and DefaultTableModel

i'm developing a desktop app. When i execute my .jar file on another computers, the jframe where i load data into a datatable is not workign correctly. The jre is the same on both computers. The jar works fine on my computer.
Here is the code:
public int cargarClaseEnVentanaResultados(ConjuntoResultados conjunto, ControladorVentanaResultados cont){
ArrayList<JPanel> jpArray= new ArrayList<>();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
String tipoExperimento = new String();
int contadorVariables = 0;
if (!conjunto.getConjuntoResultados().isEmpty()){
for (int i=0;i<conjunto.getConjuntoResultados().size();i++){
JTable jtable = new JTable(){
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
jtable.setRowSelectionAllowed(true);
jtable.setColumnSelectionAllowed(true);
jtable.setCellSelectionEnabled(true);
JPanel jpanel = new JPanel();
jpanel.setLayout(new GridBagLayout());
String[] columnNames ={"Variable","Valor"};
Object[][] data={};
DefaultTableModel model = new DefaultTableModel(data,columnNames);
String nombreConjunto = conjunto.getConjuntoResultados().get(i).getNombreResultado();contadorVariables++;
jpanel.setName(nombreConjunto);
for (int j=0;j<conjunto.getConjuntoResultados().get(i).getResultados().size();j++){
Object[] o = new Object[2];
String nombreVar = conjunto.getConjuntoResultados().get(i).getResultados().get(j).getNombre().replace(nombreConjunto+"_", "");
o[0] = nombreVar;
if (conjunto.getConjuntoResultados().get(i).getResultados().get(j).getCadena()!=null){
o[1] = conjunto.getConjuntoResultados().get(i).getResultados().get(j).getCadena();
}else if (conjunto.getConjuntoResultados().get(i).getResultados().get(j).getDoble()!=null){
o[1] = conjunto.getConjuntoResultados().get(i).getResultados().get(j).getDoble();
}else if (conjunto.getConjuntoResultados().get(i).getResultados().get(j).getEntero()!=null){
o[1] = conjunto.getConjuntoResultados().get(i).getResultados().get(j).getEntero();
}
model.addRow(o);
}
jtable.setModel(model);
jtable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
JScrollPane tableContainer = new JScrollPane(jtable);
jpanel.setPreferredSize(new Dimension(cont.getVentanaResultados().getjTabbedPane2().getWidth()-50,contadorVariables*altoVentana));
jpanel.add(tableContainer, c);
jpArray.add(jpanel);
}
for (int k=0;k<jpArray.size();k++){
aniadirScrollpane(jpArray.get(k), tipoExperimento, cont);
}
this.getVentanaResultados().getjTabbedPane2().getSelectedIndex();
}
return contadorVariables;
}
The only reason i could imagine was the java jre but it's the same. Is there any reason the table wont load? It only shows the headers and it's only loading the last tab.
Thanks!

How to create JButton array?

I have used below code but did not work properly. I have list of JButton objects on the panel but could not click on each button individually.
for(int i=0; i<udataArr.length(); i++) {
userBtn = new JButton();
userLb = new JLabel();
cur1 = userBtn.getCursor();
userBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Image imgUO = ImageIO.read(getClass().getResource("/resources/img-std.png"));
userBtn.setIcon(new ImageIcon(imgUO));
userBtn.setBorder(BorderFactory.createCompoundBorder(border,paddingBorder));
userLb.setText((String) udataArr.getJSONObject(i).get("user_name"));
//button[i].setText((String) udataArr.getJSONObject(i).get("user_name"));
panelLeft.add(userBtn);
panelLeft.add(userLb);
panelLeft.add(Box.createVerticalStrut(15));
}
This is the code to create JButton Array
JButton buttons[];
buttons = new JButton[10];
for(int i = 0; i < 10; i++) {
buttons[i] = new JButton(String.valueOf(i));
}

Strings not being, correctly, written to JTextField/Area on selection of row in JList

I'm using a vector to store the information displayed in the JList and I want to use the index of the selected index to copy the data of that row into the JTextField and JTextArea. I am having some issues where the selected item isn't be shown in the JTextField/Area but instead showing the data of a previous selected index. Every second index has an issue of showing the wrong data, 2, 4, 6, 8, 10 and then 11. Each of them will only show the right data if you select first when the program has just been executed. The print lines that I have added to the ListSelectionEvent listener shows the correct data of the selected index but it doesn't correctly copy it into the JTextArea/JTextField.
Selected right after the program was executed.
I selected a few other indices then tried to select it again
code:
public class EditFlashcardGui implements ListSelectionListener {
private JFrame frame;
private JPanel listPanel;
private Vector<Vector> flashcardMasterVector = new Vector<Vector>();
private JList list;
private JPanel tablePanel, dataPanel, textFieldPanel;
private JButton submitButton, cancelButton;
private JTextField frontTextField;
private JTextArea reverseTextArea;
private GridBagLayout gridBagLayout;
private GridBagConstraints constraints;
private JLabel frontTextLabel, reverseTextLabel;
Vector<Vector> masterVector = new Vector<Vector>();
public EditFlashcardGui() {
frame = new JFrame("Edit / Delete Flashcards");
frame.setSize(500, 200);
Container con = frame.getContentPane();
con.setLayout(new BorderLayout());
listPanel = new JPanel(new BorderLayout());
Vector<String> columnNames = new Vector<String>();
columnNames.add("id");
columnNames.add("front text");
columnNames.add("reverse text");
list = new JList(populateList());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(this);
Font font1 = new Font("SansSerif", Font.BOLD, 20);
list.setFont(font1);
tablePanel = new JPanel();
tablePanel.add(list);
JScrollPane scrollPane = new JScrollPane(list);
con.add(scrollPane, BorderLayout.NORTH);
// south panel
gridBagLayout = new GridBagLayout();
constraints = new GridBagConstraints();
textFieldPanel = new JPanel(gridBagLayout);
// cancelButton = new JButton("Cancel");
// dataPanel.add(cancelButton, BorderLayout.SOUTH);
frontTextLabel = new JLabel("Front Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 0;
gridBagLayout.setConstraints(frontTextLabel, constraints);
textFieldPanel.add(frontTextLabel);
frontTextField = new JTextField();
frontTextField.setColumns(30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 1;
gridBagLayout.setConstraints(frontTextField, constraints);
textFieldPanel.add(frontTextField);
reverseTextLabel = new JLabel("Reverse Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 2;
gridBagLayout.setConstraints(reverseTextLabel, constraints);
textFieldPanel.add(reverseTextLabel);
reverseTextArea = new JTextArea(3, 30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 3;
gridBagLayout.setConstraints(reverseTextArea, constraints);
textFieldPanel.add(reverseTextArea);
submitButton = new JButton("Submit");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 4;
gridBagLayout.setConstraints(submitButton, constraints);
textFieldPanel.add(submitButton);
con.add(textFieldPanel, BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public Vector<Vector> populateList() {
//flashcardMasterVector = flashcardDB.getList();
//Vector<String> flashcardVector = new Vector<String>();
Integer temp = 0;
for(int i = 0; i <= 20; i++) {
Vector<String> flashcardVector = new Vector<String>();
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
masterVector.add(i, flashcardVector);
temp++;
}
return masterVector;
}
public static void main(String[] args) {
EditFlashcardGui gui = new EditFlashcardGui();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (! e.getValueIsAdjusting())
{
System.out.print("id : " );
System.out.println(masterVector.get(list.getSelectedIndex()).get(0));
System.out.print("front text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(1));
frontTextField.setText(masterVector.get(e.getFirstIndex())
.get(1).toString());
System.out.print("reverse text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(2));
reverseTextArea.setText(masterVector.get(e.getFirstIndex())
.get(2).toString());
}
}
}
have to read Oracles tutorial about How to Use JList
you can't put Vector<Vector> to the JList directly,
put value and to use XxxListModel only, but in this case have to create crazy workaround for AbstractListModel, use simple array instead
JList is based on one dimensional array have to use Vector<Object (or String or Double...)>
don't complicate simple things put this array to the JTable (to the XxxTableModel), remove all synchronizations columns, remove JTableHeader if required, then output to the GUI looks like as JList
JTable.removeColumn remove only column from view, all data are still presented and stored into XxxTableModel without any changes
then selected (have to test for -1 == none of row is selected) row (have to convertViewToModel in the case that JTable is sorted or filtered) returns all required data from XxxTableModel
Use list.getSelectedIndex() instead of e.getFirstIndex() method.
Code :
frontTextField.setText( masterVector.get(list.getSelectedIndex() ).get(1).toString() );
reverseTextArea.setText(masterVector.get( list.getSelectedIndex()).get(2).toString() );
Clean Code:
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
Vector masterVec = masterVector.get( list.getSelectedIndex() );
System.out.print("id : ");
System.out.println(masterVec.get(0));
System.out.print("front text : ");
System.out.println(masterVec.get(1));
System.out.print("reverse text : ");
System.out.println(masterVec.get(2));
frontTextField.setText(masterVec.get(1).toString());
reverseTextArea.setText(masterVec.get(2).toString());;
}
}

Categories

Resources