Related
I have a problem with Swing interface on java. Explaination: I have a Combobox with 1, 2, 3, 4, 5 items. When an exact item is selected I need to create some more comboboxes the number of which depends on the selected item. So, if number 5 is selected, 5 more comboboxes must appear in the frame. I used ActionListener but it did not work properly. However, the same code but outside Actionlistener works well. What a problem can it be?
public class FrameClass extends JFrame {
JPanel panel;
JComboBox box;
String[] s = {"1", "2", "3", "4", "5"};
String[] s1 = {"0", "1", "2", "3", "4", "5"};
public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox adults = new JComboBox(s);
JComboBox children = new JComboBox(s1);
panel.add(box, BorderLayout.CENTER);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i <= box.getSelectedIndex(); i++) {
panel.add(adults, BorderLayout.WEST);
panel.add(children, BorderLayout.WEST);
}
}
});
add(panel);
}
}
public class MainClass {
public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.getContentPane().setBackground(Color.WHITE);
frame.setVisible(true);
}
}
The problem that you don't inform the layout manager about new elements in your panel.
Here is the correct variant of your action listener:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class FrameClass extends JFrame {
JPanel panel;
JComboBox<String> box;
String[] s = {"1", "2", "3", "4", "5"};
String[] s1 = {"0", "1", "2", "3", "4", "5"};
public FrameClass() {
panel = new JPanel();
box = new JComboBox(s);
JComboBox[] adults = new JComboBox[5];
JComboBox[] children = new JComboBox[5];
for (int i = 0; i < 5; i++) {
adults[i] = new JComboBox<>(s);
children[i] = new JComboBox<>(s1);
}
panel.add(box, BorderLayout.CENTER);
JPanel nested = new JPanel();
add(nested, BorderLayout.EAST);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
nested.removeAll();
nested.setLayout(new GridLayout(box.getSelectedIndex() + 1, 2));
for (int i = 0; i <= box.getSelectedIndex(); i++) {
nested.add(adults[i]);
nested.add(children[i]);
}
getContentPane().revalidate();
getContentPane().repaint();
pack();
}
});
add(panel);
}
public static void main(String[] args) {
JFrame frame = new FrameClass();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.getContentPane().setBackground(Color.WHITE);
frame.setLocationRelativeTo(null); // center the window
frame.setVisible(true);
}
}
It is not changing the corresponding combobox value why it is changing the latest combobox value not the respective combobox?
When i run this code, after clicking addfield two times, when i change the first combobox the second combobox value should change not the fourth combobox, this is wrong, what i want is depending on first combobox selection second combobox should be selectable and if third combobox is selected, then the fourth combobox should be selectable.
add Field button adds extra comboboxes in the window, the way it should work is, in the case when the add Field button is pressed twice, i select first combobox, respectively second combobox should be selectable but for some reason, fourth combobox is getting selectable. you will understand the problem better when you run the above code, I have provided the entire code in the description, please help!
package addextraitem;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ExtraComboBox {
int count = 0;
JComboBox fruits[] = new JComboBox[10];;
JPanel comboPanel;
JFrame guiFrame;
//JComboBox dude1;
String[] valOptions3 = {"&"};
String[] valOptions2 = {"|->", "|=>"};
String[] valOptions1 = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
String[] valOptions0 = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
String[] fruitOptions1 = {"", "Delay1", "Delay2", "Delay3"};
String chosenString;
int numPairs1 = valOptions0.length;
JButton addField;
int count1 = 0;
JComboBox[] ComboBox4 = new JComboBox[numPairs1];
JComboBox[] ComboBox5 = new JComboBox[numPairs1];
JComboBox[] ComboBox6 = new JComboBox[numPairs1];
String[] comborel = {"a", "b", "c", "d", "e"};
JLabel lb;
JComboBox dude;
JTextField handle;
String clockOptions1;
JLabel dudel[] = new JLabel[10];
JComboBox dude1[] = new JComboBox[10];
JComboBox dude2[] = new JComboBox[10];;
//JComboBox dude1[] = new JComboBox[10];
String[] valOptions = {"Unknown", "0", "1"};
String [] s = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
int cnt = 0;
int i = 0;
JLabel comboLbl;
JLabel lb1;
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
new ExtraComboBox();
}
public ExtraComboBox()
{
guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("ComboBox GUI");
guiFrame.setSize(350,250);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//The first JPanel contains a JLabel and JCombobox
comboPanel = new JPanel();
addField = new JButton("Add Field");
addField.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == addField) {
count1++;
comboLbl = new JLabel("Select a relation:");
fruits[count1] = new JComboBox(fruitOptions1);
MyItemListener2 actionListener2 = new MyItemListener2();
fruits[count1].addItemListener(actionListener2);
//System.out.println("HI: " + fruits[count1].getParent());
dude2[count1] = new JComboBox();
System.out.println("ADD FIELDS: " + count1);
comboPanel.add(comboLbl);
comboPanel.add(fruits[count1]);
comboPanel.add(dude2[count1]);
guiFrame.revalidate();
guiFrame.validate();
guiFrame.pack();
guiFrame.repaint();
}
}
});
comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.Y_AXIS));
comboPanel.add(addField);
//The JFrame uses the BorderLayout layout manager.
//Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
//make sure the JFrame is visible
guiFrame.setVisible(true);
}
class MyItemListener2 implements ItemListener {
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
JComboBox cb = (JComboBox) evt.getSource();
Object item = evt.getItem();
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
System.out.println("COUNTER: " + count1);
System.out.println(evt.getItem());
dude2[count1].removeAllItems();
if(evt.getItem() == "Delay1") {
System.out.println(valOptions1.length);
for(int i = 0; i < valOptions1.length; i++) {
dude2[count1].addItem(valOptions1[i]); //dude1 = new JComboBox(valOptions1);
System.out.println(valOptions1[i]);
}
}
else if(evt.getItem() == "Delay2") {
System.out.println(valOptions2.length);
for(int j = 0; j < valOptions2.length; j++) {
System.out.println(valOptions2[j]);
dude2[count1].addItem(valOptions2[j]); //dude1 = new JComboBox(valOptions1);
}
}
else if(evt.getItem() == "Delay3") {
System.out.println(valOptions3.length);
for(int j = 0; j < valOptions3.length; j++) {
System.out.println(valOptions3[j]);
dude2[count1].addItem(valOptions3[j]); //dude1 = new JComboBox(valOptions1);
}
}
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
// Item is no longer selected
}
}
}
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ExtraComboBox {
private int maxFields = 4; // The max number of fields allowed in the dialog
JComboBox fruits[] = new JComboBox[maxFields];
JPanel comboPanel;
JFrame guiFrame;
String[] valOptions3 = { "&" };
String[] valOptions2 = { "|->", "|=>" };
String[] valOptions1 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] valOptions0 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] fruitOptions1 = { "", "Delay1", "Delay2", "Delay3" };
JButton addField;
int count1 = 0;
JLabel dudel[] = new JLabel[maxFields];
JComboBox dude2[] = new JComboBox[maxFields];
String[] valOptions = { "Unknown", "0", "1" };
String[] s = { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
private JLabel comboLbl;
public static void main(String[] args) {
new ExtraComboBox();
}
public ExtraComboBox() {
guiFrame = new JFrame();
// make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("ComboBox GUI");
guiFrame.setSize(350, 350);
// The first JPanel contains a JLabel and JCombobox
comboPanel = new JPanel();
addField = new JButton("Add Field");
addField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource().equals(addField)) {
if (count1 < maxFields) {
comboLbl = new JLabel("Select a relation:");
fruits[count1] = new JComboBox<String>(fruitOptions1);
MyItemListener2 actionListener2 = new MyItemListener2(count1);
fruits[count1].addItemListener(actionListener2);
// System.out.println("HI: " + fruits[count1].getParent());
dude2[count1] = new JComboBox<String>();
System.out.println("ADD FIELDS: " + count1);
comboPanel.add(comboLbl);
comboPanel.add(fruits[count1]);
comboPanel.add(dude2[count1]);
guiFrame.validate();
guiFrame.repaint();
count1++;
} else {
System.out.println("You reached the maximum of 4 fields.");
}
}
}
});
comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.Y_AXIS));
comboPanel.add(addField);
// The JFrame uses the BorderLayout layout manager.
// Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
// make sure the JFrame is visible
guiFrame.setVisible(true);
}
class MyItemListener2 implements ItemListener {
private int index;
public MyItemListener2(int pIndex) {
super();
index = pIndex;
}
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
System.out.println("COUNTER: " + index);
System.out.println(evt.getItem());
dude2[index].removeAllItems();
switch ((String) evt.getItem()) {
case "Delay1":
for (int i = 0; i < valOptions1.length; i++) {
dude2[index].addItem(valOptions1[i]); // dude1 = new JComboBox(valOptions1);
System.out.println(valOptions1[i]);
}
break;
case "Delay2":
for (int j = 0; j < valOptions2.length; j++) {
System.out.println(valOptions2[j]);
dude2[index].addItem(valOptions2[j]); // dude1 = new JComboBox(valOptions1);
}
break;
case "Delay3":
for (int j = 0; j < valOptions3.length; j++) {
System.out.println(valOptions3[j]);
dude2[index].addItem(valOptions3[j]); // dude1 = new JComboBox(valOptions1);
}
}
}
}
}
}
I think this solves your request. I removed any unused code but kept all variablenames. Please chose the names for your variables in a way anyone reading the code knows what the variable is for.
It is pretty obvious you do not know java or any other high programming language. I'd recommend you to learn the basics first before trying to programm fancy stuff.
I hope this helps you
I want to add a scrollpane in the frame window or comboPanel.
Below code, the guiFrame.add(scrollpane) is not working, why it is not working?
How can I add the scrollpane to comboPanel or the guiFrame?
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ExtraComboBox {
private int maxFields = 4; // The max number of fields allowed in the dialog
JComboBox fruits[] = new JComboBox[maxFields];
JPanel comboPanel;
JFrame guiFrame;
String[] valOptions3 = { "&" };
String[] valOptions2 = { "|->", "|=>" };
String[] valOptions1 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] valOptions0 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] fruitOptions1 = { "", "Delay1", "Delay2", "Delay3" };
JButton addField;
int count1 = 0;
JLabel dudel[] = new JLabel[maxFields];
JComboBox dude2[] = new JComboBox[maxFields];
String[] valOptions = { "Unknown", "0", "1" };
String[] s = { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
private JLabel comboLbl;
public static void main(String[] args) {
new ExtraComboBox();
}
public ExtraComboBox() {
guiFrame = new JFrame();
// make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("ComboBox GUI");
guiFrame.setSize(350, 350);
// The first JPanel contains a JLabel and JCombobox
comboPanel = new JPanel();
addField = new JButton("Add Field");
addField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource().equals(addField)) {
if (count1 < maxFields) {
comboLbl = new JLabel("Select a relation:");
fruits[count1] = new JComboBox<String>(fruitOptions1);
MyItemListener2 actionListener2 = new MyItemListener2(count1);
fruits[count1].addItemListener(actionListener2);
// System.out.println("HI: " + fruits[count1].getParent());
dude2[count1] = new JComboBox<String>();
System.out.println("ADD FIELDS: " + count1);
comboPanel.add(comboLbl);
comboPanel.add(fruits[count1]);
comboPanel.add(dude2[count1]);
guiFrame.validate();
guiFrame.repaint();
count1++;
} else {
System.out.println("You reached the maximum of 4 fields.");
}
}
}
});
comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.Y_AXIS));
comboPanel.add(addField);
// The JFrame uses the BorderLayout layout manager.
// Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
// make sure the JFrame is visible
guiFrame.setVisible(true);
}
class MyItemListener2 implements ItemListener {
private int index;
public MyItemListener2(int pIndex) {
super();
index = pIndex;
}
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
System.out.println("COUNTER: " + index);
System.out.println(evt.getItem());
dude2[index].removeAllItems();
switch ((String) evt.getItem()) {
case "Delay1":
for (int i = 0; i < valOptions1.length; i++) {
dude2[index].addItem(valOptions1[i]); // dude1 = new JComboBox(valOptions1);
System.out.println(valOptions1[i]);
}
break;
case "Delay2":
for (int j = 0; j < valOptions2.length; j++) {
System.out.println(valOptions2[j]);
dude2[index].addItem(valOptions2[j]); // dude1 = new JComboBox(valOptions1);
}
break;
case "Delay3":
for (int j = 0; j < valOptions3.length; j++) {
System.out.println(valOptions3[j]);
dude2[index].addItem(valOptions3[j]); // dude1 = new JComboBox(valOptions1);
}
}
}
}
}
}
How can I add the scrollpane to comboPanel or the guiFrame?
You add the comboPanel to the JViewport of the JScrollPane and then you add the scroll pane to the JFrame.
//guiFrame.add(comboPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane( comboPanel );
guiFrame.add(scrollPane, BorderLayout.CENTER);
It is better to add the scrollpane to the CENTER, then it will get all the space available to the frame.
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.
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