Guys I have a problem with my JTable, my JTable(tblLivro) which contents should be the result(ArrayList) of my query (working) , but when I try to put the rsult in my jtable it just doesn't work, it doesn't show any errors, yet not show it. Why?
Here is my code
package view;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
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 model.Livro;
import control.LivroControl;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
public class LivroView extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lblIdLivro, lblLombada, lblTitulo, lblTituloInternacional, lblEdicao, lblEditora, lblAutor ;
private JTextField txtIdLivro, txtTombo, txtTitulo, txtTituloInternacional, txtEdicao, txtEditora, txtAutor;
private JButton btnAdicionar, btnPesquisar, btnExcluir;
private JPanel painelPrincipal, painelGeral, painelBotoes, painelJPanel;
private JTable tblLivros;
private List<Livro> encontrados;
DefaultTableModel modelo;
public LivroView() {
super("Manutenção de Livros");
encontrados = new ArrayList<Livro>();
lblIdLivro = new JLabel("Código do livro:");
lblLombada = new JLabel("Tombo:");
lblTitulo = new JLabel("Título:");
lblTituloInternacional = new JLabel("Título Internacional:");
lblEdicao = new JLabel("Edição:");
lblEditora = new JLabel("Editora:");
lblAutor = new JLabel("Autor:");
txtIdLivro = new JTextField(20);
txtTombo= new JTextField("Tombo");
txtTitulo = new JTextField(20);
txtTituloInternacional= new JTextField(20);
txtEdicao = new JTextField(20);
txtEditora= new JTextField(20);
txtAutor= new JTextField("Autor");
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
btnAdicionar = new JButton("Adicionar");
btnExcluir = new JButton("Excluir");
btnPesquisar = new JButton("Pesquisar");
btnAdicionar.addActionListener(this);
btnPesquisar.addActionListener(this);
btnExcluir.addActionListener(this);
painelPrincipal = new JPanel();
painelGeral = new JPanel();
painelBotoes = new JPanel();
painelJPanel = new JPanel();
painelPrincipal.setLayout(new BorderLayout());
painelGeral.setLayout(new GridLayout(7,2));
painelBotoes.setLayout(new GridLayout(2,1));
painelGeral.add(lblIdLivro);
painelGeral.add(txtIdLivro);
painelGeral.add(lblLombada);
painelGeral.add(txtTombo);
painelGeral.add(lblTitulo);
painelGeral.add(txtTitulo);
painelGeral.add(lblTituloInternacional);
painelGeral.add(txtTituloInternacional);
painelGeral.add(lblEdicao);
painelGeral.add(txtEdicao);
painelGeral.add(lblEditora);
painelGeral.add(txtEditora);
painelGeral.add(lblAutor);
painelGeral.add(txtAutor);
painelBotoes.add(btnAdicionar);
painelBotoes.add(btnPesquisar);
painelBotoes.add(btnExcluir);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(55, 80, 359, 235);
painelJPanel.add(scrollPane);
tblLivros = new JTable();
tblLivros.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Tombo", "T\u00EDtulo", "T\u00EDtulo Internacional", "Edi\u00E7\u00E3o", "Autor", "Editora"
}
));
modelo = new DefaultTableModel();
tblLivros.getColumnModel().getColumn(0).setPreferredWidth(54);
tblLivros.getColumnModel().getColumn(1).setPreferredWidth(104);
tblLivros.getColumnModel().getColumn(2).setPreferredWidth(136);
tblLivros.getColumnModel().getColumn(4).setPreferredWidth(102);
// modelo = (DefaultTableModel) tblLivros.getModel();
scrollPane.setViewportView(tblLivros);
painelJPanel.setLayout(null);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
this.setSize(500,300);
this.setVisible(true);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
LivroControl control = new LivroControl();
if ("Adicionar".equalsIgnoreCase(cmd)){
boolean adicionado = false;
adicionado = control.adicionarLivro(txtIdLivro.getText(), txtTitulo.getText(), txtTituloInternacional.getText(), txtTombo.getText(), txtAutor.getText(), txtEdicao.getText(), txtEditora.getText());
if (adicionado == true){
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
txtIdLivro.requestFocus();
}
}
else if("Excluir".equalsIgnoreCase(cmd)){
control.excluirLivro(txtTombo.getText());
txtTombo.setText("");
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
Livro l = control.pesquisarLivroPorTombo(txtTombo.getText());
if (l!=null){
txtIdLivro.setText(String.valueOf(l.getIdLivro()));
txtTombo.setText(l.getTombo());
txtTitulo.setText(l.getTitulo());
txtTituloInternacional.setText(l.getTituloInternacional());
txtEdicao.setText(l.getEdicao());
txtEditora.setText(l.getEditora());
txtAutor.setText(l.getAutor());
}
}
else if (!txtAutor.getText().equals("")){
encontrados = control.pesquisarLivroPorAutor(txtAutor.getText());
if (encontrados!= null){
for (Livro dados : encontrados){
Object[] objetoTombo = new Object[1];
Object[] objetoTitulo = new Object[2];
Object[] objetoTituloInternacional = new Object[3];
Object[] objetoEdicao = new Object[4];
Object[] objetoAutor = new Object[5];
Object[] objetoEditora = new Object[6];
objetoTombo[0] = dados.getTombo();
objetoTitulo[0] = dados.getTitulo();
objetoTituloInternacional[0] = dados.getTituloInternacional();
objetoEdicao[0] = dados.getEdicao();
objetoAutor[0]= dados.getAutor();
objetoEditora[0]= dados.getEditora();
//modelo.setNumRows(0);
modelo.addRow(objetoTombo);
modelo.addRow(objetoTitulo);
modelo.addRow(objetoTituloInternacional);
modelo.addRow(objetoEdicao);
modelo.addRow(objetoAutor);
modelo.addRow(objetoEditora);
}
this.setSize(700,500);
tblLivros.setModel(modelo);
painelJPanel.add(tblLivros);
painelJPanel.setVisible(true);
painelJPanel.repaint();
painelPrincipal.add(painelJPanel, BorderLayout.SOUTH);
painelPrincipal.repaint();
}
}
else {
encontrados = control.pesquisarLivroPorNome(txtTitulo.getText());
if (encontrados!= null){
}
}
}
}
public static void main(String[] args) {
new LivroView();
}
}
Thank you!
Because you didn't even added JScrollPane on your painelPrincipal. You can do it like this:
painelPrincipal.add(scrollPane, BorderLayout.SOUTH);
Also:
Do not call setVisible for JFrame before all components are added.
Call pack instead of setSize for JFrame
Avoid using null layout and absolute positioning.
Regards and good luck!
EDIT:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LivroView extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lblIdLivro, lblLombada, lblTitulo, lblTituloInternacional, lblEdicao, lblEditora, lblAutor ;
private JTextField txtIdLivro, txtTombo, txtTitulo, txtTituloInternacional, txtEdicao, txtEditora, txtAutor;
private JButton btnAdicionar, btnPesquisar, btnExcluir;
private JPanel painelPrincipal, painelGeral, painelBotoes, painelJPanel;
private JTable tblLivros;
DefaultTableModel modelo;
public LivroView() {
super("Manutenção de Livros");
lblIdLivro = new JLabel("Código do livro:");
lblLombada = new JLabel("Tombo:");
lblTitulo = new JLabel("Título:");
lblTituloInternacional = new JLabel("Título Internacional:");
lblEdicao = new JLabel("Edição:");
lblEditora = new JLabel("Editora:");
lblAutor = new JLabel("Autor:");
txtIdLivro = new JTextField(20);
txtTombo= new JTextField("Tombo");
txtTitulo = new JTextField(20);
txtTituloInternacional= new JTextField(20);
txtEdicao = new JTextField(20);
txtEditora= new JTextField(20);
txtAutor= new JTextField("Autor");
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
btnAdicionar = new JButton("Adicionar");
btnExcluir = new JButton("Excluir");
btnPesquisar = new JButton("Pesquisar");
btnAdicionar.addActionListener(this);
btnPesquisar.addActionListener(this);
btnExcluir.addActionListener(this);
painelPrincipal = new JPanel();
painelGeral = new JPanel();
painelBotoes = new JPanel();
painelJPanel = new JPanel();
painelPrincipal.setLayout(new BorderLayout());
painelGeral.setLayout(new GridLayout(7,2));
painelBotoes.setLayout(new GridLayout(2,1));
painelGeral.add(lblIdLivro);
painelGeral.add(txtIdLivro);
painelGeral.add(lblLombada);
painelGeral.add(txtTombo);
painelGeral.add(lblTitulo);
painelGeral.add(txtTitulo);
painelGeral.add(lblTituloInternacional);
painelGeral.add(txtTituloInternacional);
painelGeral.add(lblEdicao);
painelGeral.add(txtEdicao);
painelGeral.add(lblEditora);
painelGeral.add(txtEditora);
painelGeral.add(lblAutor);
painelGeral.add(txtAutor);
painelBotoes.add(btnAdicionar);
painelBotoes.add(btnPesquisar);
painelBotoes.add(btnExcluir);
tblLivros = new JTable();
tblLivros.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Tombo", "T\u00EDtulo", "T\u00EDtulo Internacional", "Edi\u00E7\u00E3o", "Autor", "Editora"
}
));
JScrollPane scrollPane = new JScrollPane(tblLivros);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
painelPrincipal.add(scrollPane, BorderLayout.SOUTH);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("Adicionar".equalsIgnoreCase(cmd)){
boolean adicionado = false;
if (adicionado == true){
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
txtIdLivro.requestFocus();
}
}
else if("Excluir".equalsIgnoreCase(cmd)){
txtTombo.setText("");
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
}
else if (!txtAutor.getText().equals("")){
} }
}
public static void main(String[] args) {
new LivroView();
}
}
Ok, here is your code. Altough I had to remove some pieces of code to make it functional.
First of all, stop using null layouts. Swing was designed to be used with layout managers.
You add the table to the scroll pane which is a good thing.
scrollPane.setViewportView(tblLivros);
Later on it looks like you update the model (which is a good thing), but then you add the table to another panel (which is a bad thing). This removes the table from the scrollpane. The table will no longer have a header unless the table is displayed in a scrollpane. All you need to do is invoke the setModel() method and the table will automatically repaint itself.
tblLivros.setModel(modelo);
//painelJPanel.add(tblLivros);
//painelJPanel.setVisible(true);
//painelJPanel.repaint();
//painelPrincipal.add(painelJPanel, BorderLayout.SOUTH);
If you ever do need to add a component to a visible GUI then the code should be:
panel.add(..)
panel.revalidate();
panel.repaint();
just got help from a friend, here is the final code:
public class LivroView extends JFrame implements ActionListener {
private JTable tblLivros;
DefaultTableModel modeloTabela;
private List<Livro> encontrados;
public LivroView() {
super("Manutenção de Livros");
encontrados = new ArrayList<Livro>();
modeloTabela = new DefaultTableModel(
new String[] {
"Tombo", "Título", "Título Internacional", "Edição", "Autor", "Editora"
}, 0);
tblLivros = new JTable(modeloTabela);
tblLivros.getColumnModel().getColumn(0).setPreferredWidth(54);
tblLivros.getColumnModel().getColumn(1).setPreferredWidth(104);
tblLivros.getColumnModel().getColumn(2).setPreferredWidth(136);
tblLivros.getColumnModel().getColumn(4).setPreferredWidth(102);
painelTabela = new JScrollPane(tblLivros);
painelTabela.setVisible(false);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
painelPrincipal.add(painelTabela, BorderLayout.SOUTH);
//this.setSize(500,300);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
LivroControl control = new LivroControl();
if ("Adicionar".equalsIgnoreCase(cmd)){
}
else if("Excluir".equalsIgnoreCase(cmd)){
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
Livro l = control.pesquisarLivroPorTombo(txtTombo.getText());
if (l!=null){
txtIdLivro.setText(String.valueOf(l.getIdLivro()));
txtTombo.setText(l.getTombo());
txtTitulo.setText(l.getTitulo());
txtTituloInternacional.setText(l.getTituloInternacional());
txtEdicao.setText(l.getEdicao());
txtEditora.setText(l.getEditora());
txtAutor.setText(l.getAutor());
}
}
else if (!txtAutor.getText().equals("")){
encontrados = control.pesquisarLivroPorAutor(txtAutor.getText());
if (encontrados!= null){
for (Livro dados : encontrados){
Object[] row = new Object[6];
row[0] = dados.getTombo();
row[1] = dados.getTitulo();
row[2] = dados.getTituloInternacional();
row[3] = dados.getEdicao();
row[4]= dados.getAutor();
row[5]= dados.getEditora();
modeloTabela.addRow(row);
}
painelTabela.setVisible(true);
painelPrincipal.repaint();
this.pack();
}
}
else {
//the same
}
}
}
public static void main(String[] args) {
new LivroView();
}
}
Thank you so much for the help!
Related
This code was taken from my original code and modified for testing purposes.
Question: Why is it that after clicking on a JComboBox, I cannot click on any other JComboBoxes?
Purpose: After clicking on the JComboBox, the selection gets copied down to the JTextField.
I have read many other posts on StackOverflow and made those changes accordingly, yet they have not solved the problem.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Test implements ActionListener {
JComboBox[] cb;
JTextField[] text = new JTextField[3];
JFrame frame2;
public static void main(String[] args) {
Test t = new Test();
t.changeEntry();
}
private void changeEntry() {
frame2 = new JFrame();
frame2.setLayout(new BorderLayout());
Panel p = new Panel();
p.setLayout(new GridLayout(3, 3));
initialize(p);
JTextField url = new JTextField();
JTextField username = new JTextField();
JPasswordField password = new JPasswordField();
addTextField(p, 0, url);
addTextField(p, 1, username);
addPassField(p, 2, password);
frame2.add(p, "Center");
frame2.setTitle("Entries");
frame2.setVisible(true);
frame2.setSize(500, 500);
frame2.setLocation(430, 100);
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private void initialize(Panel p) {
String[] array1 = {"A"};
String[] array2 = {"B"};
String[] array3 = {"C"};
JComboBox aa = new JComboBox<String>(array1);
JComboBox bb = new JComboBox<String>(array2);
JComboBox cc = new JComboBox<String>(array3);
cb = new JComboBox[3];
cb[0] = aa;
cb[0].addActionListener(this);
cb[0].setActionCommand("A");
cb[1] = bb;
cb[1].addActionListener(this);
cb[1].setActionCommand("B");
cb[2] = cc;
cb[2].addActionListener(this);
cb[2].setActionCommand("C");
p.add(cb[0]);
p.add(cb[1]);
p.add(cb[2]);
}
#Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("A")) {
checkSelection(cb[0], 0);
} else if (s.equals("B")) {
checkSelection(cb[1], 1);
} else if (s.equals("C")) {
checkSelection(cb[2], 2);
}
}
private void checkSelection(JComboBox cb, int i) {
String str = (String) cb.getSelectedItem();
text[i].setText(str);
}
private void addTextField(Container c, int i, JTextField tf) {
tf.setText("Edit entry here");
tf.setEditable(true);
c.add(tf);
text[i] = tf;
}
private void addPassField(Container c, int i, JPasswordField pf) {
pf.setText("test");
pf.setEditable(true);
c.add(pf);
text[i] = pf;
}
}
My professor and I looked over the code and found out that JComboBoxes do not like overlapping with JTextFields. This is the modification to the code that makes the error go away:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Test implements ActionListener {
JComboBox[] cb;
JTextField[] text = new JTextField[3];
JFrame frame2;
public static void main(String[] args) {
Test t = new Test();
t.changeEntry();
}
private void changeEntry() {
frame2 = new JFrame();
frame2.setLayout(new BorderLayout());
Panel p = new Panel();
p.setLayout(new GridLayout(2, 3));
JTextField url = new JTextField();
JTextField username = new JTextField();
JPasswordField password = new JPasswordField();
addTextField(p, 0, url);
addTextField(p, 1, username);
addPassField(p, 2, password);
initialize(p);
frame2.add(p, "Center");
frame2.setTitle("Entries");
frame2.setVisible(true);
frame2.setSize(500, 500);
frame2.setLocation(430, 100);
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private void initialize(Panel p) {
String[] array1 = {"A"};
String[] array2 = {"B"};
String[] array3 = {"C"};
JComboBox aa = new JComboBox<String>(array1);
JComboBox bb = new JComboBox<String>(array2);
JComboBox cc = new JComboBox<String>(array3);
cb = new JComboBox[3];
cb[0] = aa;
cb[0].addActionListener(this);
cb[0].setActionCommand("A");
cb[1] = bb;
cb[1].addActionListener(this);
cb[1].setActionCommand("B");
cb[2] = cc;
cb[2].addActionListener(this);
cb[2].setActionCommand("C");
p.add(cb[0]);
p.add(cb[1]);
p.add(cb[2]);
}
#Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("A")) {
checkSelection(cb[0], 0);
} else if (s.equals("B")) {
checkSelection(cb[1], 1);
} else if (s.equals("C")) {
checkSelection(cb[2], 2);
}
}
private void checkSelection(JComboBox cb, int i) {
String str = (String) cb.getSelectedItem();
text[i].setText(str);
}
private void addTextField(Container c, int i, JTextField tf) {
tf.setText("Edit entry here");
tf.setEditable(true);
c.add(tf);
text[i] = tf;
}
private void addPassField(Container c, int i, JPasswordField pf) {
pf.setText("test");
pf.setEditable(true);
c.add(pf);
text[i] = pf;
}
}
So, for anyone having this problem, look at the differences between my question and the modification:
p.setLayout(new GridLayout(3, 3));
initialize(p);
JTextField url = new JTextField();
JTextField username = new JTextField();
JPasswordField password = new JPasswordField();
addTextField(p, 0, url);
addTextField(p, 1, username);
addPassField(p, 2, password);
to
p.setLayout(new GridLayout(2, 3));
JTextField url = new JTextField();
JTextField username = new JTextField();
JPasswordField password = new JPasswordField();
addTextField(p, 0, url);
addTextField(p, 1, username);
addPassField(p, 2, password);
initialize(p);
I am trying to create a JList with some elements and when the user selects an element another JList will appear in the window. Then, if the user selects an element of the other list a text area will appear in the window. Here is what I have made so far :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class ProductsList extends JFrame implements ItemListener {
private JLabel availableDev;
private JComboBox avDevBox
private JTextArea itemDetails;
private JList Items;
private JList devicesForSale;
private JList imandSJList;
private JList applJList;
private JList gamJList;
public ProductsList() {
String[] avDevicesListItems = {"Image and Sound", "Appliance", "Gaming"};
ArrayList<imageAndSound> iasList = new ArrayList<imageAndSound>;
ArrayList<Appliance> applianceList = new ArrayList<Appliance>;
ArrayList<Gaming> gamingList = new ArrayList<Gaming>;
//construct components
availableDev = new JLabel ("Available Devices");
avDevicesList = new JList (avDevicesListItems);
itemDetails = new JTextArea (5, 5);
avDevBox = new JComboBox (avDevicesListItems);
devicesForSale = new JList(devList);
imandSJList = new JList(iasList);
applJList = new JList(applianceList);
gamJList = new JList(gamingList);
avDevBox.addItemListener(this);
//adjust size and set layout
setPreferredSize (new Dimension (944, 574));
setLayout (null);
//add components
add (availableDev);
add (avDevicesList);
add (itemDetails);
add (avDevBox);
add(devicesForSale);
//set component bounds
availableDev.setBounds (35, 0, 100, 25);
avDevBOx.setBounds (25, 30, 120, 25);
itemDetails.setBounds (245, 225, 265, 215);
public void itemStateChanged(ItemEvent event) {
int choice = avDevBox.getSelectedIndex();
if (choice = 0) {
add(imandSJList);
imandSJList.addItemListener(this);
}
else if (choice = 1){
add(applJList);
applJList.addItemListener(this);
}
else {
add(gamJList);
gamJList.addItemListener(this);
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("Products List");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel());
frame.pack();
frame.setVisible (true);
TV tv1 = new TV("LCD","28","720p","HDMI/DVI","11235","AT142","2015","SONY",500,5); //Creates object of class TV
TV tv2 = new TV("LED","32","1080p","HDMI/DVI","15394","AT168","2016","SAMSUNG",1000,0); //Creates object of class TV
bluerayDVD dvd = new bluerayDVD("DVD","720p","DVD-RW","15642","TT172","2015","SONY",400,100); //Creates object of class bluerayDVD
bluerayDVD blueray = new bluerayDVD("blueray","1080p","BD-R","18412","TT100","2015","SONY",500,1000); //Creates object of class bluerayDVD
Camera cam1 = new Camera("DSLR","50","stable","x5","2","19785","TC137","2016","SONY",600,50); //Creates object of class Camera
Camera cam2 = new Camera("compact,","40","stable","x7","1","16783","TC108","2016","SONY",700,70); //Creates object of class Camera
Console c1 = new Console("PS4","RGEN","1080p","Dolby","1 TB","15641","TG142","2016","SONY",400,80); //Creates object of class Console
Console c2 = new Console("XBOX","RGEN2","1080p","Dolby Digital","2 TB","13424","TG123","2016","MICROSOFT",400,10); //Creates object of class Console
Refrigerator f1 = new Refrigerator("Single door","C++","5kg","2kg","28756","TF357","2016","BOSS",1500,10); //Creates object of class Refrigerator
Refrigerator f2 = new Refrigerator("Double door","C++","8kg","4kg","26756","TF382","2016","SIEMENS",500,5); //Creates object of class Refrigerator
WashMachines wM1 = new WashMachines("C++","2kg","200rs","49356","TW364","2016","SIEMENS",3000,10); //Creates object of class WashMachines
WashMachines wM2 = new WashMachines("C++","4kg","250rs","49579","TW376","2016","BOSS",5000,10); //Creates object of class WashMachines
imandSJList.add(tv1);
imandSJList.add(tv2);
imandSJList.add(dvd);
imandSJList.add(blueray);
imandSJList.add(cam1);
imandSJList.add(cam2);
gamJList.add(c1);
gamJList.add(c2);
applJList.add(f1);
applJList.add(f2);
applJList.add(wM1);
applJList.add(wM2);
}
}
So if any body could suggest a better way, I would be very glad
Thank You
Similarly you can keep on adding listener directly to each list
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListDemo extends JFrame {
public JListDemo() {
setSize(new Dimension(300, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
final JLabel label = new JLabel("Update");
String[] data = { "one", "two", "three", "four" };
final JList dataList = new JList(data);
dataList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent arg0) {
if (!arg0.getValueIsAdjusting()) {
label.setText(dataList.getSelectedValue().toString());
}
}
});
add(dataList);
add(label);
setVisible(true);
}
public static void main(String args[]) {
new JListDemo();
}
}
I have been trying to get my JApplet to show all the buttons needed for a calculator applet in an orderly fashion, but I can't seem to get them to all be the same size and display right under each other. Should I use different a different layout or change the entire design? Thanks in advance.
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyCalc extends JApplet implements ActionListener{
/**
*
*/
protected static final long serialVersionUID = 3169756252830354073L;
private JMenuBar menuBar = new JMenuBar();
private JMenu edit = new JMenu("Edit");
private JMenu view = new JMenu("View");
private JMenu help = new JMenu("Help");
//Instantiated all JPanels used in this Applet
private JPanel[] rows = {new JPanel(), new JPanel(), new JPanel(),
new JPanel(), new JPanel(), new JPanel(), new JPanel()};
JTextField calc = new JTextField(1);
private JButton[] buttons = {new JButton("Backspace"), new JButton("CE"), new JButton("C"),
new JButton("MC"), new JButton("7"), new JButton("8"), new JButton("9"),
new JButton("/"), new JButton("sqrt"), new JButton("MR"), new JButton("4"),
new JButton("5"), new JButton("6"), new JButton("*"), new JButton("%"),
new JButton("MS"), new JButton("1"), new JButton("2"), new JButton("3"),
new JButton("-"), new JButton("1/x"), new JButton("M+"), new JButton("0"),
new JButton("+/-"), new JButton("."), new JButton("+"), new JButton("=")};
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttons[0])
{
}
}
public void init()
{
setName("Calculator Applet");
menuBar.add(edit);
menuBar.add(view);
menuBar.add(help);
setJMenuBar(menuBar);
rows[0].setLayout(new BoxLayout(rows[0], BoxLayout.Y_AXIS));
getContentPane();
add(rows[0]);
setSize(300, 200);
calc.setText("0.");
calc.setHorizontalAlignment(JTextField.RIGHT);
for(int i = 0; i < 3; i++)
{
rows[2].add(buttons[i]);
}
for(int i = 3; i < 9; i++)
{
rows[3].add(buttons[i]);
}
for(int i = 9; i < 15; i++)
{
rows[4].add(buttons[i]);
}
for(int i = 15; i < 21; i++)
{
rows[5].add(buttons[i]);
}
for(int i = 21; i < 26; i++)
{
rows[6].add(buttons[i]);
}
rows[1].add(calc);
rows[1].setLayout(new GridLayout());
rows[2].setLayout(new GridLayout());
rows[0].add(rows[1]);
rows[0].add(rows[2]);
for(int i = 3; i < 7; i++)
{
rows[0].add(rows[i]);
rows[i].setLayout(new FlowLayout(FlowLayout.CENTER));
}
}
"but I can't seem to get them to all be the same size and display right under each other."
Generally this screams out GridLayout. Instead of using two BoxLayout (one vertical and one horizinal) just use a GridLayout(4, 6) (for the number buttons). Keep in mind though that the size of the buttons will be the size of the largest button (which is sqrt).
Also I'd recommend staying away from keeping your panels in an array like you are doing. It's difficult to follow the flow of how you want to add everything. Give your panels (and all components for that matter) meaningful names that are self-documenting.
For general knowledge on layout managers, check out Laying out Component Within a Container
I refactored your code to be able to run it as an applet or as a standalone frame. I also wrapped all the components in a panel and set the layout manager of the content pane to GridBagLayout, so everything does get screwed up if you resize the frame
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyCalc extends JApplet implements ActionListener {
/**
*
*/
protected static final long serialVersionUID = 3169756252830354073L;
private JMenuBar menuBar = new JMenuBar();
private JMenu edit = new JMenu("Edit");
private JMenu view = new JMenu("View");
private JMenu help = new JMenu("Help");
// Instantiated all JPanels used in this Applet
//private JPanel[] rows = { new JPanel(), new JPanel(), new JPanel(),
// new JPanel(), new JPanel(), new JPanel(), new JPanel() };
JTextField calc = new JTextField(1);
private JButton[] buttons = { new JButton("Backspace"), new JButton("CE"),
new JButton("C"), new JButton("MC"), new JButton("7"),
new JButton("8"), new JButton("9"), new JButton("/"),
new JButton("sqrt"), new JButton("MR"), new JButton("4"),
new JButton("5"), new JButton("6"), new JButton("*"),
new JButton("%"), new JButton("MS"), new JButton("1"),
new JButton("2"), new JButton("3"), new JButton("-"),
new JButton("1/x"), new JButton("M+"), new JButton("0"),
new JButton("+/-"), new JButton("."), new JButton("+"),
new JButton("=") };
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttons[0]) {
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
MyCalc calc = new MyCalc();
calc.init();
frame.add(calc);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public void init() {
setName("Calculator Applet");
menuBar.add(edit);
menuBar.add(view);
menuBar.add(help);
setJMenuBar(menuBar);
Container contentPane = getContentPane();
calc.setText("0.");
calc.setHorizontalAlignment(JTextField.RIGHT);
JPanel topButtonPanel = new JPanel(new GridLayout(1, 0));
for (int i = 0; i < 3; i++) {
topButtonPanel.add(buttons[i]);
}
JPanel numberButtonPanel = new JPanel(new GridLayout(4, 6));
for (int i = 3; i < 26; i++) {
numberButtonPanel.add(buttons[i]);
}
JPanel centerWrapper = new JPanel(new BorderLayout());
centerWrapper.add(calc, BorderLayout.PAGE_START);
centerWrapper.add(topButtonPanel);
centerWrapper.add(numberButtonPanel, BorderLayout.PAGE_END);
contentPane.setLayout(new GridBagLayout());
contentPane.add(centerWrapper);
}
}
I am creating a simple messenger in Java(just for learning purposes) and I am trying to have a friends tab that, on the left side is the list of friends, and the right side is the messages with the friend that you click on, but whenever I try to add the JSplitPane in the tab, but it doesn't display. I have done this exact same code(except I only did the JSplitPane stuff and its components, not the other tabs and the menus and such.
All my code
package Client;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane, friendChatScrollPane, friendListScrollPane;
JSplitPane friendsSplitPane;
JTextArea friendChatArea, testArea;
JTextField friendChatField, testField;
JList friendList;
Box box;
DefaultListModel friends;
public ClientMain() {
super("Messenger Client");
//Networking();
/** MAIN PANEL **/
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
/** TEST PANEL **/
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
/** FRIENDS PANEL **/
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
friends = new DefaultListModel();
//method here that retrieves users' friends from the server and adds them to the friends DefaultListModel
friends.addElement("Person1");
friends.addElement("Person2");
friendList = new JList(friends);
friendList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
friendList.setLayoutOrientation(JList.VERTICAL_WRAP);
friendList.setVisibleRowCount(3);
friendList.setSize(50, 50);
friendChatArea = new JTextArea();
friendChatArea.setSize(50, 50);
friendChatArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
friendChatArea.append("TEST");
Dimension minimumSize = new Dimension(100, 50);
friendListScrollPane = new JScrollPane(friendList);
friendListScrollPane.setMinimumSize(minimumSize);
friendChatScrollPane = new JScrollPane(friendChatArea);
friendChatScrollPane.setMinimumSize(minimumSize);
friendsSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, friendListScrollPane, friendChatScrollPane);
friendsSplitPane.setOneTouchExpandable(false);
friendsSplitPane.setDividerLocation(50);
friendsPanel.add(friendsSplitPane);
/** TEST PANEL **/
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
/** SET UP **/
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void createSplitPane() {
friendListScrollPane = new JScrollPane();
friendListScrollPane.add(new JLabel("Hello"));
friendChatArea = new JTextArea();
friendChatArea.setBounds(0, 150, HEIGHT, HEIGHT);
friendChatArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
Dimension minimumSize = new Dimension(WIDTH/2 , HEIGHT);
friendListScrollPane.setMinimumSize(minimumSize);
//friendsSplitPane.setLeftComponent()
friendsSplitPane.add(friendChatArea);
friendsSplitPane.setRightComponent(friendChatScrollPane);
}
}
The specific JSplitPane code(part of the code above)
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
friends = new DefaultListModel();
//method here that retrieves users' friends from the server and adds them to the friends DefaultListModel
friends.addElement("Person1");
friends.addElement("Person2");
friendList = new JList(friends);
friendList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
friendList.setLayoutOrientation(JList.VERTICAL_WRAP);
friendList.setVisibleRowCount(3);
friendList.setSize(50, 50);
friendChatArea = new JTextArea();
friendChatArea.setSize(50, 50);
friendChatArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
friendChatArea.append("TEST");
Dimension minimumSize = new Dimension(100, 50);
friendListScrollPane = new JScrollPane(friendList);
friendListScrollPane.setMinimumSize(minimumSize);
friendChatScrollPane = new JScrollPane(friendChatArea);
friendChatScrollPane.setMinimumSize(minimumSize);
friendsSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, friendListScrollPane, friendChatScrollPane);
friendsSplitPane.setOneTouchExpandable(false);
friendsSplitPane.setDividerLocation(50);
friendsPanel.add(friendsSplitPane);
friendsPanel.setLayout(null);
your friendsPanel has the null layout and you are adding split pane as:
friendsPanel.add(friendsSplitPane);
to add a component to a container(friendsPanel) with null layout, you must specify the bound of the component you are adding with component.setBounds() method. But seriously why are even using null layout ? Don't use it. It has been already advice from page to page in by the swing family of stack overflow. Try to use one of the layout manager the Swing developer has created for us with effort wasting time from day after day just to save our own time.
Start learning : Lesson: Laying Out Components Within a Container. Let us give some value their efforts for saving our time, which we are spending just to find the answer: uhh! where is my component!?!
I've searched through the forums but keep coming up empty for a solution.
I'm making a sort of library with a GUI program. What I want is for it to save entries via a text file. I can create objects fine with the methods I have, and can save them to a file easily. The problem comes from starting up the program again and populating a Vector with values in the text file. The objects I'm adding have a String value, followed by 7 booleans. When I try to load up from file, the String value is empty ("") and all booleans are false.
How do I get it to read the text before starting the rest of the GUI and filling the Vector right?
EDIT: Sorry for being very vague about it all. I'll post the code, but it's about 337 lines long..
import java.awt.Container;
import java.awt.FlowLayout;
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.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class SteamLibraryGUI extends JFrame implements ActionListener
{
//For main window
private JButton exitButton, addEntry, editEntry, removeEntry;
private JLabel selectGame, gameCount;
private JComboBox<String> gameCombo;
private Vector<Game> gamesList = new Vector<Game>();
private Vector<String> titleList = new Vector<String>();
private int numGames = gamesList.size();
private int selectedGame;
//For add window
private JFrame addFrame;
private JLabel gameTitle = new JLabel("Title:");
private JTextField titleText = new JTextField(60);
private JCheckBox singleBox, coopBox, multiBox, cloudBox, controllerBox, achieveBox, pcBox;
private JButton addGame, addCancel;
//For edit window
private JFrame editFrame;
private JButton editGame, editCancel;
public SteamLibraryGUI()
{
setTitle("Steam Library Organizer");
addEntry = new JButton("Add a game");
editEntry = new JButton("Edit a game");
removeEntry = new JButton("Remove a game");
exitButton = new JButton("Exit");
selectGame = new JLabel("Select a game:");
gameCount = new JLabel("Number of games:"+numGames);
gameCombo = new JComboBox<String>(titleList);
JPanel selectPanel = new JPanel();
selectPanel.setLayout(new GridLayout(1,2));
selectPanel.add(selectGame);
selectPanel.add(gameCombo);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,3));
buttonPanel.add(addEntry);
buttonPanel.add(editEntry);
buttonPanel.add(removeEntry);
JPanel exitPanel = new JPanel();
exitPanel.setLayout(new GridLayout(1,2));
exitPanel.add(gameCount);
exitPanel.add(exitButton);
Container pane = getContentPane();
pane.setLayout(new GridLayout(3,1));
pane.add(selectPanel);
pane.add(buttonPanel);
pane.add(exitPanel);
addEntry.addActionListener(this);
editEntry.addActionListener(this);
removeEntry.addActionListener(this);
exitButton.addActionListener(this);
gameCombo.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==addEntry)
addEntry();
if(e.getSource()==editEntry)
editEntry(gamesList.get(selectedGame));
if(e.getSource()==removeEntry)
{
removeEntry(selectedGame);
update();
}
if(e.getSource()==exitButton)
exitProg();
if(e.getSource()==gameCombo)
{
selectedGame = gameCombo.getSelectedIndex();
}
if(e.getSource()==singleBox)
singleBox.isSelected();
if(e.getSource()==coopBox)
coopBox.isSelected();
if(e.getSource()==multiBox)
multiBox.isSelected();
if(e.getSource()==cloudBox)
cloudBox.isSelected();
if(e.getSource()==controllerBox)
controllerBox.isSelected();
if(e.getSource()==achieveBox)
achieveBox.isSelected();
if(e.getSource()==pcBox)
pcBox.isSelected();
if(e.getSource()==addGame)
{
gamesList.add(new Game(titleText.getText(), singleBox.isSelected(), coopBox.isSelected(),
multiBox.isSelected(), cloudBox.isSelected(), controllerBox.isSelected(),
achieveBox.isSelected(), pcBox.isSelected()));
titleList.add(titleText.getText());
addFrame.dispose();
update();
}
if(e.getSource()==addCancel)
addFrame.dispose();
if(e.getSource()==editCancel)
editFrame.dispose();
if(e.getSource()==editGame)
{
gamesList.get(selectedGame).name = titleText.getText();
gamesList.get(selectedGame).single = singleBox.isSelected();
gamesList.get(selectedGame).coop = coopBox.isSelected();
gamesList.get(selectedGame).multi = multiBox.isSelected();
gamesList.get(selectedGame).cloud = cloudBox.isSelected();
gamesList.get(selectedGame).controller = controllerBox.isSelected();
gamesList.get(selectedGame).achieve = achieveBox.isSelected();
gamesList.get(selectedGame).pc = pcBox.isSelected();
titleList.remove(selectedGame);
titleList.add(titleText.getText());
editFrame.dispose();
update();
}
}
public void update()
{
Collections.sort(titleList);
Collections.sort(gamesList);
gameCombo.updateUI();
titleText.setText("");
gameCombo.setSelectedIndex(-1);
numGames = gamesList.size();
gameCount.setText("Number of games:"+numGames);
}
public void addEntry()
{
addFrame = new JFrame("Add Entry");
addFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
addFrame.getContentPane();
addFrame.setLayout(new GridLayout(3,1));
singleBox = new JCheckBox("Single-Player");
singleBox.setSelected(false);
coopBox = new JCheckBox("Coop");
coopBox.setSelected(false);
multiBox = new JCheckBox("MultiPlayer");
multiBox.setSelected(false);
cloudBox = new JCheckBox("Steam Cloud");
cloudBox.setSelected(false);
controllerBox = new JCheckBox("Controller Support");
controllerBox.setSelected(false);
achieveBox = new JCheckBox("Achievements");
achieveBox.setSelected(false);
pcBox = new JCheckBox("For New PC");
pcBox.setSelected(false);
addGame = new JButton("Add game");
addCancel = new JButton("Cancel");
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(gameTitle);
titlePanel.add(titleText);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new FlowLayout());
checkPanel.add(singleBox);
checkPanel.add(coopBox);
checkPanel.add(multiBox);
checkPanel.add(cloudBox);
checkPanel.add(controllerBox);
checkPanel.add(achieveBox);
checkPanel.add(pcBox);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(addGame);
buttonPanel.add(addCancel);
addFrame.add(titlePanel);
addFrame.add(checkPanel);
addFrame.add(buttonPanel);
singleBox.addActionListener(this);
coopBox.addActionListener(this);
multiBox.addActionListener(this);
cloudBox.addActionListener(this);
controllerBox.addActionListener(this);
achieveBox.addActionListener(this);
pcBox.addActionListener(this);
addGame.addActionListener(this);
addCancel.addActionListener(this);
addFrame.pack();
addFrame.setVisible(true);
}
public void editEntry(Game g)
{
editFrame = new JFrame("Edit Entry");
editFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
editFrame.getContentPane();
editFrame.setLayout(new GridLayout(3,1));
singleBox = new JCheckBox("Single-Player");
singleBox.setSelected(g.single);
coopBox = new JCheckBox("Coop");
coopBox.setSelected(g.coop);
multiBox = new JCheckBox("MultiPlayer");
multiBox.setSelected(g.multi);
cloudBox = new JCheckBox("Steam Cloud");
cloudBox.setSelected(g.cloud);
controllerBox = new JCheckBox("Controller Support");
controllerBox.setSelected(g.controller);
achieveBox = new JCheckBox("Achievements");
achieveBox.setSelected(g.achieve);
pcBox = new JCheckBox("For New PC");
pcBox.setSelected(g.pc);
editGame = new JButton("Edit game");
editCancel = new JButton("Cancel");
titleText.setText(g.name);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(gameTitle);
titlePanel.add(titleText);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new FlowLayout());
checkPanel.add(singleBox);
checkPanel.add(coopBox);
checkPanel.add(multiBox);
checkPanel.add(cloudBox);
checkPanel.add(controllerBox);
checkPanel.add(achieveBox);
checkPanel.add(pcBox);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(editGame);
buttonPanel.add(editCancel);
editFrame.add(titlePanel);
editFrame.add(checkPanel);
editFrame.add(buttonPanel);
singleBox.addActionListener(this);
coopBox.addActionListener(this);
multiBox.addActionListener(this);
cloudBox.addActionListener(this);
controllerBox.addActionListener(this);
achieveBox.addActionListener(this);
pcBox.addActionListener(this);
editGame.addActionListener(this);
editCancel.addActionListener(this);
editFrame.pack();
editFrame.setVisible(true);
}
public void removeEntry(int g)
{
Object[] options = {"Yes, remove the game", "No, keep the game"};
int n = JOptionPane.showOptionDialog(null, "Are you sure you want to remove this game from the list?",
"Remove game?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
if (n==0)
{
gamesList.remove(g);
titleList.remove(g);
}
}
public void exitProg()
{
try
{
PrintWriter out = new PrintWriter("games.txt");
out.flush();
for(int i=0;i<gamesList.size();i++)
{
out.print(gamesList.get(i).toString());
}
out.close();
}
catch (FileNotFoundException e) {}
System.exit(0);
}
public static void main(String[] args)
{
SteamLibraryGUI frame = new SteamLibraryGUI();
frame.pack();
frame.setSize(600,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Scanner in = new Scanner("games.txt");
while(in.hasNextLine())
{
String line = in.nextLine();
String[] options = line.split("|");
Game g = new Game(options[0],Boolean.getBoolean(options[1]),
Boolean.getBoolean(options[2]),Boolean.getBoolean(options[3]),
Boolean.getBoolean(options[4]),Boolean.getBoolean(options[5]),
Boolean.getBoolean(options[6]),Boolean.getBoolean(options[7]));
frame.gamesList.add(g);
frame.titleList.add(options[0]);
System.out.println(g.toString());
}
in.close();
}
}
There's also a Game class, but it's simply 1 String, and then 7 booleans.
There were two significant bugs in the code. First, Scanner was constructed with a string parameter (which means that the Scanner scanned the string, not the file named by the string). Second, the pipe character "|" is a regular expression metacharacter. That is important because line.split() splits on regular expressions. Thus, the "|" has to be escaped. The main() function works fine if it is written as follows (with debugging output code included to show that each step is working correctly):
public static void main(String[] args)
{
SteamLibraryGUI frame = new SteamLibraryGUI();
frame.pack();
frame.setSize(600,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try
{
Scanner in = new Scanner(new File("games.txt"));
while(in.hasNextLine())
{
System.out.println("line = ");
String line = in.nextLine();
System.out.println(line);
String[] options = line.split("\\|");
System.out.println("Options = ");
for (String s : options)
{
System.out.println(s);
}
Game g = new Game(options[0],Boolean.getBoolean(options[1]),
Boolean.getBoolean(options[2]),Boolean.getBoolean(options[3]),
Boolean.getBoolean(options[4]),Boolean.getBoolean(options[5]),
Boolean.getBoolean(options[6]),Boolean.getBoolean(options[7]));
frame.gamesList.add(g);
frame.titleList.add(options[0]);
System.out.println(g.toString());
}
in.close();
} catch (IOException x)
{
System.err.println(x);
}
}
There is one other important Gotcha: The method exitProg() writes the "games.txt" file out again before the program finishes. This creates a problem if the file was read incorrectly in the first place because the wrong data will be written back to the file. During testing, this means that even when the reading code has been corrected, it will still read the erroneous data that was written from a previous test run.
My preference in this situation is would be to isolate all the reading and writing code for "game.txt" inside the Game class (which makes it easier to verify that the reading and writing formats are identical) and only write the code to write the data back out once I'd written and tested the reading code, which would avoid this Gotcha.