populate DefaultTableModel after insert a row java - java

I am running a program with two frames. First one has a table, the second one has a form which allows adding a new user to the table. I think the problem is I didn't add a reference from the mainframe. I was trying different methods to refresh the mainframe programmatically, but it did not help so much. I read many articles on how to to it but I could find a solution. My table usually changes when I close my app and open it again. But I don't think is the right way to do it. I tried to delete elements from DefaultTableModel and populated jtable again, but did not get any results. Here is my code:
public Vector vector_jtable = new Vector();
public MainApp() {
initComponents();
Database b = new Database();
b.getAmountOfRows(getCount);
this.setLocationRelativeTo(null);
printResultDB();
}
//add function that is responsible for addding data to the table
public void postDataJtable() {
System.out.println("The vector is: " + vector_jtable);
Vector<String> header = new Vector<String>();
header.add("Number");
header.add("Name");
header.add("First Payment");
header.add("Next Payment");
header.add("Picture");
header.add("Phone");
header.add("Amount");
header.add("Age");
model = (DefaultTableModel)jTable2.getModel();
model.setDataVector(vector_jtable,header);
}
I created a vector that allows putting data from the second frame.
MainApp app;
public AddStudents(MainApp a) {
initComponents();
app = a;
this.setLocationRelativeTo(null);
jDateChooser1.setDateFormatString("yyyy-MM-dd");
jDateChooser2.setDateFormatString("yyyy-MM-dd");
}
After that, I push the button to send it out and update the mainframe, but nothing happened:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
app.vector_jtable.add(name);
app.vector_jtable.add(first_p);
app.vector_jtable.add(next_p);
app.vector_jtable.add(picture);
app.vector_jtable.add(phone);
app.vector_jtable.add(amount);
app.vector_jtable.add(age);
app.postDataJtable();
My question. How to add a row in jtable and refresh it. I really stuck in this topic. I need your help.

Don't update the Vector.
When you want to change the data in the table you need to change the data in the TableModel.
You can use the addRow(...) method of the DefaultTableModel to add a new row of data.
So the basic logic is:
Vector<Object> row = new Vector<Object>();
row.add( someVariable1 );
row.add( someVariable2 );
...
modal.addRow( row ):
The model will then tell the table to repaint itself.
Edit:
There is no trick all you need is a reference to the model. Then you update the model.
Here is a simple example to prove the concept works:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
private DefaultTableModel model;
SSCCE()
{
setLayout( new BorderLayout() );
model = new DefaultTableModel(0, 2);
JTable table = new JTable( model );
add(new JScrollPane( table ));
JButton button = new JButton( "Add Row" );
add(button, BorderLayout.PAGE_END);
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
Vector<Object> row = new Vector<Object>();
row.add( "" + model.getRowCount() );
row.add( new Date().toString() );
model.addRow( row );
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
If it doesn't work for you then you need to debug your code. Maybe you have two "model" variables? Maybe you have to "table" variables. Maybe your code isn't even executed. Did you add any debug statements to the code to make sure it is executed.
We can't solve your problem only point you in the right direction.

You can try some aspects from this example below. The example has two JFrame's - one with a JTable and the other the data entry fields. When the data is entered and the "UpdateTable" button is pressed (in the data entry class) the table is updated.
The example uses java.util.Observer and Observable to achieve this functionality.
The class with table:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.util.Observer;
import java.util.Observable;
public class TableUpdateTester implements Observer {
private JTable table;
private static final Object[] TABLE_COLUMNS = {"Book", "Author"};
private static final Object [][] TABLE_DATA = {
{"Book 1", "author 1"}, {"Book 2", "author 1"}
};
public static void main(String [] args) {
TableUpdateTester tester = new TableUpdateTester();
new DataEntryClass(tester);
}
public TableUpdateTester() {
JFrame frame = new JFrame("Table Update Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getTablePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel getTablePanel() {
table = new JTable(new DefaultTableModel(TABLE_DATA, TABLE_COLUMNS));
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.setPreferredSize(new Dimension(400, 150));
scrollpane.setViewportView(table);
JPanel panel = new JPanel();
panel.add(scrollpane);
return panel;
}
// This is Observer's override method.
#Override public void update(Observable o, Object arg) {
String [] data = (String []) arg;
System.out.println("Data recieving: " + java.util.Arrays.toString(data));
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(data);
}
}
The data entry class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Observable;
public class DataEntryClass {
public DataEntryClass(TableUpdateTester observer) {
final DataObservable observable = new DataObservable();
observable.addObserver(observer);
JLabel label = new JLabel("Book: ");
final JTextField text = new JTextField(15);
JLabel label2 = new JLabel("Author: ");
final JTextField text2 = new JTextField(15);
JButton button = new JButton("Update Table");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data1 = text.getText().isEmpty() ? "empty" : text.getText();
String data2 = text2.getText().isEmpty() ? "empty" : text2.getText();
String [] data = {data1, data2};
System.out.println("Data sent: " + java.util.Arrays.toString(data));
observable.changeData(data);
}
});
JPanel panel = new JPanel();
GridLayout grid = new GridLayout(3, 2);
panel.setLayout(grid);
panel.add(label);
panel.add(text);
panel.add(label2);
panel.add(text2);
panel.add(new JLabel(""));
panel.add(button);
JFrame frame = new JFrame();
frame.setTitle("Data Entry");
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.pack();
}
}
class DataObservable extends Observable {
DataObservable() {
super();
}
void changeData(Object data) {
// the two methods of Observable class
setChanged();
notifyObservers(data);
}
}

Finally, I found a solution to my problem. I will post my code here.
The Mainframe. I know the app with two frames is not a good option, because it's hard to fix the problem and it usually takes a lot of time to debug it.
/**
* Create the application.
*/
public MainApp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 689, 345);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//add table in DefaultTableModel
model = new DefaultTableModel(0,2);
table = new JTable(model);
table.setBounds(58, 38, 524, 197);
frame.getContentPane().add(table);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(0, 0, 4, 4);
frame.getContentPane().add(scrollPane);
JButton btnNewButton = new JButton("Add");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Call a second frame
//add reference for DefaultTableModel and send it to another frame
AddData frame = new AddData(model);
frame.setVisible(true);
}
});
btnNewButton.setBounds(239, 269, 117, 29);
frame.getContentPane().add(btnNewButton);
}
The second frame, that is responsible for adding a new row in a table.
/**
* Create the frame.
*/
public AddData(DefaultTableModel model) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(115, 71, 188, 41);
contentPane.add(dateChooser);
JButton btnNewButton = new JButton("Send");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//MainApp app = new MainApp();
Vector<Object> row = new Vector<Object>();
row.add(""+model.getRowCount());
row.add(dateChooser.getDate().toString());
model.addRow(row);
}
});
btnNewButton.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
btnNewButton.setBounds(165, 192, 117, 41);
contentPane.add(btnNewButton);
}
I found my mistake. I did not send a link of DefaultTableModel into the second frame. That's why it was null every time. It was a really painful experience, but I learned from my mistakes. Thanks, everyone for your help. I really appriciate.

Related

How to close JDialog and save the setting ?

Hi I'm working on a program and I faced a problem when I choose some settings from JDialog then click "ok", which is that the setting didn't save but come back to the original settings.
PS : I'm not English speaker so maybe you observe some mistakes in my text above.
picture
enter image description here
class DrawingSettingWindow extends JDialog {
public DrawingSettingWindow() {
this.setTitle("Drawing Setting Window");
this.setSize(550, 550);
this.setLocationRelativeTo(null);
this.setModal(true);
this.setLayout(new GridLayout(4, 1));
JLabel selectColorText = new JLabel("Select Drawing Color");
colorsList = new JComboBox(colors);
JPanel panel1 = new JPanel();
panel1.add(selectColorText);
panel1.add(colorsList);
add(panel1);
JLabel selectStyleText = new JLabel("Select Drawing Style");
JPanel panel2 = new JPanel();
normal = new JRadioButton("Normal");
normal.setSelected(true);
filled = new JRadioButton("Filled");
ButtonGroup bg = new ButtonGroup();
bg.add(normal);
bg.add(filled);
panel2.add(selectStyleText);
panel2.add(normal);
panel2.add(filled);
add(panel2);
JButton ok = new JButton("OK");
add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
this.pack();
this.setVisible(true);
}
The information is there, you just have to extract it from the dialog after the user is done using it. I would give the code above at least two new methods, one a public getColor() method that returns colorsList.getSelectedItem();, the color selection of the user (I'm not sure what type of object this is, so I can't show the method yet). Also another one that gets the user's filled setting, perhaps
public boolean getFilled() {
return filled.isSelected();
}
Since the dialog is modal, you'll know that the user has finished using it immediately after you set it visible in the calling code. And this is where you call the above methods to extract the data.
In the code below, I've shown this in this section: drawingSettings.setVisible(true);
// here you extract the data
Object color = drawingSettings.getColor();
boolean filled = drawingSettings.getFilled();
textArea.append("Color: " + color + "\n");
textArea.append("Filled: " + filled + "\n");
}
For example (see comments):
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class UseDrawingSettings extends JPanel {
private JTextArea textArea = new JTextArea(20, 40);
private DrawingSettingWindow drawingSettings;
public UseDrawingSettings() {
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new ShowDrawSettings()));
setLayout(new BorderLayout());
add(new JScrollPane(textArea));
add(topPanel, BorderLayout.PAGE_START);
}
private class ShowDrawSettings extends AbstractAction {
public ShowDrawSettings() {
super("Get Drawing Settings");
}
#Override
public void actionPerformed(ActionEvent e) {
if (drawingSettings == null) {
Window win = SwingUtilities.getWindowAncestor(UseDrawingSettings.this);
drawingSettings = new DrawingSettingWindow(win);
}
drawingSettings.setVisible(true);
// here you extract the data
Object color = drawingSettings.getColor();
boolean filled = drawingSettings.getFilled();
textArea.append("Color: " + color + "\n");
textArea.append("Filled: " + filled + "\n");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
UseDrawingSettings mainPanel = new UseDrawingSettings();
JFrame frame = new JFrame("UseDrawingSettings");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class DrawingSettingWindow extends JDialog {
private static final String TITLE = "Drawing Setting Window";
private JComboBox<String> colorsList;
private JRadioButton normal;
private JRadioButton filled;
// not sure what colors is, but I'll make it a String array for testing
private String[] colors = {"Red", "Orange", "Yellow", "Green", "Blue"};
public DrawingSettingWindow(Window win) {
super(win, TITLE, ModalityType.APPLICATION_MODAL);
// this.setTitle("Drawing Setting Window");
this.setSize(550, 550); // !! this is not recommended
this.setLocationRelativeTo(null);
this.setModal(true);
this.setLayout(new GridLayout(4, 1));
JLabel selectColorText = new JLabel("Select Drawing Color");
colorsList = new JComboBox(colors);
JPanel panel1 = new JPanel();
panel1.add(selectColorText);
panel1.add(colorsList);
add(panel1);
JLabel selectStyleText = new JLabel("Select Drawing Style");
JPanel panel2 = new JPanel();
normal = new JRadioButton("Normal");
normal.setSelected(true);
filled = new JRadioButton("Filled");
ButtonGroup bg = new ButtonGroup();
bg.add(normal);
bg.add(filled);
panel2.add(selectStyleText);
panel2.add(normal);
panel2.add(filled);
add(panel2);
JButton ok = new JButton("OK");
add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
this.pack();
// this.setVisible(true); // this should be the calling code's responsibility
}
public Object getColor() {
return colorsList.getSelectedItem();
}
public boolean getFilled() {
return filled.isSelected();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Foo");
}
}
Side notes:
I've changed your class's constructor to accept a Window parameter, the base class for JFrame, JDialog, and such, and have added a call to the super's constructor. This way, the dialog is a true child window of the calling code (or you can pass in null if you want it not to be).
I recommend not making the dialog visible within its constructor. It is the calling code's responsibility for doing this, and there are instances where the calling code will wish to not make the dialog visible after creating it, for example if it wanted to attach a PropertyChangeListener to it before making it visible. This is most important for modal dialogs, but is just good programming practice.
I didn't know the type of objects held by your combo box, and so made an array of String for demonstration purposes.

Write to and read from .txt file, listselectionlistener

I need some help making this program write the JList elements info to a .txt file and then outputing the contents of the .txt file to the textarea instead of just outputing the JList elements info directly in to the textarea.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.lang.System.*;
public class ListModel extends JFrame {
private JList list;
private DefaultListModel model;
private JTextField inputf;
private JTextField inpute;
private JTextArea text;
private JPanel p1;
private JPanel p2;
private ListSelectionModel ListSelectionModel;
public ListModel() {
setLayout(new FlowLayout());
DefaultListModel model = new DefaultListModel();
list = new JList(model);
JButton addButton = new JButton( "Lägg till" );
model.addElement("Kajsa Åslund");
model.addElement("Erik Carlsson");
model.addElement("John Åkesson");
model.addElement("Per-arne Ingvarsson");
model.addElement("Rebecka Asp");
model.addElement("Linnéa Åslund");
model.addElement("Åsa-Nisse Strong");
model.addElement("Super Lasse");
model.addElement("Alexander Ahl");
model.addElement("Ann Ahl");
model.addElement("Bo Sten");
addButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
final String name=inputf.getText() + " " + inpute.getText();
model.addElement( name );
}
}
);
JButton removeButton =
new JButton( "Ta bort" );
removeButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
setTitle("Borttagning");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
model.removeElement(list.getSelectedValue());
setTitle("Personer");
}
}
);
text = new JTextArea(5, 20);
text.setEditable(false);
inputf = new JTextField();
inputf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
inpute = new JTextField();
inpute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
list.setModel(model);
list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
text.setText(list.getSelectedValue().toString());
}
});
inpute.setBounds(5, 5, 100, 100);
inpute.setPreferredSize(new Dimension(120,20));
inputf.setBounds(10, 10, 150, 150);
inputf.setPreferredSize(new Dimension(120,20));
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(200,200));
JPanel p2 = new JPanel();
p2.add(text);
p2.add(inputf);
p2.add(inpute);
p2.add(addButton);
p2.add(removeButton);
p2.setLayout(new BoxLayout(p2,BoxLayout.Y_AXIS));
JPanel p1 = new JPanel();
p1.add(scroll);
Container container = getContentPane();
container.add(p1);
container.add(p2);
container.setLayout(new FlowLayout());
setDefaultCloseOperation( EXIT_ON_CLOSE );
setSize( 500, 250 );
setVisible( true );
}
public static void main( String args[] )
{
new ListModel();
}
}
Thanks in advance! :)
You can do that using for example BufferedWriter() and BufferedReader(), which are one of the basic java I/O API, and you can read about them here. It is worth to learn to use it.
To write a content of model to .txt file you can use loop, like this one:
for(Object string : model.toArray()){
out.write(t + "\n"); // "out" is BufferedWriter object
}
toArray() will take a data form model, and store it in an Object[] array. Then you can extract it with for each loop, and write into a file.
This will print a model content as a list inside .txt file, one name in one line.
Then, you can read it using BufferedReader(), line after line, an add avery line directly to JTextArea.
BTW. I think you ramove option does't work as it should. It is because, you need to select a item to remove it. But when you select it, ListSelectionListener() try to read a data form list, and throw NullPointerException() when item is removed. In effect it behave wierd. To fix it, it is enough to modify valueChanged():
public void valueChanged(ListSelectionEvent e) {
if(list.getSelectedValue()!=null) text.setText(list.getSelectedValue().toString());
}
It will read data from list, only it is not null (in other words removed).

JScrollPane does not work on JPanel

I have a frame that contains a mainPanel. This last will add other commandPanels (each one contains a button and a textField) Dynamically. the problem is that the JScrollPane does not appear to let me use the unseen commandPanels even if the mainPanel is full.
The below picture shows my case.
To initialize the window I wrote below code:
frame = new JFrame();
frame.setBounds(100, 100, 962, 639);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(264, 6, 692, 500);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
scroll = new JScrollPane();
scroll.getViewport().add(mainPanel);
frame.getContentPane().add(scroll);
and the method that add dynamically the new commandPanels is:
public void loadCommandPanel(String commandName)
{
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
mainPanel.add( scroll, BorderLayout.EAST);
frame.add( mainPanel);
...
}
Any help to get the scrollPane, will be much more than appreciated.
scroll.getViewport().add(mainPanel); is not how you use JViewport or JScrollPane; instead you should using something like this:
scroll.getViewport().setView(newCommandPanel);
or
scroll.setViewportView(newCommandPanel);
Take a look at How to Use Scroll Panes for more details.
Note also, this doesn't makes sense:
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
You add newCommandPanel to mainPanel, then promptly add it to another container (albeit incorrectly).
A component can only reside on a single parent; the moment you add it to another container, it is automatically removed from the previous container.
I have made some changes and it works perfectly now. For those who want the same thing here's my code:
import ...
public class mainUserInterface {
private JFrame frame;
private JPanel mainPanel;
private JPanel commandsPanel;
private JScrollPane commandsScrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainUserInterface window = new mainUserInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainUserInterface() {
initialize();
}
private void initialize() {
frame = new JFrame("CommandsExecutor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 700));
mainPanel = new JPanel(new BorderLayout(5,5));
mainPanel.setBorder( new TitledBorder("") );
commandsPanel = new JPanel();
commandsPanel.setLayout(new BoxLayout(commandsPanel, BoxLayout.Y_AXIS));
for(int i=0; i<15;i++){
commandsPanel.add(new CommandPanel());
}
commandsScrollPane = new JScrollPane(commandsPanel);
mainPanel.add(commandsScrollPane,BorderLayout.CENTER);
frame.setContentPane(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
and Here's the commandPanel class:
import ...
public class CommandPanel extends JPanel {
private JTextField commandResult;
private JButton commandBtn;
public CommandPanel()
{
this.setLayout( new BorderLayout(10,10));
this.setBorder( new TitledBorder("Command:") );
this.setMaximumSize(new Dimension(692,60));
this.setMinimumSize(new Dimension(692,60));
commandBtn = new JButton("Execute");
commandBtn.setMaximumSize(new Dimension(137, 34));
commandBtn.setMinimumSize(new Dimension(137, 34));
this.add(commandBtn, BorderLayout.WEST);
commandResult = new JTextField();
commandResult.setMaximumSize(new Dimension(518, 34));
commandResult.setMinimumSize(new Dimension(518, 34));
this.add(commandResult, BorderLayout.CENTER);
}
public JTextField getCommandResult() {
return commandResult;
}
public JButton getCommandBtn() {
return commandBtn;
}
public void setCommandResult(JTextField commandResult) {
this.commandResult = commandResult;
}
public void setCommandBtn(JButton commandBtn) {
this.commandBtn = commandBtn;
}
}
Thanks for all who answered my question, it really helped.

JTable, JComboBox - problems in showing JComboBox in second column

I have written this simple program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class JcomboboxJtableDemo extends JPanel
implements ActionListener {
private DefaultTableModel tableModel;
JTable table = new JTable (tableModel);
private JScrollPane scrollpaneTable = new JScrollPane( table );
private JPanel PaneBottoniTabella = new JPanel( );
public JcomboboxJtableDemo() {
super(new BorderLayout());
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JComboBox comboBox = new JComboBox(petStrings);
comboBox.setSelectedIndex(4);
tableModel = CreateTableModel();
tableModel.insertRow( 0, new Object[] {"Header col1", ""} );
tableModel.insertRow( 0, new Object[] {petStrings[0], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[1], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[2], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[3], ""} );
tableModel.setValueAt("Header col2", 0, 1);
DefaultCellEditor editor = new DefaultCellEditor(comboBox);
table.getColumnModel().getColumn(0).setCellEditor(editor);
table.getColumnModel().getColumn(1).setCellEditor(editor);
//Lay out the demo.
add(comboBox, BorderLayout.PAGE_START);
add(table, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
private final DefaultTableModel CreateTableModel () {
DefaultTableModel modello = new DefaultTableModel( new Object[] { "Col1","Col2" }, 0 ) {
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
};
table.setModel(modello);
return modello;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new JcomboboxJtableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I you try to run it you will see that there is a problem in showing correctly the JComboBox components in the second column, in the first column the are correctly shown and you can see each selected item as set in the code, instead in the second column there are some problems: none on the relative cell.
Could you tell me why? How can I solve the problem?
Thanks
You're using the same JComboBox component for both ColumnModel columns which in turn share the same ComboBoxModel. Any change in the selected item from one column will be reflected in the other column. Create a second combobox
JComboBox comboBox2 = new JComboBox(petStrings);
...
table.getColumnModel().getColumn(1).setCellEditor(editor2);
so that any changes can occur independently in either column.

JTable Won't Show On JPanel

Hi I have created a Jtable and can get it to show on my frame yet not on the JPanel I have ontop of my JFrame. I can't seem to change
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.;
import java.util.ArrayList;
import java.util.Comparator;
import javax.swing.;
import javax.swing.table.;
public class Main
{
DefaultTableModel table_model;
String[][] addressData = new String[10][5];
JPanel panel;
JFrame frame;
JButton loadData;
int count,index,row =0;
String thisLine;
ArrayList People = new ArrayList();
public Main()
{
//Creating JFrame and setting properties
frame = new JFrame();
frame.setResizable(false);
frame.setTitle("Address Book");
frame.setSize(800,600);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
//Creating JPanel and setting properties
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(new Color(77,81,84));
//Setting the table and Scroll Bars
this.table_model = new DefaultTableModel(addressData, new String[]{"First Name", "Surname", "Home Number", "Mobile Number", "Address", "Postcode"});
JTable table = new JTable(this.table_model);
table.setBounds(130, 40, 200, 200);
panel.add(new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
//Load Data button, reading file in and adding data to ArrayList then Array of Arrays
loadData = new JButton("Load File");
loadData.setBounds(10, 10, 100, 20);
loadData.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("file/address.buab"));
while ((thisLine = reader.readLine()) !=null)
{
if (row >= 4)
{
index++;
row = 0;
People.add(thisLine);
addressData[index][row] = People.get(count);
count++;
row++;
}
else
{
People.add(thisLine);
addressData[index][row] = People.get(count);
count++;
row++;
}
}
reader.close();
}
catch (IOException ex)
{
System.err.println("Input Exception, Check address.buab File");
}
}
});
panel.add(loadData);
//Auto sort on table fields
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(this.table_model);
sorter.setComparator(1, new Comparator<Integer>()
{
public int compare(Integer o1, Integer o2)
{
return o1.compareTo(o2);
}
public boolean equals(Object obj)
{
return obj.equals(this);
}
});
table.setRowSorter(sorter);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
public static void main(String[] args)
{
new Main();
}
}
Any ideas on how I might go about setting the table visible ontop of my JPanel
You need to create your JPanel with a specific layout manager and then add components (the JTable and JButton) with appropriate constraints to cause them to appear in the correct area of the panel. Currently you are setting the panel's layout manager to null, which is almost certainly incorrect. You may want to check out the Using Layout Managers tutorial.
One simple layout manager to consider is BorderLayout. For example:
// Create JPanel with BorderLayout layout manager.
JPanel panel = new JPanel(new BorderLayout());
// Add JTable to panel center. This component will expand
// to take up available space.
panel.add(myTableScrollPane, BorderLayout.CENTER);
// Add button to the bottom of the panel.
panel.add(myButton, BorderLayout.SOUTH);
A wild guess:
panel.setLayout(null);
Try this instead:
panel.setLayout(new BorderLayout());
And later:
panel.add(loadData, BorderLayout.SOUTH) // e.g. for the button
// e.g. for the table
panel.add(new JScrollPane(table, .....)), BorderLayout.CENTER)

Categories

Resources