Get all column values from all JTable (ex: three tables) - java

Am struggling to get it working, have three tables trying to get all column values from all JTable(s) (Three tables) by clicking button "Read All Values".
When I use Vector data = tableModel.getDataVector();, returns only all columns values of the last table initiated.
Please give me directions, Thanks.
CODE:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
public class readAllJTableItem {
private JFrame frame;
private static JTextArea textAreaSD;
private static JTextArea textAreaPI;
private static JTextArea textAreaVL;
private TitledBorder textAreaTitleBorder = new TitledBorder(new EtchedBorder(), "Item(s)");
private static JCheckBox checkBoxTypeOne;
private static JCheckBox checkBoxTypeTwo;
private static JCheckBox checkBoxTypeThree;
//Table items
private JScrollPane scrollTableSD;
private JScrollPane scrollTablePI;
private JScrollPane scrollTableVL;
private JTable itemsTableSD;
private JTable itemsTablePI;
private JTable itemsTableVL;
private DefaultTableModel tableModel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
readAllJTableItem window = new readAllJTableItem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public readAllJTableItem() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 872, 587);
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ArrayList<String> addItems = new ArrayList<String>();
final int stedCntLpt_1[] = {0,1,2,3,4,5,6,7,8,9,10,11}; //total = 12
final int stedCntLpt_2[] = {0,1,2,3,4,5,6,7,8,9,10,12,13}; //total = 13
final int stedCntLpt_3[] = {0,1,3,7,14,15,16,17}; //total = 8
//Type-1 (0-11)
addItems.add(0, "Column-01"); addItems.add(1, "Column-02"); addItems.add(2, "Column-03"); addItems.add(3, "Column-04");
addItems.add(4, "Column-05"); addItems.add(5, "Column-06"); addItems.add(6, "Column-07"); addItems.add(7, "Column-08");
addItems.add(8, "Column-09"); addItems.add(9, "Column-10"); addItems.add(10, "Column-11"); addItems.add(11, "Column-12");
addItems.add(12, "Column-13"); addItems.add(13, "Column-14");
addItems.add(14, "Column-15"); addItems.add(15, "Column-16"); addItems.add(16, "Column-17"); addItems.add(17, "Column-18");
//1
JButton btnNewButton_1 = new JButton("Read All Values");
btnNewButton_1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//if (checkBoxTypeOne.isSelected() == true){
//This is were you get the cell values of each JTable
//#camickr's code...
DefaultTableModel model1 = (DefaultTableModel)itemsTableSD.getModel();
Vector data1 = model1.getDataVector();
System.out.println(data1.toString());
//}
}
});
btnNewButton_1.setBounds(281, 487, 125, 23);
frame.getContentPane().add(btnNewButton_1);
checkBoxTypeOne = new JCheckBox("SD");
checkBoxTypeOne.setBounds(685, 196, 87, 23);
frame.getContentPane().add(checkBoxTypeOne);
checkBoxTypeOne.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
callRenderTable(textAreaSD, scrollTableSD, itemsTableSD, addItems, stedCntLpt_1, 3, 12);
} else {
textAreaSD.setVisible(true);
scrollTableSD.setVisible(false);
};
}
});
checkBoxTypeTwo = new JCheckBox("PI");
checkBoxTypeTwo.setBounds(682, 288, 44, 23);
frame.getContentPane().add(checkBoxTypeTwo);
checkBoxTypeTwo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
callRenderTable(textAreaPI, scrollTablePI, itemsTablePI, addItems, stedCntLpt_2, 4, 13);
} else {
textAreaPI.setVisible(true);
scrollTablePI.setVisible(false);
};
}
});
checkBoxTypeThree = new JCheckBox("VL");
checkBoxTypeThree.setBounds(685, 374, 55, 23);
frame.getContentPane().add(checkBoxTypeThree);
checkBoxTypeThree.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
callRenderTable(textAreaVL, scrollTableVL, itemsTableVL, addItems, stedCntLpt_3, 2, 8);
} else {
textAreaVL.setVisible(true);
scrollTableVL.setVisible(false);
};
}
});
textAreaSD = new JTextArea();
textAreaSD.setBounds(43, 166, 608, 87);
textAreaSD.setBorder(textAreaTitleBorder);
textAreaSD.setBackground(new Color(240,240,240));
textAreaSD.setEditable(false);
textAreaSD.setVisible(true);
frame.getContentPane().add(textAreaSD);
scrollTableSD = new JScrollPane();
scrollTableSD.setBounds(43, 166, 608, 87);
scrollTableSD.setVisible(false);
frame.getContentPane().add(scrollTableSD);
textAreaPI = new JTextArea();
textAreaPI.setBounds(43, 256, 608, 103);
textAreaPI.setBorder(textAreaTitleBorder);
textAreaPI.setBackground(new Color(240,240,240));
textAreaPI.setEditable(false);
textAreaPI.setVisible(true);
frame.getContentPane().add(textAreaPI);
scrollTablePI = new JScrollPane();
scrollTablePI.setBounds(43, 256, 608, 103);
scrollTablePI.setVisible(false);
frame.getContentPane().add(scrollTablePI);
textAreaVL = new JTextArea();
textAreaVL.setBounds(43, 362, 608, 71);
textAreaVL.setBorder(textAreaTitleBorder);
textAreaVL.setBackground(new Color(240,240,240));
textAreaVL.setEditable(false);
textAreaVL.setVisible(true);
frame.getContentPane().add(textAreaVL);
scrollTableVL = new JScrollPane();
scrollTableVL.setBounds(43, 362, 608, 71);
scrollTableVL.setVisible(false);
frame.getContentPane().add(scrollTableVL);
itemsTableSD = new JTable();
scrollTableSD.setViewportView(itemsTableSD);
itemsTablePI = new JTable();
scrollTablePI.setViewportView(itemsTablePI);
itemsTableVL = new JTable();
scrollTableVL.setViewportView(itemsTableVL);
}
private void callRenderTable(JTextArea textArea, JScrollPane scrollTable, JTable itemsTable, ArrayList<String> addItems, int itemIndexNo[], int loopCount, int totCount){
textArea.setVisible(false);
scrollTable.setVisible(true);
//DefaultTableModel tableModel = new DefaultTableModel(){
tableModel = new DefaultTableModel(){
public Class<?> getColumnClass(int column){
switch(column){
case 0:
return String.class;
case 1:
return Boolean.class;
case 2:
return String.class;
case 3:
return Boolean.class;
case 4:
return String.class;
case 5:
return Boolean.class;
default:
return String.class;
}
}
int row = 0;
int column = 1;
boolean[] canEdit = new boolean[]{false, true, false, true, false, true};
#Override
public boolean isCellEditable(int row, int column) {
if (row == 0 && column == 1){
return false;}
return canEdit[column];
}
};
//Assign the model to table
itemsTable.setModel(tableModel);
tableModel.addColumn("Items");
tableModel.addColumn("Select");
tableModel.addColumn("Items");
tableModel.addColumn("Select");
tableModel.addColumn("Items");
tableModel.addColumn("Select");
//The row
int indIncr = 0;
for(int i = 0; i <= loopCount; i++){
tableModel.addRow(new Object[0]);
for(int j = 0; j <= 2; j++){
if (j == 0 && indIncr < totCount){
tableModel.setValueAt(addItems.get(itemIndexNo[indIncr]), i, j);
tableModel.setValueAt(true, i, j+1);
indIncr = indIncr + 1;}
if (j == 1 && indIncr < totCount ){
tableModel.setValueAt(addItems.get(itemIndexNo[indIncr]), i, j+1);
tableModel.setValueAt(true, i, j+2);
indIncr = indIncr + 1;}
if (j == 2 && indIncr < totCount){
tableModel.setValueAt(addItems.get(itemIndexNo[indIncr]), i, j+2);
tableModel.setValueAt(true, i, j+3);
indIncr = indIncr + 1;}
}
}
}
}

You only have one variable "tableModel" so how do you expect that variable to reference 3 table models?
You have 3 variables to reference each of your 3 tables.
So you need code like:
DefaultTableModel model1 = (DefaultTableModel)itsTableSD.getModel();
DefaultTableModel model2 = (DefaultTableModel)itsTablePI.getModel();
DefaultTableModel model3 = (DefaultTableModel)itsTableVL.getModel();
Now you can use the getDataVector() method on each of the table models.
Also, get rid of your static variables. In general variables should not be static.

Related

JScrollPane Not Appearing

I have looked at many of the other threads that are related to this, however none of the suggested fixes worked.
I have tried doing contentPanel.revalidate(); and contentPanel.repaint();, after adding it. I have tried adding both the JScrollPane and JTextArea to the contentPanel, and I have tried individually. I have tried changing from a JTextArea to a JTextPane, however none of that worked. The JTextArea shows up fine without the JScrollPane, but when I add it, the JTextArea completely disappears.
I am using a null layout, and I think that could be the issue, but if there is a solution that doesn't involve changing the layout, I would much prefer that. If there is no way to fix it other that changing the layout, please let me know. Thanks.
Here is the code (It is a JDialog window that is a popup off of the main window):
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class TransactionsDialog extends JDialog
{
private static final long serialVersionUID = 6939141004692809959L;
private final JPanel contentPanel = new JPanel();
private SimpleDateFormat monthDate = new SimpleDateFormat("MMMM");
private JTextArea txtTransactions;
private JComboBox<String> comboStartMonth;
private JComboBox<Integer> comboStartDay;
private JComboBox<Integer> comboStartYear;
private JComboBox<String> comboEndMonth;
private JComboBox<Integer> comboEndDay;
private JComboBox<Integer> comboEndYear;
private JCheckBox chckbxStartDate;
private JCheckBox chckbxEndDate;
/**
* Create the dialog.
*/
public TransactionsDialog(BankAccount account)
{
setResizable(false);
/**
* Populating (Day, Month, Year) Arrays.
*/
ArrayList<String> monthList = new ArrayList<String>();
for(int month = 0; month < 12; month++)
{
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
String monthName = monthDate.format(calendar.getTime());
monthList.add(monthName);
}
ArrayList<Integer> dayList = new ArrayList<Integer>();
for(int day = 1; day <= 31; day++)
{
dayList.add(day);
}
ArrayList<Integer> yearList = new ArrayList<Integer>();
for(int year = 1980; year <= Calendar.getInstance().get(Calendar.YEAR); year++)
{
yearList.add(year);
}
setTitle("Transactions of " + account);
setBounds(100, 100, 404, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
comboStartMonth = new JComboBox<String>();
comboStartMonth.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
comboStartMonth.setModel(new DefaultComboBoxModel<String>(monthList.toArray(new String[monthList.size()])));
comboStartMonth.setEnabled(false);
comboStartMonth.setBounds(100, 8, 118, 20);
contentPanel.add(comboStartMonth);
comboStartDay = new JComboBox<Integer>();
comboStartDay.setModel(new DefaultComboBoxModel<Integer>(dayList.toArray(new Integer[dayList.size()])));
comboStartDay.setEnabled(false);
comboStartDay.setBounds(228, 8, 71, 20);
comboStartDay.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboStartDay);
comboStartYear = new JComboBox<Integer>();
comboStartYear.setModel(new DefaultComboBoxModel<Integer>(yearList.toArray(new Integer[yearList.size()])));
comboStartYear.setSelectedIndex(comboStartYear.getItemCount() - 1);
comboStartYear.setEnabled(false);
comboStartYear.setBounds(309, 8, 71, 20);
comboStartYear.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboStartYear);
comboEndMonth = new JComboBox<String>();
comboEndMonth.setModel(new DefaultComboBoxModel<String>(monthList.toArray(new String[monthList.size()])));
comboEndMonth.setEnabled(false);
comboEndMonth.setBounds(100, 34, 119, 20);
comboEndMonth.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboEndMonth);
comboEndDay = new JComboBox<Integer>();
comboEndDay.setModel(new DefaultComboBoxModel<Integer>(dayList.toArray(new Integer[dayList.size()])));
comboEndDay.setEnabled(false);
comboEndDay.setBounds(228, 34, 71, 20);
comboEndDay.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboEndDay);
comboEndYear = new JComboBox<Integer>();
comboEndYear.setModel(new DefaultComboBoxModel<Integer>(yearList.toArray(new Integer[yearList.size()])));
comboEndYear.setSelectedIndex(comboEndYear.getItemCount() - 1);
comboEndYear.setEnabled(false);
comboEndYear.setBounds(309, 34, 71, 20);
comboEndYear.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
listTransactions(account);
}
});
contentPanel.add(comboEndYear);
txtTransactions = new JTextArea();
txtTransactions.setFont(new Font("Courier New", Font.PLAIN, 11));
txtTransactions.setEditable(false);
txtTransactions.setBounds(10, 63, 368, 187);
JScrollPane txtTScrollPane = new JScrollPane(txtTransactions);
contentPanel.add(txtTScrollPane);
contentPanel.revalidate();
contentPanel.repaint();
chckbxStartDate = new JCheckBox("Start Date:");
chckbxStartDate.setBounds(6, 7, 89, 23);
chckbxStartDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(chckbxStartDate.isSelected())
{
comboStartMonth.setEnabled(true);
comboStartDay.setEnabled(true);
comboStartYear.setEnabled(true);
}
else
{
comboStartMonth.setEnabled(false);
comboStartDay.setEnabled(false);
comboStartYear.setEnabled(false);
}
listTransactions(account);
}
});
contentPanel.add(chckbxStartDate);
chckbxEndDate = new JCheckBox("End Date:");
chckbxEndDate.setBounds(6, 33, 89, 23);
chckbxEndDate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(chckbxEndDate.isSelected())
{
comboEndMonth.setEnabled(true);
comboEndDay.setEnabled(true);
comboEndYear.setEnabled(true);
}
else
{
comboEndMonth.setEnabled(false);
comboEndDay.setEnabled(false);
comboEndYear.setEnabled(false);
}
listTransactions(account);
}
});
contentPanel.add(chckbxEndDate);
listTransactions(account);
}
private void listTransactions(BankAccount account)
{
LocalDateTime startTime;
LocalDateTime endTime;
String startMonthName = (String) comboStartMonth.getSelectedItem();
int startDay = (int) comboStartDay.getSelectedItem();
int startYear = (int) comboStartYear.getSelectedItem();
String endMonthName = (String) comboEndMonth.getSelectedItem();
int endDay = (int) comboEndDay.getSelectedItem();
int endYear = (int) comboEndYear.getSelectedItem();
if(chckbxStartDate.isSelected())
{
int startMonth = Month.valueOf(startMonthName.toUpperCase()).getValue();
try
{
startTime = LocalDateTime.of(startYear, startMonth, startDay, 0, 0);
}
catch(DateTimeException e)
{
txtTransactions.setText("INVALID DATE");
return;
}
}
else
{
startTime = null;
}
if(chckbxEndDate.isSelected())
{
int endMonth = Month.valueOf(endMonthName.toUpperCase()).getValue();
try
{
endTime = LocalDateTime.of(endYear, endMonth, endDay, 23, 59);
}
catch(DateTimeException e)
{
txtTransactions.setText("INVALID DATE");
return;
}
}
else
{
endTime = null;
}
ArrayList<Transaction> transactionList = account.getTransactions(startTime, endTime);
String output = "";
int maxAmountDigits = 1;
for(Transaction t : transactionList)
{
String stringAmount = String.format("%.2f", t.getAmount());
if(stringAmount.length() > maxAmountDigits)
maxAmountDigits = stringAmount.length();
}
output += String.format("%-10s %-8s %-" + (maxAmountDigits + 1) + "s %s\n", "Date", "Time", "Amount", "Description");
//https://stackoverflow.com/questions/37791455/java-string-format-adding-spaces-to-integers
output += String.format("%0" + 100 + "d\n", 0).replace("0", "-");
for(Transaction t : transactionList)
{
output += String.format("%d.%02d.%02d %02d:%02d:%02d $%-" + maxAmountDigits + ".2f %s\n", t.getTransactionTime().getYear(),
t.getTransactionTime().getMonthValue(),
t.getTransactionTime().getDayOfMonth(),
t.getTransactionTime().getHour(),
t.getTransactionTime().getMinute(),
t.getTransactionTime().getSecond(),
t.getAmount(),
t.getDescription());
}
txtTransactions.setText(output);
}
}
contentPanel.setLayout(null);
First you set the layout to null:
JScrollPane txtTScrollPane = new JScrollPane(txtTransactions);
contentPanel.add(txtTScrollPane);
//contentPanel.revalidate();
//contentPanel.repaint();
Then you add the scrollpane to the content panel. However, you didn't use setBounds() on the scrollpane and the default size of a component is (0, 0) so there is nothing to paint.
However, the solution is not to add the setBounds(...). The solution is to not use a null layout. It may seem easier with a null layout but then you get into problems like this and components don't work properly when used in a scrollpane.
So the proper solution is to fix your code and use Layout Managers. Swing was designed to be used with layout managers. Then the layout manager will set the size and location of the component so you don't have to worry about it.
The revalidate() and repaint() is only used when adding components to a visible GUI to invoke the layout manager so they are not needed.
Also when creating the text area do something like:
//txtTransactions = new JTextArea();
txtTransactions = new JTextArea(5, 20);
This will let the text area determine its own preferred size based on the rows/columns and font of the text area. Then the layout manager can do a better job.

setValueAt(...) jtable from combobox.selectedItem throws .ArrayIndexOutOfBoundsException: -1

i have a panel that contains labels and textfields to complete with order infromations and an empty jtable so when i click over add button an empty row will be added in the jtable that contains a comboBox with articles references thats meen when i select an item in the combbox the second and the third column will be loaded with article name and price using setvalueAt method in DefaultTableModel.
My problem is when i choose a reference in the comboBox it throws ArrayIndexOutOfBoundsException: -1 at the setValueAt line, so can any one please here help me !??
this is my code :
package vues.panel;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Date;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SpinnerDateModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import model.ArticleTableModel;
import model.beans.Article;
import model.beans.Commande;
import model.persistence.PersistentArticle;
public class CommandePanel extends JPanel {
private static final long serialVersionUID = 1L;
private JLabel lblIdCmd, lblDate, lblClient, lblTotal;
private JTextField tfIdCmd, tfClient, tfTotal;
private JSpinner spnDateCmd;
private JButton btAdd, btDelete, btSave;
private JScrollPane scp;
private JTable tab;
private TableColumn refColumn;
private JComboBox<Integer> comboBox;
private ArticleCommandeTableModel cmdArtModel;
public CommandePanel(){
setLayout(null);
initComponents();
remplirComboBox();
setActions();
setVisible(true);
}
public void initComponents(){
lblIdCmd = new JLabel("Id Commande : ");
tfIdCmd = new JTextField(12);
lblDate = new JLabel("Date Commande : ");
spnDateCmd = new JSpinner(new SpinnerDateModel());
spnDateCmd.setValue(Calendar.getInstance().getTime());
spnDateCmd.setEditor(new JSpinner.DateEditor(spnDateCmd,"dd/MM/yyyy hh:mm"));
lblClient = new JLabel("Client : ");
tfClient = new JTextField(12);
btAdd = new JButton("Ajouter Article");
btDelete = new JButton("Supprimer Article");
tab=new JTable();
tab.setModel(cmdArtModel= new ArticleCommandeTableModel());
tab.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
refColumn = tab.getColumnModel().getColumn(0);
scp =new JScrollPane(tab);
tab = new JTable();
comboBox = new JComboBox<>();
lblTotal = new JLabel("Total : ");
lblTotal.setFont(new Font("Verdana", Font.BOLD, 14));
tfTotal = new JTextField(12);
btSave = new JButton("Sauvegarder Commande");
lblIdCmd.setBounds(50, 15, 300, 25);
tfIdCmd.setBounds(220, 20, 146, 22);
lblDate.setBounds(50, 45, 300, 25);
spnDateCmd.setBounds(220, 50, 146, 22);
lblClient.setBounds(50, 75, 300, 25);
tfClient.setBounds(220, 80, 146, 22);
btAdd.setBounds(30, 145, 150, 25);
btDelete.setBounds(240, 145, 150, 25);
scp.setBounds(20, 200, 550, 300);
lblTotal.setBounds(375, 515, 300, 25);
tfTotal.setBounds(440, 515, 130, 25);
btSave.setBounds(175, 560, 200, 25);
add(lblIdCmd);
add(tfIdCmd);
add(lblDate);
add(spnDateCmd);
add(lblClient);
add(tfClient);
add(btAdd);
add(btDelete);
add(scp);
add(lblTotal);
add(tfTotal);
add(btSave);
}
public void setActions(){
btAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
chargerTab();
cmdArtModel.setRowCount(ArticleCommandeTableModel.rowCount++);
}
});
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(comboBox.getSelectedItem()!=null && comboBox.getSelectedIndex()>=0){
int ref = Integer.valueOf(comboBox.getSelectedItem().toString());
tab.setValueAt(ref, tab.getSelectedRow(), tab.getSelectedColumn());
}
}
});
}
public Commande getCommandeFromView(){
Commande c = new Commande();
c.setIdComande(Integer.valueOf(tfIdCmd.getText()));
c.setDateCmd(Date.valueOf(spnDateCmd.getValue().toString()));
c.setClient(tfClient.getText());
return c;
}
public void chargerTab(){
refColumn.setCellEditor(new DefaultCellEditor(comboBox));
//ArticleCommandeTableModel.count=cmdArtModel.getRowCount()+1;
cmdArtModel.addRow(new Vector<>());
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
refColumn.setCellRenderer(renderer);
}
public void remplirComboBox(){
List<Article> l;
try {
l = PersistentArticle.getArticles();
for(int i= 0;i<l.size();i++){
comboBox.addItem(l.get(i).getRef());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void remplirLibPu(int ref){
//tab.setValueAt(arg0, arg1, arg2)
}
}
class ArticleCommandeTableModel extends DefaultTableModel{
private static final long serialVersionUID = 1L;
String[] title ={"Ref Article", "Libelle", "PU", "Qté", "Total"};
Object[][] data;
static int rowCount =0;
public ArticleCommandeTableModel(){ }
public int getColumnCount(){
return 5;
}
// public int getRowCount(){
// if(data==null) return 0;
// return data.length;
// }
public String getColumnName(int col){
return title[col];
}
public boolean isCellEditable(int row, int col){
if(col==0||col==3)return true;
return false;
}
#Override
public void setValueAt(Object value, int row, int col) {
int ref = (Integer)value;
Article a=ArticleTableModel.getArticleByRef(ref);
if(col==0){
super.setValueAt(a.getLibelle(), row, 1);
super.setValueAt(a.getPu(), row, 2);
}
else{
super.setValueAt(value, row, col);
}
fireTableDataChanged();
}
#Override
public Object getValueAt(int row, int column) {
return super.getValueAt(row, column);
}
#Override
public void addRow(Vector rowData) {
super.addRow(rowData);
}
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected , boolean hasFocus, int row, int column) {
if(value instanceof JComboBox){
return (JComboBox) value;
}
else{
return null;
}
}
}

Java JTable Default table model cell edit and column size

I have a problem in my code that when using cell edit not allowed then the column size does not work properly
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.ListSelectionModel;
public class cTable extends JPanel {
private final int keyIndex;
private final int keyIncrement;
private ArrayList<String> tHeaderTitle;
private ArrayList<Integer> tHeaderWidth;
DefaultTableModel dataModel = new DefaultTableModel() {
#Override
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
JTable table = new JTable(dataModel);
public cTable(ArrayList<String> THeaderTitle, ArrayList< Integer> THeaderWidth, int KeyIndex, int KeyIncrement) {
if (THeaderTitle.isEmpty()) {
tHeaderTitle.add("Title1");
} else {
tHeaderTitle = new ArrayList<>(THeaderTitle);
}
if (THeaderWidth.isEmpty()) {
tHeaderWidth.add(30);
} else {
tHeaderWidth = new ArrayList<>(THeaderWidth);
}
keyIndex = KeyIndex;
keyIncrement = KeyIncrement;
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setAutoscrolls(true);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setAutoscrolls(true);
for (int i = 0; i < tHeaderTitle.size(); i++) {
dataModel.addColumn(tHeaderTitle.get(i));
table.getColumnModel().getColumn(i).setPreferredWidth(tHeaderWidth.get(i));
}
table.setPreferredScrollableViewportSize(new Dimension(TotalWidth(tHeaderWidth) + 110, 100));
table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowHeight(25);
add(scrollPane);
}
public void addColumn(String cName, int cWidth) {
dataModel.addColumn(cName);
table.getColumnModel().getColumn(dataModel.getColumnCount() - 1).setPreferredWidth(cWidth);
table.setPreferredScrollableViewportSize(new Dimension(TotalWidth(tHeaderWidth) + cWidth, 150));
tHeaderWidth.add(cWidth);
}
public void addRow(String[] values) {
boolean exists = false;
if (dataModel.getRowCount() == 0) {
dataModel.addRow(values);
} else {
for (int i = 0; i < dataModel.getRowCount(); i++) {
if (dataModel.getValueAt(i, keyIndex) == values[keyIndex]) {
dataModel.setValueAt(Integer.valueOf(String.valueOf(dataModel.getValueAt(i, keyIncrement))) + 1, i, keyIncrement);
exists = true;
}
}
if (!exists) {
dataModel.addRow(values);
}
}
}
private int TotalWidth(ArrayList<Integer> wl) {
int sum = 0;
for (Integer wl1 : wl) {
sum += wl1;
}
return sum;
}
}
and in my main frame class mainClass I used the cTable component to create my customized table but the column size does not appear to be right , actually it does not work and the cells should be editable
import javax.swing.JPanel;
........
public class mainClass {
public static void main(String args[]) {
......
// initialize frame settings to add a cTable component
......
ArrayList<Integer> TheaderWidth = new ArrayList<>();
ArrayList<String> TheaderTitle = new ArrayList<>();
cTable InvTable;
TheaderTitle.add("id");
TheaderTitle.add("Qty");
TheaderTitle.add("Description");
TheaderTitle.add("Notes");
TheaderWidth.add(30);
TheaderWidth.add(50);
TheaderWidth.add(200);
TheaderWidth.add(100);
InvTable = new cTable(TheaderTitle, TheaderWidth, 1, 2);
InvTable.setBounds(10, 10, 600, 300);
panel1.add(InvTable);
InvTable.setVisible(true);
this.pack();
}
}

Check if the jlabel icons are the same and compare with the components of the drawing lines

Hello I have to finish a project but I can't get further. The project is about having jlabels with icons generated dynamically on two sides (left and right) .
The icons are in different order on each side and there is a one to one icon relationship.
As an example one picture : link
Now you can draw lines from the left to the right between those pictures and after clicking on the check button it should tell you if its true or false :
Again one picture : link
My question is how can I compare the icons to know which combination is the right one and after comparing the drawings?
I already created two lists to know the component combination of the drawings.
Here is the code so far -
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class CatSameCoins{
public static JLabel label;
public ActionListener btn1Listener;
public ActionListener btn2Listener;
public ActionListener btn3Listener;
public ActionListener btn4Listener;
public ActionListener btn5Listener;
public ActionListener btn6Listener;
public JButton btn1;
public JButton btn2;
public JButton btn3;
public JButton btn4;
public JButton btn5;
public JButton btn6;
public JButton btnCheck;
public ArrayList<String> listto = new ArrayList<String>();
public ArrayList<String> listfrom = new ArrayList<String>();
public static boolean drawing = false;
public static List<Shape> shapes = new ArrayList<Shape> ();
public static Shape currentShape = null;
static Component fromComponent;
private JLabel lblCheck;
public void drawLine(Component from , Component to){
listfrom.add(from.getName()); //first list with component names from where the drawing start
listto.add(to.getName()); //second list with component names where the drawing ends
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX()+from.getWidth()/2; //get middle
fromPoint.y = from.getY()+from.getHeight()/2; //get middle
toPoint.x = to.getX()+to.getWidth()/2;
toPoint.y = to.getY()+to.getHeight()/2;
currentShape = new Line2D.Double (fromPoint, toPoint);
shapes.add (currentShape);
label.repaint();
drawing = false;
}
public CatSameCoins(){
JFrame frame = new JFrame ();
frame.getContentPane().setLayout(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
listfrom.removeAll(listfrom);
drawing= false;
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("btn1");
btn1.setBounds(21, 88, 45, 97);
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
btn1.removeActionListener(this);
}
};
btn1.addActionListener(btn1Listener);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("btn2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
btn2.removeActionListener(this);
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("btn3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
btn3.removeActionListener(this);
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("btn4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn4);
drawing = false;
btn4.removeActionListener(this);
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("btn5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn5);
drawing = false;
btn5.removeActionListener(this);
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("btn6");
btn6.setBounds(407, 307, 45, 91);
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn6);
drawing = false;
btn6.removeActionListener(this);
}
}
};
btn6.addActionListener(btn6Listener);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0;i< listfrom.size();i++){
System.out.println(listfrom.get(i)+" - "+listto.get(i));
}
lblCheck.setText("False");
//if().... lblCheck.setText("True")
//else lblCheck.setText("False")
/*if(btn6.getIcon().toString().equals(btn1.getIcon().toString())){
System.out.println("yes");
}
else{
System.out.println("neah");
}*/
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel (){
protected void paintComponent ( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
g2d.setPaint ( Color.black);
g2d.setStroke(new BasicStroke(5));
for ( Shape shape : shapes )
{
g2d.draw ( shape );
repaint();
}
}
} ;
label.setSize(500,500);
frame.getContentPane().add (label);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize ( 500, 500 );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
public static void main ( String[] args )
{
new CatSameCoins();
}
}
Would really appreciate for any help ;) .
Its done,
Solution : you can try it just change icon names for the second hashmap
I know this is not the best solution but at least i tried. I will try to improve it.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class Hashmap {
private JLabel label;
private ActionListener btn1Listener;
private ActionListener btn2Listener;
private ActionListener btn3Listener;
private ActionListener btn4Listener;
private ActionListener btn5Listener;
private ActionListener btn6Listener;
private JButton btn1;
private JButton btn2;
private JButton btn3;
private JButton btn4;
private JButton btn5;
private JButton btn6;
private JButton btnCheck;
private JButton btnNext;
private boolean drawing = false;
private Shape currentShape = null;
private Component fromComponent;
private JLabel lblCheck;
private List<Shape> shapes = new ArrayList<Shape>();
private HashMap<String, String> userLines = new HashMap<String, String>();
private HashMap<String, String> resultLines = new HashMap<String, String>();
private HashMap<String, String> icons = new HashMap<String, String>();
public void drawLine(Component from, Component to) {
userLines.put(from.getName(), to.getName());
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX() + from.getWidth() / 2; // get middle
fromPoint.y = from.getY() + from.getHeight() / 2; // get middle
toPoint.x = to.getX() + to.getWidth() / 2;
toPoint.y = to.getY() + to.getHeight() / 2;
currentShape = new Line2D.Double(fromPoint, toPoint);
shapes.add(currentShape);
label.repaint();
drawing = false;
}
#SuppressWarnings("serial")
public Hashmap() {
loadIcons();
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
drawing = false;
userLines.clear();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("1");
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
}
};
btn1.addActionListener(btn1Listener);
btn1.setBounds(21, 88, 45, 97);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn4);
drawing = false;
btn4.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn5);
drawing = false;
btn5.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("6");
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn6);
drawing = false;
btn6.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn6.addActionListener(btn6Listener);
btn6.setBounds(407, 307, 45, 91);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (resultLines.equals(userLines) && !userLines.isEmpty()) {
lblCheck.setText("true");
} else {
lblCheck.setText("false");
}
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
btnNext = new JButton("next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userLines.clear();
resultLines.clear();
shapes.removeAll(shapes);
drawing = false;
changeCombination();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
btnNext.setBounds(335, 435, 117, 25);
frame.getContentPane().add(btnNext);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.black);
g2d.setStroke(new BasicStroke(3));
for (Shape shape : shapes) {
g2d.draw(shape);
repaint();
}
}
};
label.setSize(frame.getWidth(), frame.getHeight());
frame.getContentPane().add(label);
frame.setVisible(true);
}
private void loadIcons() {
icons.clear();
icons.put("money/coin2/1_Cent.png", "money/coin2/1_Cent.png");
icons.put("money/coin2/5_Cent.png", "money/coin2/5_Cent.png");
icons.put("money/coin2/10_Cent.png", "money/coin2/10_Cent.png");
icons.put("money/coin2/20_Cent.png", "money/coin2/20_Cent.png");
icons.put("money/coin2/50_Cent.png", "money/coin2/50_Cent.png");
icons.put("money/coin2/2_Euro.png", "money/coin2/2_Euro.png");
icons.put("money/coin2/1_Euro.png", "money/coin2/1_Euro.png");
}
public void changeCombination() {
Random randLeftSide = new Random();
Random randRightSide = new Random();
while (resultLines.size() < 3) {
int left = randLeftSide.nextInt(3 - 1 + 1) + 1;
int right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("leftside: "+left+"rightside: "+y);
while (resultLines.containsKey(String.valueOf(left))) {
if (resultLines.size() > 3) {
break;
} else {
left = randLeftSide.nextInt(3 - 1 + 1) + 1;
// System.out.println("leftside : "+left);
}
}
while (resultLines.containsValue(String.valueOf(right))) {
if (resultLines.size() > 3) {
break;
} else {
right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("rightside: "+right);
}
}
resultLines.put(String.valueOf(left), String.valueOf(right));
}
// System.out.println("TOTAL MAP: "+resultLines.toString());
changeImages();
}
private void changeImages() {
List<Integer> randomIcon = new ArrayList<Integer>(); //creating array list for the icon random numbers
List<Integer> randomLines = new ArrayList<Integer>(); //creating array list for the lines random numbers
for (int i = 0; i < resultLines.size(); i++) {
int randomIndexIcon = new Random().nextInt(icons.size()); //generate random number for the icons from the hashmap
while (randomIcon.contains(randomIndexIcon)) { //while the list contains the random number generate a new one to prevent printing same pictures
randomIndexIcon = new Random().nextInt(icons.size());
}
randomIcon.add(randomIndexIcon); //add to the array list of the icon random numbers the generated random number
int randomIndexResult = new Random().nextInt(resultLines.size()); //generate random number for the lines
while (randomLines.contains(randomIndexResult)) { //while for second list to prevent generating same numbers
randomIndexResult = new Random().nextInt(resultLines.size());
}
randomLines.add(randomIndexResult); //add to the array list of the lines random numbers the generated random number
Object iconValue = icons.values().toArray()[randomIndexIcon]; //this is to get the icon string
Object valueLeft = resultLines.keySet().toArray()[randomIndexResult]; //this is to get the random key value from the resultLines map (left side)
if (valueLeft.equals("1")) { //check conditions
btn1.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("2")) {
btn2.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("3")) {
btn3.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
Object valueRight = resultLines.values().toArray()[randomIndexResult]; //get the values from the hashmap (right side)
if (valueRight.equals("4")) { //check conditions
btn4.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("5")) {
btn5.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("6")) {
btn6.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
}
}
public static void main(String[] args) {
new Hashmap();
}
}

How do I show a new Jframe when clicked on a button

I just want to go from one frame to the other.
I made a list where you could choose from and then when you would click the button confirm it should show a different window. Sadly it doens't.
This is the class from my first Jframe, so my first window with that confirm button:
package view;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.jgoodies.forms.factories.DefaultComponentFactory;
public class Scherm1pursco extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Scherm1pursco frame = new Scherm1pursco();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Scherm1pursco() {
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);
JLabel lblSelectCategory = DefaultComponentFactory.getInstance()
.createTitle("Select Category");
lblSelectCategory.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSelectCategory.setBounds(141, 49, 149, 16);
contentPane.add(lblSelectCategory);
ArrayList<String> purposeCategories = new ArrayList<String>();
purposeCategories.add("Behavioral");
purposeCategories.add("Structural");
purposeCategories.add("Creational");
JList list_purpose = new JList(purposeCategories.toArray());
list_purpose
.setToolTipText("Choose at least one categorie of purpose.");
list_purpose.setBounds(50, 121, 121, 63);
contentPane.add(list_purpose);
ArrayList<String> scopeCategories = new ArrayList<String>();
scopeCategories.add("Class");
scopeCategories.add("Object");
JList list_Scope = new JList(scopeCategories.toArray());
list_Scope.setToolTipText("Choose at least one categorie of Scope");
list_Scope.setBounds(244, 121, 121, 63);
contentPane.add(list_Scope);
JLabel lblPurpose = new JLabel("Purpose categories:");
lblPurpose.setBounds(50, 92, 121, 16);
contentPane.add(lblPurpose);
JLabel lblScopCategories = new JLabel("Scope categories:");
lblScopCategories.setBounds(244, 92, 121, 16);
contentPane.add(lblScopCategories);
Button button = new Button("Confirm>>");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (list_Scope.getSelectedValue().equals("Class")
&& (list_purpose.getSelectedValue()
.equals("Structural"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);;
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Class")
&& (list_purpose.getSelectedValue()
.equals("Behavioral"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Class")
&& (list_purpose.getSelectedValue()
.equals("Creational"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Object")
&& (list_purpose.getSelectedValue()
.equals("Structural"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Object")
&& (list_purpose.getSelectedValue()
.equals("Creational"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Class")
&& (list_purpose.getSelectedValue()
.equals("Behavioral"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals(null)
&& (list_purpose.getSelectedValue()
.equals(null))) {
System.out.println("error");
}
}
});
button.setBounds(169, 203, 79, 24);
contentPane.add(button);
}
}
This is my second Jframe, this the class where it should be referred to:
package view;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;
public class Scherm2FilterdPatterns extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
private boolean DEBUG = false;
private JTextField filterText;
private JTextField statusText;
private TableRowSorter<MyTableModel> sorter;
/**
* Launch the application.
*/
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();
}
});
}
/**
* Create the frame.
*/
public Scherm2FilterdPatterns() {
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// Create a table with a sorter.
MyTableModel model = new MyTableModel();
sorter = new TableRowSorter<MyTableModel>(model);
table = new JTable(model);
table.setRowSorter(sorter);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
// For the purposes of this example, better to have a single
// selection.
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// When selection changes, provide user with row numbers for
// both view and model.
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
int viewRow = table.getSelectedRow();
if (viewRow == 0) {
// Selection got filtered away.
statusText.setText("Diagram is");
} else {
System.out.print("THIS IS THE SOLUTION");
if (viewRow == 1) {
statusText.setText("diagram2 is");
} else {
int modelRow = table
.convertRowIndexToModel(viewRow);
statusText.setText(String.format("poep",
viewRow, modelRow));
if (viewRow == 2) {
statusText.setText("diagram3 is");
} else {
System.out.println("THIS IS THE SOLUTION");
}
}
}
}
});
// Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
// Add the scroll pane to this panel.
add(scrollPane);
// Create a separate form for filterText and statusText
JPanel form = new JPanel(new SpringLayout());
JLabel l1 = new JLabel("Filter on problem or consequences:",
SwingConstants.TRAILING);
form.add(l1);
filterText = new JTextField();
// Whenever filterText changes, invoke newFilter.
filterText.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
newFilter();
}
public void insertUpdate(DocumentEvent e) {
newFilter();
}
public void removeUpdate(DocumentEvent e) {
newFilter();
}
});
l1.setLabelFor(filterText);
form.add(filterText);
JLabel l2 = new JLabel("Select pattern for more info:",
SwingConstants.TRAILING);
form.add(l2);
statusText = new JTextField();
l2.setLabelFor(statusText);
form.add(statusText);
SpringUtilities.makeCompactGrid(form, 2, 2, 6, 6, 6, 6);
add(form);
}
/**
* Update the row filter regular expression from the expression in the text
* box.
*/
// filter on problem and consequences
private void newFilter() {
RowFilter<MyTableModel, Object> rf = null;
// If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter(filterText.getText(), 1, 2);
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rf);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = { "Pattern Name:", "Problem",
"Consequences", };
private Object[][] data = { { "Interpreter", "Smith", "Snowboarding" },
{ "Template Method", "Doe", "Rowing" },
{ "Chain of Responsibility", "Black", "Knitting", },
{ "Command", "White", "Speed reading", },
{ "Iterator", "Brown", "Pool" },
{ "Mediator", "Brown", "Pool", },
{ "Memento", "Brown", "Pool", },
{ "Observer", "Brown", "Pool", },
{ "State", "Brown", "Pool", },
{ "Strategy", "Brown", "Pool", },
{ "Visitor", "Brown", "Pool", }, };
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/ editor for
* each cell. If we didn't implement this method, then the last column
* would contain text ("true"/"false"), rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's editable.
*/
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's data can
* change.
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value + " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i = 0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j = 0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Filterd Patterns");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
TableFilterDemo newContentPane = new TableFilterDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
}
I am really stuck here, please help! Thank you for your time:) Sorry for my English
Your code seems too broad and unnecessary to demonstrate whereas the minimal code needed is very small.
Even then, I'm writing a brief answer to your question. Considering that you have to exit jframe1 and move to jframe2, In the action performed event of confirm button, just add the following lines :-
public static void jButton1 ActionPerformed......{
jFrame1.dispose();
jFrame2.setVisible(true);
}

Categories