How to read text file before GUI program runs - java

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.

Related

Why is my JSlider not changing the value?

I am trying to make my program so that an integer value entered in a JTextfield can be stored into a variable. Then, when a JButton is clicked, this variable can tell a JSlider to move it's head to that of the integer value stored in the variable. My class name is Camera.Java
Code is showing no errors, however if I click my JButton, nothing happens, instead I see this error in the console:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at Camera.main(Camera.java:67)
My code:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.*;
public class Camera {
static JButton addtolist;
static Scanner input = new Scanner(System.in);
static JSlider cam = new JSlider();
static JTextField enterval = new JTextField();
static int x ;
public static void main (String args[]){
JFrame myFrame = new JFrame ("Matthew Damon on Mars");
myFrame.setSize(300, 600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel userinp = new JLabel("Enter input: ");
cam = new JSlider(0, 15, 0);
cam.setPaintLabels(true);
enterval.setPreferredSize(new Dimension(100,80));
addtolist = new JButton("Enter");
addtolist.setPreferredSize(new Dimension(50,20));
JTextField enterval1 = new JTextField();
panel.add(addtolist);
Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
table.put(0, new JLabel("0"));
table.put(1, new JLabel("1"));
table.put(2, new JLabel("2"));
table.put(3, new JLabel("3"));
table.put(4, new JLabel("4"));
table.put(5, new JLabel("5"));
table.put(6, new JLabel("6"));
table.put(7, new JLabel("7"));
table.put(8, new JLabel("8"));
table.put(9, new JLabel("9"));
table.put(10, new JLabel("A"));
table.put(11, new JLabel("B"));
table.put(12, new JLabel("C"));
table.put(13, new JLabel("D"));
table.put(14, new JLabel("E"));
table.put(15, new JLabel("F"));
cam.setLabelTable(table);
myFrame.add(cam, BorderLayout.SOUTH);
myFrame.add(userinp, BorderLayout.NORTH);
myFrame.add(enterval1, BorderLayout.NORTH);
myFrame.add(panel, BorderLayout.CENTER);
myFrame.setVisible(true);
buttonAction();
}
public static void buttonAction() {
addtolist.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
});
}
}
Your setting x on program creation before the user has had any chance to change its value. Get the text value from within the actionPerformed method which should be after the user has already selected a value, parse it into a number and set the slider with that value.
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
Then get rid of all that static nonsense. The only method that should be static here is main, and it should do nothing but create an instance and set it visible.
Note that better than using a JTextField, use a JSpinner or a JFormattedTextField or if you're really stuck, a DocumentFilter to limit what the user can enter
Again, you should put most everything into the instance realm and out of the static realm. This means getting most of that code outside of the main method and into other methods and constructors, that means not trying to access fields or methods from the class, but rather from the instance. For instance, your main method should only create the main instances, hook them up and set them running and that's it. It should not be used to build the specific GUI components. For example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class CameraFoo extends JPanel {
// only static field here is a constant.
private static String TEXTS = "0123456789ABCDEF";
private JSpinner spinner = new JSpinner();
private JSlider slider = new JSlider(0, 15, 0);
public CameraFoo() {
List<Character> charList = new ArrayList<>();
Hashtable<Integer, JLabel> table = new Hashtable<>();
for (int i = 0; i < TEXTS.toCharArray().length; i++) {
char c = TEXTS.charAt(i);
String myText = String.valueOf(c);
JLabel label = new JLabel(myText);
table.put(i, label);
charList.add(c);
}
SpinnerListModel spinnerModel = new SpinnerListModel(charList);
spinner.setModel(spinnerModel);
slider.setLabelTable(table);
slider.setPaintLabels(true);
JPanel topPanel = new JPanel();
topPanel.add(spinner);
topPanel.add(new JButton(new ButtonAction("Press Me")));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(slider);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
char ch = (char) spinner.getValue();
int value = TEXTS.indexOf(ch);
slider.setValue(value);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
CameraFoo mainPanel = new CameraFoo();
JFrame frame = new JFrame("CameraFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}

Why my JTable isn't showing?

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!

Jpanels don't show up as defined size

Hello while trying to build my Java GUI I keep running across the problem that my JPanels keep resizing or they just show up as small collapsed squares. I defined the size of each JPanel using the setSize() method.
This is what I'm getting
And this is more of what i'm trying to build
This is my code. I guess my question is how to stop the JPanels from resizing and sticking to their widths defined by the setSize() method.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import javaQuery.j2ee.GeoLocation;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class iPerf extends JFrame implements ActionListener{
private static final int JFrame_W = 437;
private static final int JFrame_H = 586;
private static final int titlePanel_W = 437;
private static final int titlePanel_H = 46;
private static final int locationPanel_W = 437;
private static final int locationPanel_H = 46;
private static final int buttonPanel_W = 437;
private static final int buttonPanel_H = 47;
private static final int resultsPanel_W = 437;
private static final int resultsPanel_H = 444;
private static final int outputPanel_W = 371;
private static final int outputPanel_H = 172;
JPanel titlePanel = new JPanel();
JPanel locationPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel resultsPanel = new JPanel();
JPanel pingResultsPanel = new JPanel();
JPanel iperfResultsPanel = new JPanel();
JLabel iperfTitle = new JLabel("iPerf");
JLabel cityTitleLabel = new JLabel("City");
JLabel cityResultLabel = new JLabel("");
JLabel countryTitleLabel = new JLabel("Country");
JLabel countryResultLabel = new JLabel("");
JLabel latitudeTitleLabel = new JLabel("Latitude");
JLabel latitudeResultLabel = new JLabel("");
JLabel longitudeTitleLabel = new JLabel("Longitude");
JLabel longitudeResultLabel = new JLabel("");
JScrollPane pingResultsScrollPane = new JScrollPane();
JScrollPane iPerfResultsScrollPane = new JScrollPane();
String results;
JTextArea label = new JTextArea(results);
JButton runButton = new JButton("Run iPerf");
public static void main(String[] args){
iPerf w = new iPerf( );
w.setVisible(true);
w.setResizable(false);
w.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public iPerf() {
super();
setSize(JFrame_W, JFrame_H);
setTitle("iPerf");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Title Panel
titlePanel.setSize(titlePanel_W, titlePanel_H);
titlePanel.setBackground(Color.darkGray);
titlePanel.add(iperfTitle);
add(titlePanel);
//Location Panel
locationPanel.setSize(locationPanel_W, locationPanel_H);
locationPanel.setBackground(Color.LIGHT_GRAY);
locationPanel.setLayout(new GridLayout(2, 4));
locationPanel.add(cityTitleLabel);
locationPanel.add(countryTitleLabel);
locationPanel.add(latitudeTitleLabel);
locationPanel.add(longitudeTitleLabel);
locationPanel.add(cityResultLabel);
locationPanel.add(countryResultLabel);
locationPanel.add(latitudeResultLabel);
locationPanel.add(longitudeResultLabel);
add(locationPanel);
//Button Panel
buttonPanel.setSize(buttonPanel_W, buttonPanel_H);
buttonPanel.setBackground(Color.LIGHT_GRAY);
buttonPanel.setLayout(new FlowLayout());
runButton.addActionListener(this);
buttonPanel.add(runButton);
add(buttonPanel);
//Results Panel
resultsPanel.setSize(resultsPanel_W, resultsPanel_H);
resultsPanel.setBackground(Color.darkGray);
resultsPanel.setLayout(new FlowLayout());
pingResultsPanel.setSize(outputPanel_W, outputPanel_H);
pingResultsPanel.setBackground(Color.WHITE);
pingResultsPanel.setLayout(new FlowLayout());
iperfResultsPanel.setSize(outputPanel_W, outputPanel_H);
iperfResultsPanel.setBackground(Color.WHITE);
iperfResultsPanel.setLayout(new FlowLayout());
iPerfResultsScrollPane.setViewportView(label);
iperfResultsPanel.add(iPerfResultsScrollPane);
resultsPanel.add(pingResultsPanel);
resultsPanel.add(iperfResultsPanel);
add(resultsPanel);
}
public void actionPerformed(ActionEvent e) {
String buttonString = e.getActionCommand();
if (buttonString.equals("Run iPerf")) {
System.out.println(buttonString + "it works!");
runIperfEastTCP iperfEastTCPThread = new runIperfEastTCP();
getLocation locationThread = new getLocation();
runPing pingThread = new runPing();
iperfEastTCPThread.start();
locationThread.start();
pingThread.start();
}
}
private class runPing extends Thread {
public void run() {
try {
String line;
Process p = Runtime.getRuntime().exec("/sbin/ping -c 4 www.google.com");
BufferedReader input = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
results += line + "\n";
label.setText(results);
System.out.println(line);
}
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class runIperfEastTCP extends Thread {
public void run() {
try {
String line = "";
Process p;
p = Runtime.getRuntime().exec("/usr/local/bin/iperf -c 184.72.222.65 -p 5001 -w 64k -P 4 -i 1 -t 10 -f k");
BufferedReader input = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
results += line + "\n";
label.setText(results);
System.out.println(line);
}
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class getLocation extends Thread {
public void run() {
try {
InetAddress thisIP = InetAddress.getLocalHost();
GeoLocation _gl = new GeoLocation();
_gl.GetGeoLocation(thisIP);
String IP = _gl.IP;
String Country = _gl.Country;
String City = _gl.City;
String Latitude = _gl.Latitude;
String Longitude = _gl.Longitude;
cityResultLabel.setText(City);
countryResultLabel.setText(Country);
latitudeResultLabel.setText(Latitude);
longitudeResultLabel.setText(Longitude);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Don't call setSize(...) on any component.
consider overriding getPreferredSize() if you absolutely need to set a size, but use it very sparingly.
You're not using layout managers correctly. Go through the layout manager tutorial as it will explain and show all that you need to know.
You need to call pack() on your JFrame after adding all components to it and before setting it visible or positioning it.
For example, you could...
Consider using BoxLayout for the overall structure
The top section could use a JLabel with the text centered.
The next section with the JLabels and JButton could use a BorderLayout
The BorderLayout could hold the JPanel that holds four labels/fields in the BorderLayout.CENTER position,
That same JPanel could use GridBagLayout.
the JPanel that holds the JButton could use a FlowLayout and be located in the BorderLayout.SOUTH or PAGE_END position of the BorderLayout-using JPanel.
Next JPanel can use a GridLayout with borders and gaps.
etc...
Try using another LayoutManager, like GridLayout.

Difficulty Activating BufferedReader Through JButton

I am looking for a quick fix to this problem I have: Here is my code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory{
public static void main(String args[]) throws IOException{
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300,300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(100,30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
String housetype = br.readLine();
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if(searchquery.equals(housetype)){
System.out.println("We Have Found A Record!!");
}}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
Basically After I wrote this code, Eclipse told me I had to change the modifier of housetype, to final. Which truly won't do, because I need to be a changing value if its going to go trough different records.
PLEASE HELP ME! D:
You have several options here:
The quickest would be to do what Eclipse tells you, actually it is Java that tells you that. In order to be able to use method local variables inside inner classes inside the method, the variables must be final.
Another option is to declare the housetype variable as an instance variable, immediately after the class definition. But, using it in the static main method means that the variable needs to be static too, which makes it a class variable.
Another one would be to keep the code as you have, but declare an extra variable like below and then use the house variable inside the inner class instead of housetype. See the entire code below:
public class Directory {
public static void main(String args[]) throws IOException {
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(100, 30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
final List<String> housetypes = new ArrayList<String>();
String line = "";
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
while (line != null) {
line = br.readLine();
housetypes.add(line);
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
}
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
for (String housetype : housetypes) {
if (searchquery.equals(housetype)) {
System.out.println("We Have Found A Record!!");
}
}
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
There are even more options, but these are the quickest.
One workaround is that you create a new method inside your class Directory that is being called from the ActionListener and does your tasks:
private void searchButtonAction() {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if(searchquery.equals(housetype)){
System.out.println("We Have Found A Record!!");
}
}
and then call it like this:
public void actionPerformed(ActionEvent ae)
{
searchButtonAction();
});
This only works if you create a constructor in the class and call it from the main method. Furthermore all variables used inside the searchButtonAction method must be class visible.
Full code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory {
private final JTextField searchfield = new JTextField();
private final JProgressBar searchprogress = new JProgressBar();
private String housetype;
public Directory() throws IOException {
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
searchfield.setPreferredSize(new Dimension(100, 30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
housetype = br.readLine();
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchButtonAction();
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private void searchButtonAction() {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if (searchquery.equals(housetype)) {
System.out.println("We Have Found A Record!!");
}
}
public static void main(String args[]) throws IOException {
new Directory();
}
}

Issues in Java Swing

i have created a Java program to save MAC Addresses to an external File. Below is the code:
import java.io.*;
public class MAC{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the MAC Addres : ");
File file = new File("mac.txt");
FileWriter fstream = new FileWriter("mac.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(in.readLine());
out.newLine();
out.close();
}
}
I have also created a Swing Application. I am done with the Front End, but now I can't save MAC address to a external file using swing.
In my ActionListener, I am getting the values, but I have no idea how to save the details to a external file.
I am able to print the ActionListener values to the screen, but I want it to be saved in the external file.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.io.*;
public class TextForm extends JPanel {
private JTextField[] fields;
// Create a form with the specified labels, tooltips, and sizes.
public TextForm(String[] labels, int[] widths) {
super(new BorderLayout());
JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));
add(labelPanel, BorderLayout.WEST);
add(fieldPanel, BorderLayout.CENTER);
fields = new JTextField[labels.length];
for (int i = 0; i < labels.length; i += 1) {
fields[i] = new JTextField();
if (i < widths.length)
fields[i].setColumns(widths[i]);
JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
lab.setLabelFor(fields[i]);
labelPanel.add(lab);
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
p.add(fields[i]);
fieldPanel.add(p);
}
}
public String getText(int i) {
return (fields[i].getText());
}
public static void main(String[] args) {
String[] labels = { "Enter MAC Address : "};
int[] widths = { 17 };
final TextForm form = new TextForm(labels, widths);
JButton submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(form.getText(0));
}
});
JFrame f = new JFrame("Text Form Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(form, BorderLayout.NORTH);
JPanel p = new JPanel();
p.add(submit);
f.getContentPane().add(p, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
}
Thank you.
Copy the working method into the actionPerformed method and swap.
out.write(in.readLine());
For:
out.write(form.getText(0));
Then wrap the lot of it in a try/catch.

Categories