Error connecting Jtable with mysql "java.lang.NullPointerException" - java

When I try to connect my application with MySQL, an exception is thrown: java.lang.NullPointerException.
The application then starts without a database. I debugged the program and the error is in: md.addRow(a).
The code is:
package inmobiliaria;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.RowFilter;
import javax.swing.RowSorter;
import javax.swing.SwingConstants;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import java.awt.Font;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.KeyAdapter;
import javax.swing.JFormattedTextField;
import java.awt.Component;
import javax.swing.Box;
import javax.swing.JRadioButton;
import java.awt.Toolkit;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.sql.*;
import java.util.ArrayList;
import java.util.Vector;
public class Ventana extends JFrame {
private JPanel contentPane;
private JTextField txtNumero;
private JTextField txtNombreDelInquilino;
private JTextField txtNombreDelPropietario;
private JTextField txtDomicilio;
private JTextField txtCantidad;
private JTextArea taObservacionesDos;
private JTable table;
DefaultTableModel md;
String dataaa[][] = {};
String columnasss[] = {"NUMERO", "FECHA DE ENTRADA", "FECHA DE VENCIMIENTO", "NOMBRE DEL INQUILINO", "NOMBRE DEL PROPIETARIO", "DOMICILIO", "CANTIDAD", "OBSERVACIONES"};
private JTextField txtFiltro;
private TableRowSorter<TableModel> trsfiltro;
private Connection connect = null;
private Statement statement = null;
//Autor Martìn Sànchez
//FACEBOOK: http://www.facebook.com/martin98sanchez
public void run() {
try {
Ventana frame = new Ventana();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the frame.
*/
public Ventana() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return;
}
try {
connect = DriverManager.getConnection("jdbc:mysql://127.0.0.1/inmobiliaria", "root", "");
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return;
}
try {
ResultSet rs = connect.getMetaData().getCatalogs();
} catch (SQLException e) { }
try {
statement = connect.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM usuarios");
// get columns info
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// add rows to table
while (rs.next()) {
String[] a = new String[columnCount];
for(int i = 0; i < columnCount; i++) {
a[i] = rs.getString(i+1);
}
md.addRow(a);
}
// Close ResultSet and Statement
rs.close();
statement.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex, ex.getMessage(), WIDTH, null);
}
setTitle("Inmobiliaria");
//setIconImage(Toolkit.getDefaultToolkit().getImage(Ventana.class.getResource("/imagenes/inmobiliaria.png")));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1325, 727);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtNumero = new JTextField();
txtNumero.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
if (!Character.isDigit(e.getKeyChar())){
e.consume();
}
}
});
txtNumero.setBounds(88, 26, 86, 20);
contentPane.add(txtNumero);
txtNumero.setColumns(10);
JLabel lblNumero = new JLabel("N\u00FAmero");
lblNumero.setBounds(22, 23, 56, 26);
contentPane.add(lblNumero);
JLabel lblFechaDeEntregaUno = new JLabel("Fecha de");
lblFechaDeEntregaUno.setHorizontalAlignment(SwingConstants.CENTER);
lblFechaDeEntregaUno.setBounds(22, 60, 56, 26);
contentPane.add(lblFechaDeEntregaUno);
JLabel lblFechaDeEntregaDos = new JLabel("ENTREGA");
lblFechaDeEntregaDos.setHorizontalAlignment(SwingConstants.CENTER);
lblFechaDeEntregaDos.setBounds(22, 82, 56, 14);
contentPane.add(lblFechaDeEntregaDos);
JComboBox cbDiaE = new JComboBox();
cbDiaE.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
cbDiaE.setBounds(98, 66, 50, 20);
contentPane.add(cbDiaE);
JComboBox cbMesE = new JComboBox();
cbMesE.setModel(new DefaultComboBoxModel(new String[] {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre"}));
cbMesE.setBounds(158, 66, 76, 20);
contentPane.add(cbMesE);
JComboBox cbAnioE = new JComboBox();
cbAnioE.setModel(new DefaultComboBoxModel(new String[] {"2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030"}));
cbAnioE.setBounds(244, 66, 56, 20);
contentPane.add(cbAnioE);
JLabel lblFechaDeVencimientoUno = new JLabel("Fecha de");
lblFechaDeVencimientoUno.setHorizontalAlignment(SwingConstants.CENTER);
lblFechaDeVencimientoUno.setBounds(22, 107, 56, 26);
contentPane.add(lblFechaDeVencimientoUno);
JLabel lblFechaDeVencimientoDos = new JLabel("VENCIMIENTO");
lblFechaDeVencimientoDos.setHorizontalAlignment(SwingConstants.CENTER);
lblFechaDeVencimientoDos.setBounds(22, 129, 76, 14);
contentPane.add(lblFechaDeVencimientoDos);
JComboBox cbDiaV = new JComboBox();
cbDiaV.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
cbDiaV.setBounds(98, 113, 50, 20);
contentPane.add(cbDiaV);
JComboBox cbMesV = new JComboBox();
cbMesV.setModel(new DefaultComboBoxModel(new String[] {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre"}));
cbMesV.setBounds(158, 113, 76, 20);
contentPane.add(cbMesV);
JComboBox cbAnioV = new JComboBox();
cbAnioV.setModel(new DefaultComboBoxModel(new String[] {"2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030"}));
cbAnioV.setBounds(244, 113, 56, 20);
contentPane.add(cbAnioV);
JLabel lblNombreDelInquilino = new JLabel("Nombre del Inquilino");
lblNombreDelInquilino.setBounds(22, 154, 109, 14);
contentPane.add(lblNombreDelInquilino);
JLabel lblNombreDelPropietario = new JLabel("Nombre del Propietario");
lblNombreDelPropietario.setBounds(22, 189, 137, 14);
contentPane.add(lblNombreDelPropietario);
txtNombreDelInquilino = new JTextField();
txtNombreDelInquilino.setBounds(158, 151, 130, 20);
contentPane.add(txtNombreDelInquilino);
txtNombreDelInquilino.setColumns(10);
txtNombreDelPropietario = new JTextField();
txtNombreDelPropietario.setBounds(158, 186, 129, 20);
contentPane.add(txtNombreDelPropietario);
txtNombreDelPropietario.setColumns(10);
JLabel lblDomicilio = new JLabel("Domicilio");
lblDomicilio.setBounds(22, 224, 76, 14);
contentPane.add(lblDomicilio);
txtDomicilio = new JTextField();
txtDomicilio.setBounds(100, 221, 200, 20);
contentPane.add(txtDomicilio);
txtDomicilio.setColumns(10);
JLabel lblCantidad = new JLabel("Cantidad");
lblCantidad.setBounds(22, 255, 76, 14);
contentPane.add(lblCantidad);
txtCantidad = new JTextField();
txtCantidad.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
if (!Character.isDigit(e.getKeyChar())){
//... no lo escribe
e.consume();
}
}
});
txtCantidad.setBounds(100, 252, 200, 20);
contentPane.add(txtCantidad);
txtCantidad.setColumns(10);
JLabel lblObservaciones = new JLabel("Observaciones");
lblObservaciones.setBounds(22, 280, 86, 14);
contentPane.add(lblObservaciones);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(110, 283, 204, 132);
contentPane.add(scrollPane);
JTextArea taObservaciones = new JTextArea();
scrollPane.setViewportView(taObservaciones);
JButton btnAceptar = new JButton("Aceptar");
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String numero = txtNumero.getText();
String nombreInquilino = txtNombreDelInquilino.getText();
String nombrePropietario = txtNombreDelPropietario.getText();
String domicilio = txtDomicilio.getText();
String cantidad = txtCantidad.getText();
String observaciones = taObservaciones.getText();
String dDE = cbDiaE.getSelectedItem().toString();
String mDE = cbMesE.getSelectedItem().toString();
String aDE = cbAnioE.getSelectedItem().toString();
String dDV = cbDiaV.getSelectedItem().toString();
String mDV = cbMesV.getSelectedItem().toString();
String aDV = cbAnioV.getSelectedItem().toString();
String fechaEntrada;
String fechaVencimiento;
fechaEntrada = dDE + " / " + mDE + " / " + aDE;
fechaVencimiento = dDV + " / " + mDV + " / " + aDV;
txtNumero.setText("");
txtNombreDelInquilino.setText("");
txtNombreDelPropietario.setText("");
txtDomicilio.setText("");
txtCantidad.setText("");
taObservaciones.setText("");
cbDiaE.setSelectedItem("1");
cbMesE.setSelectedItem("Enero");
cbDiaV.setSelectedItem("1");
cbMesV.setSelectedItem("Enero");
}
});
btnAceptar.setFont(new Font("Tahoma", Font.BOLD, 18));
btnAceptar.setBounds(98, 446, 189, 58);
contentPane.add(btnAceptar);
md = new DefaultTableModel(dataaa, columnasss);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(344, 11, 955, 493);
contentPane.add(scrollPane_1);
table = new JTable();
table.setAutoResizeMode(1);
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(md);
table.setRowSorter(sorter);
scrollPane_1.setViewportView(table);
table.setToolTipText("");
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"NUMERO", "FECHA DE ENTRADA", "FECHA DE VENCIMIENTO", "NOMBRE DEL INQUILINO", "NOMBRE DEL PROPIETARIO", "DOMICILIO", "CANTIDAD", "OBSERVACIONES"
}
));
//String observacionesDos = (String) table.getValueAt(table.getSelectedRow(), 7);
//taObservacionesDos.setText(observacionesDos);
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable table2 =(JTable) me.getSource();
Point p = me.getPoint();
int row = table2.rowAtPoint(p);
String observacionesDos = table.getValueAt(row, 7).toString();
taObservacionesDos.setText(observacionesDos);
/*if (me.getClickCount() == 2) {
// your valueChanged overridden method
}*/
}
});
table.setModel(md);
JButton btnBorrarTodo = new JButton("Borrar Todo");
btnBorrarTodo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnBorrarTodo.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int respuesta = JOptionPane.showConfirmDialog(null, "¿Desea borrar todos los datos guardados?", "Borrar Todo", JOptionPane.YES_NO_OPTION);
if (respuesta == 0){
if(md.getRowCount() == 0){
JOptionPane.showMessageDialog(null, "No hay ningùn archivo para borrar.");
}else{
while (md.getRowCount() > 0){
md.removeRow(0);
}
}
}
}
});
btnBorrarTodo.setFont(new Font("Tahoma", Font.BOLD, 15));
btnBorrarTodo.setBounds(344, 515, 293, 62);
contentPane.add(btnBorrarTodo);
JButton btnBorrarDatoSeleccionado = new JButton("Borrar Dato Seleccionado");
btnBorrarDatoSeleccionado.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
md.removeRow(table.getSelectedRow());
}catch(Exception x) {
JOptionPane.showMessageDialog(null, "No se ha seleccionado ninguna fila aùn.");
}
}
});
btnBorrarDatoSeleccionado.setFont(new Font("Tahoma", Font.BOLD, 15));
btnBorrarDatoSeleccionado.setBounds(926, 515, 373, 62);
contentPane.add(btnBorrarDatoSeleccionado);
txtFiltro = new JTextField();
txtFiltro.addKeyListener(new KeyAdapter() {
#SuppressWarnings("unchecked")
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
trsfiltro.setRowFilter(RowFilter.regexFilter(txtFiltro.getText()));
}
}
});
txtFiltro.setBounds(158, 538, 142, 20);
txtFiltro.addKeyListener(new KeyAdapter() {
public void keyReleased(final KeyEvent e) {
String cadena = (txtFiltro.getText());
txtFiltro.setText(cadena);
repaint();
filtro();
}
});
trsfiltro = new TableRowSorter<TableModel>(table.getModel());
table.setRowSorter(trsfiltro);
contentPane.add(txtFiltro);
txtFiltro.setColumns(10);
JLabel lblFiltro = new JLabel("Filtro : ");
lblFiltro.setBounds(102, 541, 46, 14);
contentPane.add(lblFiltro);
JScrollPane scrollPane_2 = new JScrollPane();
scrollPane_2.setBounds(10, 590, 1289, 87);
contentPane.add(scrollPane_2);
taObservacionesDos = new JTextArea();
taObservacionesDos.setEditable(false);
scrollPane_2.setViewportView(taObservacionesDos);
}
public void filtro() {
trsfiltro.setRowFilter(RowFilter.regexFilter("(?i)"+ txtFiltro.getText()));
}
}

You are calling...
md.addRow(a);
before you initialize md...
md = new DefaultTableModel(dataaa, columnasss);
In other words, initialize it first, then call the database and do your work. Otherwise you are trying to write to a table that doesn't exist yet.

Related

Syntax Error insert "}" to complete class block

I am making a program for my friend. I ran into an error while trying to create a write and save text into a .txt file. I should note this is the first time I have ever created something in Java Swing.
The error is marked with an asterisk.
package com.laganstoop.me;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
// Created by: Laganstoop (David L. Perez)
// Do Not Distribute!
public class Main implements ActionListener {
private JFrame frame;
public static String infoBox(String infoMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, infoMessage, "" + titleBar, JOptionPane.INFORMATION_MESSAGE);
return "";
}
public static void errorMessage(String errorMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, errorMessage, "" + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
public static final int HEIGHT = 800;
public static final int WIDTH = 600;
public static final int nHEIGHT = 400;
public static final int nWIDTH = 300;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(HEIGHT, WIDTH);
JButton btnNewButton = new JButton("Click To Add New");
btnNewButton.setBounds(10, 11, 132, 23);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnNewButton);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 764, 181);
panel.setBackground(Color.WHITE);
panel.setForeground(Color.WHITE);
frame.getContentPane().add(panel);
panel.setLayout(null);
panel.hide();
JLabel lblName = new JLabel("Name:");
lblName.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblName.setBounds(10, 11, 46, 14);
panel.add(lblName);
JLabel lblDate = new JLabel("Date:");
lblDate.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblDate.setBounds(10, 36, 46, 14);
panel.add(lblDate);
JLabel lblLocation = new JLabel("Time:\r\n");
lblLocation.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblLocation.setBounds(10, 61, 60, 14);
panel.add(lblLocation);
JLabel lblLocation_1 = new JLabel("Location:");
lblLocation_1.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblLocation_1.setBounds(10, 86, 60, 14);
panel.add(lblLocation_1);
JLabel lblRe = new JLabel("Referee");
lblRe.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblRe.setBounds(10, 111, 60, 14);
panel.add(lblRe);
textField = new JTextField();
textField.setBounds(76, 8, 127, 20);
panel.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(76, 33, 127, 20);
panel.add(textField_1);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(76, 58, 127, 20);
panel.add(textField_2);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(76, 86, 127, 20);
panel.add(textField_3);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_4.setBounds(76, 108, 127, 20);
panel.add(textField_4);
JCheckBox checkBox = new JCheckBox("");
checkBox.setBounds(209, 7, 21, 23);
panel.add(checkBox);
JCheckBox checkBox_1 = new JCheckBox("");
checkBox_1.setBounds(209, 32, 21, 23);
panel.add(checkBox_1);
JCheckBox checkBox_2 = new JCheckBox("");
checkBox_2.setBounds(209, 57, 21, 23);
panel.add(checkBox_2);
JCheckBox checkBox_3 = new JCheckBox("");
checkBox_3.setBounds(209, 82, 21, 23);
panel.add(checkBox_3);
JCheckBox checkBox_4 = new JCheckBox("");
checkBox_4.setBounds(209, 107, 21, 23);
panel.add(checkBox_4);
JPanel panel_2 = new JPanel();
panel_2.setBounds(20, 290, 358, 210);
panel_2.setLayout(null);
JButton btnNewNote = new JButton("New Note");
btnNewNote.setFont(new Font("Yu Gothic", Font.BOLD, 16));
btnNewNote.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame noteFrame = new JFrame();
noteFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
noteFrame.setLocationRelativeTo(panel);
noteFrame.pack();
noteFrame.setSize(nHEIGHT, nWIDTH);
noteFrame.getContentPane().add(panel_2);
noteFrame.setVisible(true);
}
});
btnNewNote.setBounds(293, 16, 461, 151);
panel.add(btnNewNote);
JLabel lblNotes = new JLabel("Notes:");
lblNotes.setBounds(10, 0, 46, 23);
panel_2.add(lblNotes);
lblNotes.setFont(new Font("Yu Gothic", Font.BOLD, 13));
JButton btnSaveCreate = new JButton("Create & Save");
btnSaveCreate.setBounds(237, 177, 131, 23);
panel_2.add(btnSaveCreate);
JCheckBox checkBox_5 = new JCheckBox("");
checkBox_5.setBounds(210, 177, 21, 23);
panel_2.add(checkBox_5);
btnSaveCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String NAME = textField.getText();
String DATE = textField_1.getText();
String TIME = textField_2.getText();
String LOCATION = textField_3.getText();
String Referee = textField_4.getText();
if(checkBox.isSelected() && checkBox_1.isSelected() && checkBox_2.isSelected() && checkBox_2.isSelected() && checkBox_3.isSelected() && checkBox_4.isSelected() && checkBox_5.isSelected())
{
infoBox("Met with " + NAME + " on " + DATE + " #" + TIME + ", and went to " + LOCATION + ", then I was introduced by " + Referee, "Paragraph");
}
else {
errorMessage("Error: Please validate entries!", "Error!");
}
}
});
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButton.hide();
panel.setVisible(true);
}
});
try {
String content = textField_5.getText();
File file = new File("/users/David/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content); //step2: write it
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace(); **** *****
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Any Help is greatly appreciated!
You just forgot to add the } in this statement:
catch (IOException e) {
e.printStackTrace();
}
Just as Andrew Thompson said: simple indentation would have made this error a lot easier to spot if done properly, and should be used as common practice.

How can I make my table update?

I use SQLite. I have 2 JFrames. 1st is consists of table and "Load data", "Edit data". Click on Edit make the new, 2nd JFrame to appear. I want my table to be updated after I make some changes with a help of class Edit. How do I make it? One idea is to use ActionListener so that after I click save, delete or update buttons in JFrame2 method of Jframe 1, which stays for updating of the table(using query), is called. I have tried, but it does not work. I do not want the method of the 1 Jframe to be called in 2nd Jframe, I want this method to be called in 1st Jframe. What are possible solutions?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.*;
public class Diary extends JFrame {
private JPanel contentPane;
JTable table;
private JButton btnLoadData;
public void refreshTabel(){
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Diary frame = new Diary();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Diary() {
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1250, 650);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(34, 58, 1182, 530);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
btnLoadData = new JButton("Load data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnLoadData.setBounds(33, 17, 117, 29);
contentPane.add(btnLoadData);
JButton btnAddData = new JButton("Edit");
btnAddData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddData nw = new AddData();
nw.addData();
refreshTabel();
}
});
btnAddData.setBounds(153, 17, 117, 29);
contentPane.add(btnAddData);
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.sun.glass.events.WindowEvent;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class AddData extends JFrame {
private JPanel contentPane;
private JTextField Date;
private JTextField ExerciseName;
private JTextField Weight;
private JTextField Sets;
private JTextField Reps;
/**
* Launch the application.
* #return
*/
public static void addData() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddData frame = new AddData();
frame.setVisible(true);
frame.setAlwaysOnTop(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField Exercise;
private JTextField N;
/**
* Create the frame.
*/
public AddData() {
setTitle("Edit");
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 465, 368);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDate = new JLabel("Date");
lblDate.setBounds(29, 49, 61, 16);
contentPane.add(lblDate);
JLabel ExerciseLabel = new JLabel("Exercise");
ExerciseLabel.setBounds(29, 88, 90, 16);
contentPane.add(ExerciseLabel);
JLabel lblNewLabel_1 = new JLabel("Sets");
lblNewLabel_1.setBounds(29, 169, 61, 16);
contentPane.add(lblNewLabel_1);
JLabel lblReps = new JLabel("Reps");
lblReps.setBounds(29, 213, 61, 16);
contentPane.add(lblReps);
JLabel lblWeight = new JLabel("Weight");
lblWeight.setBounds(29, 126, 61, 16);
contentPane.add(lblWeight);
Date = new JTextField();
Date.setBounds(169, 56, 150, 26);
contentPane.add(Date);
Date.setColumns(10);
ExerciseName = new JTextField();
ExerciseName.setBounds(169, 60, 150, 26);
contentPane.add(ExerciseLabel);
ExerciseName.setColumns(10);
Weight = new JTextField();
Weight.setBounds(169, 132, 150, 26);
contentPane.add(Weight);
Weight.setColumns(10);
Sets = new JTextField();
Sets.setBounds(169, 170, 150, 26);
contentPane.add(Sets);
Sets.setColumns(10);
Reps = new JTextField();
Reps.setBounds(169, 208, 150, 26);
contentPane.add(Reps);
Reps.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "insert into Diary (Date, Exercise, Weight, Sets, Reps) values (?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, Date.getText());
pst.setString(2, Exercise.getText());
pst.setString(3, Weight.getText());
pst.setString(4, Sets.getText());
pst.setString(5, Reps.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnSave.setBounds(29, 261, 117, 29);
contentPane.add(btnSave);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "update Diary set N ='"+N.getText()+"', Exercise ='"+Exercise.getText()+"', Weight ='"+Weight.getText()+"', Sets ='"+Sets.getText()+"', Reps ='"+Reps.getText()+"' where N ='"+N.getText()+"' ";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Updated");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnUpdate.setBounds(176, 261, 117, 29);
contentPane.add(btnUpdate);
Exercise = new JTextField();
Exercise.setBounds(169, 94, 150, 26);
contentPane.add(Exercise);
Exercise.setColumns(10);
N = new JTextField();
N.setBounds(169, 18, 150, 26);
contentPane.add(N);
N.setColumns(10);
JLabel lblN = new JLabel("N");
lblN.setBounds(29, 23, 61, 16);
contentPane.add(lblN);
JButton Delete = new JButton("Delete");
Delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "delete from Diary where N = '"+N.getText()+"'";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
Delete.setBounds(305, 261, 117, 29);
contentPane.add(Delete);
}
}

Reload a web page in a java application

I create a java application and now I have to reload a web page. I open the web page with this code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.JProgressBar;
import java.io.*;
import java.util.*;
public class views extends JFrame {
private JPanel contentPane;
private JTextField txtHttpswwwyoutubecom;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
views frame = new views();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public views() {
setTitle("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 707, 485);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblPutTheUrl = new JLabel("Put the url of the video");
lblPutTheUrl.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPutTheUrl.setBounds(40, 93, 159, 24);
contentPane.add(lblPutTheUrl);
JLabel lblSelectTheNumber = new JLabel("Select the number");
lblSelectTheNumber.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblSelectTheNumber.setBounds(40, 200, 203, 24);
contentPane.add(lblSelectTheNumber);
final JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"5", "10", "15", "20"}));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 15));
comboBox.setBounds(322, 202, 121, 20);
contentPane.add(comboBox);
txtHttpswwwyoutubecom = new JTextField();
txtHttpswwwyoutubecom.setText("https://www.google.com/");
txtHttpswwwyoutubecom.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtHttpswwwyoutubecom.setBounds(322, 93, 332, 24);
contentPane.add(txtHttpswwwyoutubecom);
txtHttpswwwyoutubecom.setColumns(10);
JLabel lblPressOk = new JLabel("Press Ok ");
lblPressOk.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPressOk.setBounds(40, 298, 71, 24);
contentPane.add(lblPressOk);
JButton btnOk = new JButton("Ok");
btnOk.addActionListener(new ActionListener() {
private String views;
private int intViews;
public void actionPerformed(ActionEvent arg0) {
//trasformare il numero delle views in una stringa
views = comboBox.getSelectedItem().toString();
//trasformo stringa in int
intViews = Integer.parseInt(views);
System.out.println(intViews);
//campo url
String urls = txtHttpswwwyoutubecom.getText();
//apertura url
int cont=0;
int cont1=0;
//cont=intViews;
//System.out.println("cont");
//System.out.println(intViews);
/*
try {
Thread.sleep(millisecondi);
}
catch (Exception e) {}
*/
while(intViews>cont){
cont++;
cont1++;
String URL = urls;
//String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//System.exit(0);
}
if(cont1==5){
cont1=0;
try {
Thread.sleep(5500);
}
catch (Exception e1) {}
}
}
}
});
btnOk.setFont(new Font("Tahoma", Font.PLAIN, 15));
btnOk.setBounds(322, 299, 121, 23);
contentPane.add(btnOk);
JLabel lblDevelopedByRiccardo = new JLabel("Developed by Riccardo Vecchiato");
lblDevelopedByRiccardo.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblDevelopedByRiccardo.setBounds(464, 421, 237, 24);
contentPane.add(lblDevelopedByRiccardo);
JLabel lblAlpha = new JLabel("Alpha 1.0");
lblAlpha.setBounds(10, 428, 46, 14);
contentPane.add(lblAlpha);
}
}
Every 5 seconds I open five new web page. I open that web page using this code:
String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There is a command that reload all the web page that I create with this code?
Do not use Thread.sleep() as it will freeze your Swing application.
Instead you should use a javax.swing.Timer.
See the Java tutorial How to Use Swing Timers and Lesson: Concurrency in Swing for more information and examples.

Retriving the String accosiated with a JCheckBox

I have a lottery game problem and I am able to count the number of checked boxes correctly but I do not understand how to get the String number assigned to the JcheckBox. I thought I could use .getText but that did not work. I am not sure if I am using the proper listener.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JLottery2 extends JFrame implements ItemListener {
private String[] lotteryNumbers = { "1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30" };
private JPanel jp1 = new JPanel();
private JPanel jp2 = new JPanel();
private JPanel jp3 = new JPanel(new GridLayout(3, 10, 5, 5));
private JLabel jl1 = new JLabel("The Lottery Game!!!!!");
private JLabel jl2 = new JLabel(
"To play, pick six number that match the randomly selected numbers.");
private FlowLayout layout = new FlowLayout();
private GridLayout gridBase = new GridLayout(3, 1, 5, 5);
private GridLayout grid = new GridLayout(3, 10, 5, 5);
private Font heading = new Font("Palatino Linotype", Font.BOLD, 24);
private Font bodyText = new Font("Palatino Linotype", Font.BOLD, 14);
private Color color1 = new Color(4, 217, 225);
private Color color2 = new Color(4, 225, 129);
private int maxNumber = 6;
private int counter = 0;
private int[] randomNum;
private String[] userPickedNumbers;
Container con = getContentPane();
public JLottery2() {
super("The Lottery Game");
con.setLayout(gridBase);
con.add(jp1);
jp1.setLayout(layout);
jp1.add(jl1);
jl1.setFont(heading);
jp1.setBackground(color1);
con.add(jp2);
jp2.setLayout(layout);
jp2.add(jl2);
jl2.setFont(bodyText);
jp2.setBackground(color1);
con.add(jp3);
jp3.setLayout(grid);
for (int i = 0; i < lotteryNumbers.length; i++) {
JCheckBox checkBox[] = new JCheckBox[lotteryNumbers.length];
checkBox[i] = new JCheckBox(lotteryNumbers[i]);
jp3.add(checkBox[i]);
jp3.setBackground(color2);
checkBox[i].addItemListener(this);
}
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void randNumber() {
randomNum = new int[maxNumber];
for (int i = 0; i < maxNumber; i++) {
randomNum[i] = ((int) (Math.random() * 100) % lotteryNumbers.length + 1);
System.out.println(randomNum[i]);
}
}
public static void main(String[] args) {
JLottery2 frame = new JLottery2();
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED && counter < maxNumber) {
counter++;
System.out.println("add");
System.out.println(counter);
} else if (e.getStateChange() == ItemEvent.DESELECTED
&& counter < maxNumber) {
counter--;
System.out.println("deduct");
System.out.println(counter);
}
if (counter == maxNumber) {
System.out.println("max");
jp3.setVisible(false);
randNumber();
System.out.println(userPickedNumbers);
}
}
}
((JCheckBox)e.getSource()).getText()
works fine for me with your code.

How to get proper alignment of Title border over the Jtable

Im trying to build small application in java swings. I started using this link: Creating a Grid in Java.
Everything was good. I finished that task but onething is left that I'm trying to remove extra title border. I tried to reduce the border of title border still its not affect. Any one with good suggestion try to share with me.
package swings.application.framework;
import java.awt.*;
import java.awt.event.ActionEvent
;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Inf3rNix
*/
public class KidsProblemTable {
private static JButton okbtn;
private static JFrame frame;
public static void main(String[] args) {
Runnable runner = new Runnable() {
#Override
public void run() {
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("Kids Table");
Border border = LineBorder.createGrayLineBorder();
frame.setLayout(null);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
JLabel Heading = new JLabel("My Result");
Heading.setFont(new Font("Gabriola", Font.ITALIC, 56));
Heading.setForeground(Color.BLUE);
Heading.setBounds(550, -60, 300, 200);
JLabel Heading2 = new JLabel("Nice Job! Here are your results...");
Heading2.setFont(new Font("Buxton Sketch", Font.ITALIC, 26));
Heading2.setForeground(Color.BLUE);
Heading2.setBounds(500, 10, 600, 200);
JLabel Heading3 = new JLabel();
String str = "You got 5 correct answer out of 7 question";
Heading3.setText("<html><a href=' ' style='color:rgb(248,116,49);'>" + str + "</a></html>");
Heading3.setFont(new Font("Andy", Font.PLAIN, 20));
Heading3.setBounds(500, 70, 600, 200);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
Border border1 = BorderFactory.createTitledBorder("Exercise");
panel1.setBounds(150, 200, 1000, 190);
String column = "Questions".toUpperCase();
// AttributedString as = new AttributedString(column);
// Font plainFont = new Font("Times New Roman", Font.PLAIN, 24);
// as.addAttribute(TextAttribute.FONT, plainFont);
// as.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON,0,8 );
String column1 = "Problem".toUpperCase();
String column2 = "Answer".toUpperCase();
String column3 = "Answer".toUpperCase();
String results = "results".toUpperCase();
Object rowData[][] = {{"1", "3+9", "12", "12", "Correct !"},
{"2", "4+3", "7", "7", "Correct !"},
{"3", "10+8", "17", "18", "Sorry :("},
{"4", "5+1", "6", "6", "Correct !"},
{"5", "10+8", "18", "18", "Correct !"},
{"6", "8+2", "10", "10", "Correct !"},
{"7", "5+6", "4", "11", "Sorry :("}
};
Object columnNames[] = {column, column1, column2, column3, results};
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
JTable tb1 = new JTable(model) {
//when checking if a cell is editable always return false
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
//JTable table1 = new JTable(rowData, columnNames1);
tb1.setBackground(Color.getHSBColor(153, 0, 91));
JScrollPane scrollPane1 = new JScrollPane(tb1);
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
Border loweredbevel = BorderFactory.createLoweredBevelBorder();
Border raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
// ImageIcon icon = createImageIcon("images/wavy.gif", "wavy-line border icon");
okbtn=new JButton("Press Ok to Exit");
okbtn.setBorder(raisedbevel);
okbtn.setFont(new Font("Vani", Font.BOLD, 12));
okbtn.setBounds(575, 390, 150, 50);
panel2.add(scrollPane1, BorderLayout.CENTER);
okbtn.addActionListener(new buttonActionListener());
frame.add(Heading);
frame.add(Heading2);
frame.add(Heading3);
frame.add(okbtn);
frame.add(panel1);
panel2.setBorder(border1);
panel1.add(panel2);
frame.setSize(500, 500);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
private static class buttonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==okbtn){
JOptionPane.showMessageDialog(null, "All the best !!!");
WindowEvent winClosingEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING );
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
}
}
}
}
maybe
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Inf3rNix
*/
public class KidsProblemTable {
private JFrame frame;
private JPanel panel1 = new JPanel();
private JLabel Heading = new JLabel("My Result", JLabel.CENTER);
private JLabel Heading2 = new JLabel("Nice Job! Here are your results...", JLabel.CENTER);
private JLabel Heading3 = new JLabel();
private String str = "You got 5 correct answer out of 7 question";
private JPanel panel2 = new JPanel();
private JButton okbtn;
private Object rowData[][] = {{"1", "3+9", "12", "12", "Correct !"},
{"2", "4+3", "7", "7", "Correct !"},
{"3", "10+8", "17", "18", "Sorry :("},
{"4", "5+1", "6", "6", "Correct !"},
{"5", "10+8", "18", "18", "Correct !"},
{"6", "8+2", "10", "10", "Correct !"},
{"7", "5+6", "4", "11", "Sorry :("}
};
private String column = "Questions".toUpperCase();
private String column1 = "Problem".toUpperCase();
private String column2 = "Answer".toUpperCase();
private String column3 = "Answer".toUpperCase();
private String results = "results".toUpperCase();
private Object columnNames[] = {column, column1, column2, column3, results};
private DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
private JTable tb1 = new JTable(model) {
private static final long serialVersionUID = 1L;
//when checking if a cell is editable always return false
#Override
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
private JScrollPane scrollPane1 = new JScrollPane(tb1);
public KidsProblemTable() {
Border border1 = BorderFactory.createTitledBorder("Exercise");
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
tb1.setBackground(Color.getHSBColor(153, 0, 91));
tb1.setPreferredScrollableViewportSize(tb1.getPreferredSize());
Heading.setFont(new Font("Gabriola", Font.ITALIC, 56));
Heading.setForeground(Color.BLUE);
Heading2.setFont(new Font("Buxton Sketch", Font.ITALIC, 26));
Heading2.setForeground(Color.BLUE);
Heading3.setText("<html><a href=' ' style='color:rgb(248,116,49);'>" + str + "</a></html>");
Heading3.setFont(new Font("Andy", Font.PLAIN, 20));
panel1.setLayout(new GridLayout(3, 1));
panel1.add(Heading);
panel1.add(Heading2);
panel1.add(Heading3);
// ImageIcon icon = createImageIcon("images/wavy.gif", "wavy-line border icon");
okbtn = new JButton(" Press Ok to Exit ");
okbtn.setBorder(raisedbevel);
okbtn.setFont(new Font("Vani", Font.BOLD, 12));
okbtn.addActionListener(new buttonActionListener());
panel2.add(okbtn);
panel2.setBorder(border1);
frame = new JFrame("Kids Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1, BorderLayout.NORTH);
frame.add(scrollPane1, BorderLayout.CENTER);
frame.add(panel2, BorderLayout.SOUTH);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
private class buttonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == okbtn) {
JOptionPane.showMessageDialog(null, "All the best !!!");
WindowEvent winClosingEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}
}
}
public static void main(String[] args) {
Runnable runner = new Runnable() {
#Override
public void run() {
new KidsProblemTable();
}
};
EventQueue.invokeLater(runner);
}
}
I found your problem,
You added the scrollPane to panel2 as
panel2.add(scrollPane1, BorderLayout.CENTER);
but you didn't setLayout as BorderLayout for panel2.
and you set the Layout of panel1 as null
see this code
JPanel panel1 = new JPanel();
panel1.setLayout(null);//add to your code
JPanel panel2 = new JPanel();
panel2.setLayout(new BorderLayout());//add to your code
panel2.setBounds(0,0,800,120);//add to your code
out put:
may this image will remove after some hours
out put image

Categories

Resources