How to make a randomized 2D Array depending on multiple variables? - java

I have code right now that takes user input to customize the the amount of rows and columns of a JTextArea, I want to use the same variables to make a 2d array with random values filling it, ranging from 0 to 2, I tried creating a nested for loop but ultimately failed. I can't find anything online that answers how to do this. Any help or advice appreciated. Below is all I have right now without anything to do this.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Main {
int tf1r = 0;
int tf2c = 0;
String space = ", ";
JPanel panel;
JLabel label;
JTextField tf1, tf2;
JButton set, reset;
JTextArea ta;
public static void main(String[] args) {
// Frame
JFrame frame = new JFrame("Mapped Array");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setResizable(false);
// Menu Bar
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("EXPORT");
JMenu m2 = new JMenu("HELP");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("TXT");
JMenuItem m22 = new JMenuItem("BAT");
m1.add(m11);
m1.add(m22);
// Panel Bottom and Components
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter Rows and Columns");
JTextField tf1 = new JTextField(10);
JTextField tf2 = new JTextField(10);
JButton set = new JButton("SET");
JButton reset = new JButton("RESET");
panel.add(label);
panel.add(tf1);
panel.add(tf2);
panel.add(set);
panel.add(reset);
// Center TextArea
JTextArea ta = new JTextArea();
// Components to Frame
frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, mb);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
//Sets Text
set.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String space = ", ";
String rows = tf1.getText();
String columns = tf2.getText();
int tf1r = Integer.parseInt(rows);
int tf2c = Integer.parseInt(columns);
ta.setRows(tf1r);
ta.setColumns(tf2c);
System.out.println("rows: "+tf1r+" columns: "+tf2c+" TaR: "+ta.getRows()+" TaC: "+ta.getColumns());
ta.setText(rows+space+columns+"\n100, 100\n");
}
});
//Resets Text
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ta.setText("");
}
});
}
}

This should work:
tf1r = Integer.parseInt(rows);
tf2c = Integer.parseInt(columns);
Random random = new Random();
int[][] values = new int[tf1r][tf2c];
for(int i = 0; i < values.length; i++)
for(int j = 0; j < values[i].length; j++)
values[i][j] = random.nextInt(3);

Check this.
public void actionPerformed(ActionEvent e) {
String space = ", ";
String rows = tf1.getText();
String columns = tf2.getText();
int tf1r = Integer.parseInt(rows);
int tf2c = Integer.parseInt(columns);
ta.setRows(tf1r);
ta.setColumns(tf2c);
Random random = new Random();
int[][] randomArray = new int[tf1r][tf2c];
for (int i = 0; i < tf1r; i++) {
for (int j = 0; j < tf2c; j++) {
randomArray[i][j] = random.nextInt(3);
}
}
System.out.println("rows: "+tf1r+" columns: "+tf2c+" TaR: "+ta.getRows()+" TaC: "+ta.getColumns());
ta.setText(rows+space+columns+"\n100, 100\n");
}

Related

miglayout with jtable with issue

I have used miglayout in swing applicaion.I have encounted one issue like jtable cant appear in whole frame it show only left side some area.
i want to show untill at right side end of jframe edge
My implemantaion code is below
package test;
import java.awt.EventQueue;
import java.util.Arrays;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
public class ProductPanel2 extends JPanel {
private JLabel lblProd;
private JButton butAdd;
private JButton butRemove;
private JButton butEdit;
private JScrollPane scroll;
private JTable table;
private static final long serialVersionUID = 1L;
public JList<String> lst_Options;
private JScrollPane scr_Data;
private JComboBox<ComboItem> cmb_Suppliers;
//Generar de inmediato
private JButton btn_NewUpdate;
private JButton btn_Delete;
private JButton btn_Copy;
private JTable tbl_Settings;
private JLabel lbl_SelectedOption;
DefaultListModel<String> modeloOpciones;
public ProductPanel2() {
initComponents();
}
private void initComponents() {
lblProd = new JLabel("Product List: ");
btn_NewUpdate = new JButton("Add");
btn_Delete = new JButton("Remove");
lbl_SelectedOption = new JLabel("Tipo de datos");
JLabel lbl_Opciones = new JLabel("Opciones");
lst_Options = new JList<String>();
modeloOpciones = new DefaultListModel<String>();
btn_Delete = new JButton("Eliminar");
btn_NewUpdate = new JButton("Nuevo");
scr_Data = new JScrollPane();
cmb_Suppliers = new JComboBox<ComboItem>();
modeloOpciones.addElement("Proveedores");
modeloOpciones.addElement("Productos");
modeloOpciones.addElement("Partidas");
lst_Options.setModel(modeloOpciones);
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
JPanel filterPanel=new JPanel();
setLayout(new MigLayout("debug", "[96px][][94.00][grow][149.00px][2px][161px]", "[16px][240px,grow][12px][29px]"));
//add(lbl_SelectedOption, "cell 1 0,alignx left,sgx");
add(lst_Options, "cell 0 1 1 5,grow");
filterPanel.add(scr_Data,"wrap, sg buttons");
// filterPanel.add(cmb_Suppliers, "");
add(filterPanel,"span 2 3, grow, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);
add(lbl_Opciones, "cell 0 0,growx,aligny top");
add(btn_Delete, "cell 6 3,alignx right,aligny bottom");
add(btn_NewUpdate, "cell 4 3,alignx right,aligny bottom");
refreshCombo(cmb_Suppliers);
}
private void refreshCombo(JComboBox<ComboItem> combo) {
combo.removeAllItems();
try {
combo.addItem(new ComboItem("0","ashjish"));
combo.addItem(new ComboItem("2","ashjish"));
combo.addItem(new ComboItem("3","ashjish"));
} catch (Exception e) {
//log.logToFile("refreshCombo: " + e.getClass().getName() + ": " + e.getMessage(), 1);
e.printStackTrace();
}
}
private JTable createTable() {
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
int rows = 30;
int cols = columnNames.length;
String[][] data = new String[rows][cols];
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
data[i][j] = "R"+i+" C"+j;
}
}
JTable table = new JTable(data, columnNames);
return table;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
ProductPanel2 pane = new ProductPanel2();
frame.setContentPane(pane);
frame.setSize(1000,1000);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
i dont want space betweeb combo and jtable whuich in mention at screenshot
package test;
import java.awt.EventQueue;
import java.util.Arrays;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
public class ProductPanel2 extends JPanel {
private JLabel lblProd;
private JButton butAdd;
private JButton butRemove;
private JButton butEdit;
private JScrollPane scroll;
private JTable table;
private static final long serialVersionUID = 1L;
public JList<String> lst_Options;
private JScrollPane scr_Data;
private JComboBox<ComboItem> cmb_Suppliers;
//Generar de inmediato
private JButton btn_NewUpdate;
private JButton btn_Delete;
private JButton btn_Copy;
private JTable tbl_Settings;
private JLabel lbl_SelectedOption;
private JPanel filterPanel;
private JLabel lbl_cmb_supplier;
private JButton btn_search;
public ProductPanel2() {
initComponents();
}
private void initComponents() {
lblProd = new JLabel("Product List: ");
lbl_cmb_supplier = new JLabel("Proveedor");
btn_NewUpdate = new JButton("Add");
btn_Delete = new JButton("Remove");
lbl_SelectedOption = new JLabel("Tipo de datos");
JLabel lbl_Opciones = new JLabel("Opciones");
cmb_Suppliers = new JComboBox<ComboItem>();
btn_Delete = new JButton("Eliminar");
btn_search = new JButton("Search");
btn_NewUpdate = new JButton("Nuevo");
scr_Data = new JScrollPane();
JComboBox<String> cmb_Suppliers = new JComboBox<String>();
JButton btn_New = new JButton("Nuevo");
JButton btn_Delete = new JButton("Cancelar");
JButton btn_PDF = new JButton("Crea PDF");
JButton btn_Send = new JButton("Envia por correo");
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
tbl_Settings.setPreferredScrollableViewportSize(tbl_Settings.getPreferredSize());
filterPanel = new JPanel();
/*setLayout(new MigLayout("","[right]"));
add(lbl_Opciones, "growx,aligny, top, wrap");
filterPanel.add(lbl_cmb_supplier, "split 2, wrap");
filterPanel.add(cmb_Suppliers, "wrap");
filterPanel.add(btn_search, "grow, spany, wrap");
add(filterPanel, "growx 5,split 2, flowy, top, sgx");
add(scr_Data, "width 100%, growx, push, span, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);*/
setLayout(new MigLayout("debug", "[122px][129px][23px][45px][148px,grow]", "[][100px,grow][]"));
add(lbl_Opciones, "growx, wrap");
filterPanel.add(lbl_cmb_supplier);
filterPanel.add(cmb_Suppliers);
filterPanel.add(btn_search, "grow, spany, wrap");
add(filterPanel, "wrap");
add(scr_Data, "width 100%, growx, push, span, wrap");
add(btn_New);
add(btn_PDF);
add(btn_Send);
add(btn_Delete);
refreshCombo(cmb_Suppliers);
}
private void refreshCombo(JComboBox<String> combo) {
combo.removeAllItems();
try {
} catch (Exception e) {
//log.logToFile("refreshCombo: " + e.getClass().getName() + ": " + e.getMessage(), 1);
e.printStackTrace();
}
}
private JTable createTable() {
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
int rows = 30;
int cols = columnNames.length;
String[][] data = new String[rows][cols];
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
data[i][j] = "R"+i+" C"+j;
}
}
JTable table = new JTable(data, columnNames);
return table;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
ProductPanel2 pane = new ProductPanel2();
frame.setContentPane(pane);
frame.setSize(1000,1000);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
You should re-think, how you are using the MigLayout! Please consider reading the quickstart guide: http://www.miglayout.com/QuickStart.pdf
Also your variable naming needs some work, it is very unclear, which variable is for what.
In order to solve your problem, do this:
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
// I have created a new Dimension-object. Those dimensions are FIXED! You might want to put a new dimension in, that is relative to the window size.
scr_Data.setPreferredSize(new Dimension(800, 800));
JPanel filterPanel=new JPanel();
Change this line (where you are setting absolute widths and heights for rows and columns!):
setLayout(new MigLayout("debug", "[96px][][94.00][grow][149.00px][2px][161px]", "[16px][240px,grow][12px][29px]"));
To this:
setLayout(new MigLayout());
Remove all the cells you have added, because you have mixed them with other layout-parts, that are not cells:
add(lst_Options, "grow");
filterPanel.add(scr_Data,"wrap");
// filterPanel.add(cmb_Suppliers, "");
add(filterPanel,"width 100%, growx, push, span, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);
add(lbl_Opciones, "growx,aligny top");
add(btn_Delete, "alignx right,aligny bottom");
add(btn_NewUpdate, "alignx right,aligny bottom");
Looks like this:
PS: I did not know that this would work:
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
The usual way is:
String[] columnNames = {"Name 1","Name 2","Name 3","Name 4","Name 5"};
I've learned something!
EDIT:
I've learned, that split() works by using regular expression, so you have to be careful, how to use it!
This will return an empty field and NOT "aaa" and "bbb":
"aaa.bbb".split(".");
Update:
I have updated my answer, this is the code in the initComponents()-method. I again urge you to read more about the MigLayout and stop mixing cell-components like this add(lst_Options, "cell 0 1,grow"); with non-cell components. This is messy and hard to understand / fix. I removed those cells in my answer and added alignments for the buttons. Now everything works as expected.
private void initComponents() {
lblProd = new JLabel("Product List: ");
btn_NewUpdate = new JButton("Add");
btn_Delete = new JButton("Remove");
lbl_SelectedOption = new JLabel("Tipo de datos");
JLabel lbl_Opciones = new JLabel("Opciones");
lst_Options = new JList<String>();
modeloOpciones = new DefaultListModel<String>();
btn_Delete = new JButton("Eliminar");
btn_NewUpdate = new JButton("Nuevo");
scr_Data = new JScrollPane();
cmb_Suppliers = new JComboBox<String>();
modeloOpciones.addElement("Proveedores");
modeloOpciones.addElement("Productos");
modeloOpciones.addElement("Partidas");
lst_Options.setModel(modeloOpciones);
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
tbl_Settings.setPreferredScrollableViewportSize(tbl_Settings.getPreferredSize());
setLayout(new MigLayout("","[right]"));
add(lbl_Opciones, "growx,aligny, top, wrap");
add(lst_Options, "grow");
add(scr_Data, "width 100%, growx, push, span, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);
btn_Delete.setHorizontalAlignment(SwingConstants.RIGHT);
btn_NewUpdate.setHorizontalAlignment(SwingConstants.RIGHT);
add(btn_Delete, "bottom, span 2");
add(btn_NewUpdate, "bottom");
refreshCombo(cmb_Suppliers);
}
Looks like this:

How to change the size of each component added to JFrame?

I'm trying to design a simple GUI, but no matter what i do, each panel I add to the JFrame becomes the same, unchangeable size. I tried all types of different layouts and they all haven't helped. What am I doing wrong? Also when I made my table scrollable, that also didn't work. It looks like this:
COMPLETE CODE:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class KMap extends JFrame
{
private ArrayList<String> variableNameList = new ArrayList<String>();
private String [] characters = {"A","B","C","D","E","F","G","H","I","J"};
private ArrayList<int[]> values = new ArrayList<int[]>();
private ArrayList<JButton> buttons = new ArrayList<JButton>();
public KMap()
{
setTitle("Karnaugh Map for COMP 228");
setLayout(new GridLayout(1,3));
createTopPane();
updateVarialbes(4);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
public void createTopPane()
{
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(10,1));
JLabel numVariablesString = new JLabel();
numVariablesString.setText("# Variables => ");
topPanel.add(numVariablesString);
JButton[] variableButton = new JButton[9];
for(int i = 0; i < variableButton.length; i++)
{
int numV = i+2;
variableButton[i] = new JButton();
variableButton[i].setText(Integer.toString(numV));
variableButton[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
removeLeftPane();
removeRightPane();
updateVarialbes(numV);
repaint();
}
});
topPanel.add(variableButton[i]);
}
add(topPanel);
}
public void updateVarialbes(int numV)
{
int combinations = (int) Math.pow(2,numV);
System.out.println(combinations);
System.out.println("New variables: " + numV);
values.clear();
variableNameList.clear();
for(int i = 0; i < numV; i++)
variableNameList.add(characters[i]);
System.out.println();
for(int i = 0; i < combinations; i++)
{
int binary[] = new int[numV];
if(i == 0)
for(int j = 0; j < numV; j++)
binary[j] = 0;
else
{
for(int z = 0; z < values.get(i-1).length; z++)
binary[z] = values.get(i-1)[z];
for(int a = numV-1; a >= 0; a--)
{
if(binary[a]==0)
{
binary[a]++;
break;
}
else
binary[a]=0;
}
}
values.add(binary);
for(int j = 0; j < values.get(i).length; j++)
System.out.print(values.get(i)[j]);
System.out.println();
}
createLeftPane(numV);
createRightPane(numV);
pack();
}
private JPanel leftPanel;
public void createLeftPane(int numV)//numV = number of variables to display
{
leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
String leftColNames [] = new String[numV];
Object[][] leftData = new Object[values.size()][numV];
for(int i = 0; i < leftColNames.length; i++)
leftColNames[i] = variableNameList.get(i);
for(int i = 0; i < values.size(); i++)
for(int j = 0; j < numV; j++)
leftData[i][j] = new Integer(values.get(i)[j]);
JTable leftTable = new JTable(leftData, leftColNames);
JPanel innerRightPanel = new JPanel();
String s = "F(";
for(int i = 0; i < numV; i++)
{
s+=characters[i];
if(i!=numV-1)
s+=",";
}
s+=(")");
System.out.println(s);
for(int i = 0; i < values.size(); i++)
{
JButton btn = new JButton();
btn.setText("0");
btn.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.WHITE));
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(Integer.parseInt(btn.getText()) == 1)
btn.setText("0");
else
btn.setText("1");
}
});
buttons.add(btn);
}
innerRightPanel.setLayout(new BoxLayout(innerRightPanel, BoxLayout.Y_AXIS));
innerRightPanel.setSize((2^numV)*5,5);
JLabel functionLabel = new JLabel();
functionLabel.setText(s);
innerRightPanel.add(functionLabel);
for(int i = 0; i < buttons.size(); i++)
{
innerRightPanel.add(buttons.get(i));
}
JScrollPane leftScrollTable = new JScrollPane(leftTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
leftScrollTable.setMaximumSize(new Dimension(100, 100));
leftPanel.add(leftScrollTable,BorderLayout.WEST);
leftPanel.add(innerRightPanel,BorderLayout.EAST);
add(leftPanel);
}
public void removeLeftPane()
{
remove(leftPanel);
}
public void createRightPane(int numV)
{
JPanel kPanel = new JPanel();
kPanel.setSize(100,100);
kPanel.setBackground(Color.BLACK);
add(kPanel);
}
public void removeRightPane()
{
}
}
no matter what i do, each panel I add to the JFrame becomes the same, unchangeable size.
setLayout(new GridLayout(1,3));
That is because you are using a GridLayout() which makes every component the same size. If you don't want that to happen then don't use a GridLayout.
Read the section from the Swing tutorial Using Layout Managers for examples of using each layout manager.
Also when I made my table scrollable, that also didn't work. It looks like this:
There is no reason for the table to be scrollable since all the rows a visible.
Don't really know what you are trying to do but I might suggest you just use the default BorderLayout of the JFrame. Then your code might be something like:
frame.add(buttonsPanel, BorderLayout.LINE_START);
frame.add(scrollPaneWithTable, BorderLayout.CENTER);
frame.add(blackPanel, BorderLayout,LINE_START);
Unrelated to the Swing questions, innerRightPanel.setSize((2^numV)*5,5); probably isn't setting the size you think it is - the ^ operator is Bitwise XOR in Java, not exponent.
Change the width argument to (int)Math.pow(2,numV)*5.

how to get the values from multiple textboxes in java swing

Hi I am working on an innovation in my company to handle the hits from the server so for that user has to add the service names in my application which is of monitoring application. So i have kept a button which will give the jtextfields counting to 9 so during submit button, how will i get the values from all the textboxes, below is my code,
package com.Lawrence;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Sample2 implements ActionListener
{
JFrame mainFrame;
static int count = 0;
static int width_textfield = 10;
static int height_textfield = 40;
static int height = 0;
JButton addTextField,submit;
JTextField virtualDirectories;
JLabel virtualDirectoriesName;
ArrayList<String> texts = new ArrayList<String>();
public Sample2()
{
mainFrame = new JFrame("Add Virtual Directory");
mainFrame.setSize(640,640);
mainFrame.setResizable(false);
mainFrame.setLayout(null);
addTextField = new JButton();
addTextField.setText("Add Virtual directory");
addTextField.setBounds(10, 10, 200, 25);
addTextField.addActionListener(this);
mainFrame.add(addTextField);
submit = new JButton();
submit.setText("Submit");
submit.setBounds(180, 560, 100, 25);
submit.addActionListener(this);
mainFrame.add(submit);
mainFrame.setVisible(true);
height = mainFrame.getHeight();
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()== "Add Virtual directory")
{
if(height_textfield <= height-80)
{
virtualDirectoriesName = new JLabel("Virtual Directory"+"\t"+":");
virtualDirectoriesName.setBounds(10,height_textfield,200, 25);
mainFrame.add(virtualDirectoriesName);
virtualDirectories = new JTextField();
virtualDirectories.setBounds(150,height_textfield,200,25);
mainFrame.add(virtualDirectories);
texts.add(virtualDirectories.getText());
count++;
//width_textfield++;
height_textfield = height_textfield+60;
mainFrame.revalidate();
mainFrame.repaint();
//http://www.dreamincode.net/forums/topic/381446-getting-the-values-from-mutiple-textfields-in-java-swing/
}
else
{
JOptionPane.showMessageDialog(mainFrame, "can only add"+count+"virtual Directories");
}
}
if(e.getActionCommand() == "Submit")
{
ArrayList<String> texts = new ArrayList<String>();
for(int i = 0; i< count;i++)
{
texts.add(virtualDirectories.getText());
}
System.out.println(texts.size());
System.out.println(texts.toString());
}
}
}
So i need to get the values from those textboxes and add it to an arraylist and then processing it to enter into my server for parsing the log files.So please explain me how to do it
You could store every textfield into an arraylist, just like you did with the texts. Also, please take a look at how to use layout managers.
ArrayList<JTextField> fields = new ArrayList<JTextField>();
fields.add(virtualDirectories);
for (int i = 0; i < count; i++) {
texts.add(fields.get(i).getText());
}
Edit:
This is a version of your code using layout managers. (plus the lines above, of course)
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Sample2 implements ActionListener {
JFrame mainFrame;
JPanel bottom;
JPanel center;
JPanel centerPanel1;
JPanel centerPanel2;
static int count = 0;
static int width_textfield = 10;
static int height_textfield = 40;
static int height = 0;
JButton addTextField, submit;
JTextField virtualDirectories;
JLabel virtualDirectoriesName;
ArrayList<JTextField> fields = new ArrayList<JTextField>();
ArrayList<String> texts = new ArrayList<String>();
int maxFields = 10;
public Sample2() {
mainFrame = new JFrame("Add Virtual Directory");
mainFrame.setSize(640, 640);
mainFrame.setResizable(false);
addTextField = new JButton();
addTextField.setText("Add Virtual directory");
addTextField.setBounds(10, 10, 200, 25);
addTextField.addActionListener(this);
submit = new JButton();
submit.setText("Submit");
submit.setBounds(180, 560, 100, 25);
submit.addActionListener(this);
center = new JPanel(new GridLayout(1, 2));
centerPanel1 = new JPanel(new GridLayout(maxFields, 1, 0, 20));
centerPanel2 = new JPanel();
center.add(centerPanel1);
center.add(centerPanel2);
bottom = new JPanel(new FlowLayout());
bottom.add(addTextField);
bottom.add(submit);
mainFrame.getContentPane().add(bottom, BorderLayout.SOUTH);
mainFrame.getContentPane().add(center, BorderLayout.CENTER);
mainFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "Add Virtual directory") {
if (count < maxFields) {
JPanel p = new JPanel(new GridLayout(1, 2));
virtualDirectoriesName = new JLabel("Virtual Directory" + "\t" + ":");
virtualDirectories = new JTextField();
p.add(virtualDirectoriesName);
p.add(virtualDirectories);
centerPanel1.add(p);
texts.add(virtualDirectories.getText());
fields.add(virtualDirectories);
count++;
// width_textfield++;
height_textfield = height_textfield + 60;
mainFrame.revalidate();
mainFrame.repaint();
// http://www.dreamincode.net/forums/topic/381446-getting-the-values-from-mutiple-textfields-in-java-swing/
} else {
JOptionPane.showMessageDialog(mainFrame, "can only add " + maxFields + " virtual Directories");
}
}
if (e.getActionCommand() == "Submit") {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < count; i++) {
texts.add(fields.get(i).getText());
}
System.out.println(texts.size());
System.out.println(texts.toString());
}
}
public static void main(String[] args) {
new Sample2();
}
}

Components don't get updated in my second frame

Ok so I have two JFrames. The first one is my main program. The second one is accessed by selecting an option on the menu of the first one. This second frame allows the user to enter values for different grades. For example, they are able to set the range of the grade "A" from 90 - 100 or from 85 - 100. Furthermore, they can add new grades like "A+" or "B-", and set ranges for them too.
If the user wants to add a grade, he uses the "Add Row" option on the menu titled "Actions". The frame prompts the user to enter the grade he wants to add (A+, or B-), he enters it and it should create a new row, with that grade, in the right place.
So there is where my problem begins. The headings and the grades are stored in an ArrayList of JLabels, and I wrote an algorithm to accurately predict the index of the new grade entered by the user ("B+" would be after "A-" and before "B"). So the entered grade is on the right position in my labels ArrayList. BUT for some reason, the new label doesn't add itself to my panel, and so cannot be seen by the user.
Some other information:
1. The panel uses grid bag layout - columns = 3 and rows = number of grades.
2. Each grade has two text fields, where the user enters the range value (I haven't added any functionality to the text fields, they're just there so I don't forget about them)
Here is the code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Adjustments implements ActionListener {
private JMenuBar menubar; // for adding more grades
private ArrayList<JTextField> textFields;
private ArrayList<JLabel> labels;
private JPanel panel;
private JFrame frame;
private ArrayList<GridBagConstraints> gbcs;
private JButton button;
#Override
public void actionPerformed(ActionEvent e) {
frame = new JFrame();
frame.setSize(Frame.LENGTH, Frame.HEIGHT);
frame.setDefaultCloseOperation(1);
frame.setTitle("Adjustments");
createComponents();
frame.setVisible(true);
}
private void createComponents() {
panel = new JPanel();
panel.setLayout(new GridBagLayout());
createLabels();
createTextFields();
createMenuBar();
createLayout();
frame.setJMenuBar(menubar);
}
private void createLayout() {
// This creates the layout. First makes the constraints, then adds everything to the panel
gbcs = new ArrayList<GridBagConstraints>();
for (int i = 0; i < labels.size() - 2; i++) {
for (int j = 0; j < 3; j++) {
gbcs.add(new GridBagConstraints());
gbcs.get((i * 3) + j).gridx = 100 + (100 * j);
gbcs.get((i * 3) + j).gridy = 100 + (100 * i);
}
}
// This is for the three headings on the top - "Grade", "From" and "To"
for (int i = 0; i < 3; i++) {
panel.add(labels.get(i), gbcs.get(i));
}
int l = 3, tf = 0; // l is the labels count, tf is for text fields
for (int i = 3; i < gbcs.size(); i++) {
if (i % 3 == 0) {
panel.add(labels.get(l), gbcs.get(i));
l++;
} else {
panel.add(textFields.get(tf), gbcs.get(i));
tf++;
}
}
frame.add(panel);
}
private void createLabels() {
// all the labels are made
labels = new ArrayList<JLabel>();
labels.add(new JLabel("Grade"));
labels.add(new JLabel("From"));
labels.add(new JLabel("To"));
labels.add(new JLabel("A"));
labels.add(new JLabel("B"));
// labels.add(new JLabel("B-"));
labels.add(new JLabel("C"));
labels.add(new JLabel("D"));
}
private void createTextFields() {
// there are two text fields on each row, starting from the 2nd
textFields = new ArrayList<JTextField>();
for (int i = 0; i < 8; i++) {
textFields.add(new JTextField(5));
}
}
private void createMenuBar() {
menubar = new JMenuBar();
// create and add the menu/menu items to the menubar
JMenu actions = new JMenu("Action");
JMenuItem addrow = new JMenuItem("Add Row");
actions.add(addrow);
class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String newGrade = JOptionPane.showInputDialog(frame, "What grade is this?");
if (newGrade.length() == 2) { // e.g.: ("B+")
String s = newGrade.substring(0, 1);
int index = 0; // index is the location of grade in the labels ArrayList
for (int i = 3; i < labels.size(); i++) {
if (s.equals(labels.get(i).getText())) {
index = i;
break;
}
}
String s2 = newGrade.substring(1);
if (s2.equals("-")) index++;
labels.add(index, new JLabel(newGrade));
textFields.add(new JTextField(5));
textFields.add(new JTextField(5));
}
panel.removeAll(); // removes everything from the panel to be readied again
createLayout(); // creates the layout everything
}
}
addrow.addActionListener(new Listener());
menubar.add(actions);
}
}
Why won't the new grades display on my frame?
Thanks for your help!
You've got some errors in your code.. but i have a solution for you.
Short answer: You forgot panel.revalidate(); & panel.repaint(); after recreating layout new.
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class gui implements ActionListener {
private JMenuBar menubar; // for adding more grades
private ArrayList<JTextField> textFields;
private ArrayList<JLabel> labels;
private JPanel panel;
private JFrame frame;
private ArrayList<GridBagConstraints> gbcs;
private JButton button;
#Override
public void actionPerformed(ActionEvent e) {
frame = new JFrame();
frame.setSize(Frame.WIDTH, Frame.HEIGHT);
frame.setDefaultCloseOperation(1);
frame.setTitle("Adjustments");
createComponents();
frame.setVisible(true);
frame.pack();
}
private void createComponents() {
panel = new JPanel();
panel.setLayout(new GridBagLayout());
createLabels();
createTextFields();
createMenuBar();
createLayout();
frame.add(panel);
frame.setJMenuBar(menubar);
}
private void createLayout() {
// This creates the layout. First makes the constraints, then adds
// everything to the panel
gbcs = new ArrayList<GridBagConstraints>();
for (int i = 0; i < labels.size()-2; i++) {
for (int j = 0; j < 3; j++) {
gbcs.add(new GridBagConstraints());
gbcs.get((i * 3) + j).gridx = 100 + (100 * j);
gbcs.get((i * 3) + j).gridy = 100 + (100 * i);
}
}
// This is for the three headings on the top - "Grade", "From" and "To"
for (int i = 0; i < 3; i++) {
panel.add(labels.get(i), gbcs.get(i));
}
int l = 3, tf = 0; // l is the labels count, tf is for text fields
for (int i = 3; i < gbcs.size(); i++) {
if (i % 3 == 0) {
panel.add(labels.get(l), gbcs.get(i));
l++;
} else {
panel.add(textFields.get(tf), gbcs.get(i));
tf++;
}
}
panel.revalidate();
panel.repaint();
}
private void createLabels() {
// all the labels are made
labels = new ArrayList<JLabel>();
labels.add(new JLabel("Grade"));
labels.add(new JLabel("From"));
labels.add(new JLabel("To"));
labels.add(new JLabel("A"));
labels.add(new JLabel("B"));
// labels.add(new JLabel("B-"));
labels.add(new JLabel("C"));
labels.add(new JLabel("D"));
}
private void createTextFields() {
// there are two text fields on each row, starting from the 2nd
textFields = new ArrayList<JTextField>();
for (int i = 0; i < 8; i++) {
textFields.add(new JTextField(5));
}
}
private void createMenuBar() {
menubar = new JMenuBar();
// create and add the menu/menu items to the menubar
JMenu actions = new JMenu("Action");
JMenuItem addrow = new JMenuItem("Add Row");
actions.add(addrow);
class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String newGrade = JOptionPane.showInputDialog(frame,
"What grade is this?");
if (newGrade.length() == 2) { // e.g.: ("B+")
String s = newGrade.substring(0, 1);
int index = 0; // index is the location of grade in the
// labels ArrayList
for (int i = 3; i < labels.size(); i++) {
if (s.equals(labels.get(i).getText())) {
index = i;
break;
}
}
String s2 = newGrade.substring(1);
if (s2.equals("-"))
index++;
labels.add(index, new JLabel(newGrade));
textFields.add(new JTextField(5));
textFields.add(new JTextField(5));
}
panel.removeAll(); // removes everything from the panel to be
// readied again
createLayout(); // creates the layout everything
}
}
addrow.addActionListener(new Listener());
menubar.add(actions);
}
}

JButton + radiobox + checkbox

I'd like this program I have to have some kind of "sum" button which will add in the column "Description" summarised information about the movie. Lets say I have "die hard" as a title, age 7 from radiobutton, and horror selected from the checkbox. Pressin the button would put "Die hard, 7, horror" under the column. I have no idea how to aproach this case.
package naplety.Swing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.JCheckBox;
public class SamodzielnaListaOsob extends JFrame implements ActionListener {
JButton dodaj, erease;
JTextField film;
DefaultListModel<String> listFilm;
DefaultTableModel tableFilm;
public SamodzielnaListaOsob(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JTextField film = new JTextField("Wpisz tytul filmu", 10);
film.setBorder(BorderFactory.createTitledBorder("Film"));
JPanel p1 = new JPanel();
p1.add(film);
JButton dodaj = new JButton("Add to list");
dodaj.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
listFilm.addElement(nowyFilm);
film.setText("");
}
}
});
JButton erease = new JButton("Clear");
erease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
film.setText("");
}
});
JButton dodajDoTabeli = new JButton("Add to table");
dodajDoTabeli.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
int ile = tableFilm.getRowCount();
tableFilm.addRow(new Object[] { ile + 1, nowyFilm });
}
}
});
JRadioButton sevenbutton = new JRadioButton("7");
JRadioButton twbutton = new JRadioButton("12");
JRadioButton sixbutton = new JRadioButton("16");
JRadioButton eightbutton = new JRadioButton("18");
ButtonGroup bg1 = new ButtonGroup();
bg1.add(sevenbutton);
bg1.add(twbutton);
bg1.add(sixbutton);
bg1.add(eightbutton);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(4, 0));
radioPanel.add(sevenbutton);
radioPanel.add(twbutton);
radioPanel.add(sixbutton);
radioPanel.add(eightbutton);
radioPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Age"));
radioPanel.setSize(200, 200);
JCheckBox Horror = new JCheckBox("Horror");
JCheckBox Komedia = new JCheckBox("Comedy");
JCheckBox Thriller = new JCheckBox("Thriller");
JCheckBoxMenuItem listac = new JCheckBoxMenuItem();
listac.add(Horror);
listac.add(Komedia);
listac.add(Thriller);
JPanel listaChceck = new JPanel();
listaChceck.add(Horror);
listaChceck.add(Komedia);
listaChceck.add(Thriller);
listaChceck.setLayout(new GridLayout(3, 0));
JPanel p2 = new JPanel();
p2.add(dodaj);
p2.add(erease);
p2.add(dodajDoTabeli);
p2.add(radioPanel);
p2.add(listaChceck);
listFilm = new DefaultListModel<String>();
listFilm.addElement("Achacy");
listFilm.addElement("Bonifacy");
listFilm.addElement("Cezary");
JList<String> lista = new JList<String>(listFilm);
JScrollPane sl = new JScrollPane(lista);
sl.setPreferredSize(new Dimension(150, 150));
sl.setBorder(BorderFactory.createTitledBorder("List"));
String[] kolumnyTabeli = { "Nr", "Movie", "Description" };
tableFilm = new DefaultTableModel(kolumnyTabeli, 0) {
};
JTable tabela = new JTable(tableFilm);
JScrollPane st = new JScrollPane(tabela);
st.setPreferredSize(new Dimension(300, 150));
st.setBorder(BorderFactory.createTitledBorder("Table"));
JPanel p3 = new JPanel();
p3.add(sl);
p3.add(st);
setPreferredSize(new Dimension(900, 900));
setVisible(true);
p1.add(p2);
p2.add(p3);
setContentPane(p1);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SamodzielnaListaOsob("List of movies");
}
});
}
}
You need to declare your variables either before you try to access them, or declare them global, which I did. I prefer this way.
Use .pack() on your frame to when you start the program, something actually shows.
Learn to use LayoutManagers for a better look.
Use arrays of RadioButtons and CheckBoxes so its easier to loop through them. I has to manually write a bunch of if statements, which would not be necessary if I could loop through them.
To get is a RadioButton or CheckBox is selected, use .isSelected()
.setVisible(true) after you add all your components.
Here's is your refactored code. I did nothing else to it, but fix the issue posted in your question. It now adds the info the desciption, when you hit the Add Film button.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class SamodzielnaListaOsob extends JFrame {
JButton dodaj, erease;
JTextField film;
DefaultListModel<String> listFilm;
DefaultTableModel tableFilm;
JList<String> lista = null;
JRadioButton sevenbutton = new JRadioButton("7");
JRadioButton twbutton = new JRadioButton("12");
JRadioButton sixbutton = new JRadioButton("16");
JRadioButton eightbutton = new JRadioButton("18");
JCheckBox Horror = new JCheckBox("Horror");
JCheckBox Komedia = new JCheckBox("Comedy");
JCheckBox Thriller = new JCheckBox("Thriller");
ButtonGroup bg1 = new ButtonGroup();
public SamodzielnaListaOsob(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JTextField film = new JTextField("Wpisz tytul filmu", 10);
film.setBorder(BorderFactory.createTitledBorder("Film"));
JPanel p1 = new JPanel();
p1.add(film);
JButton dodaj = new JButton("Add to list");
dodaj.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
listFilm.addElement(nowyFilm);
film.setText("");
}
}
});
JButton erease = new JButton("Clear");
erease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
film.setText("");
}
});
JButton dodajDoTabeli = new JButton("Add to table");
dodajDoTabeli.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
int ile = tableFilm.getRowCount();
String title = lista.getSelectedValue();
int age;
if (sixbutton.isSelected()) {
age = 16;
} else if (sevenbutton.isSelected()) {
age = 7;
} else if (eightbutton.isSelected()) {
age = 18;
} else {
age = 12;
}
String genres = "";
if (Horror.isSelected()) {
genres += "Horror, ";
}
if (Komedia.isSelected()) {
genres += "Komedia, ";
}
if (Thriller.isSelected()) {
genres += "Thriller";
}
String desc = title + ", " + age + ", " + genres;
tableFilm.addRow(new Object[]{ile + 1, nowyFilm, desc});
}
}
});
bg1.add(sevenbutton);
bg1.add(twbutton);
bg1.add(sixbutton);
bg1.add(eightbutton);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(4, 0));
radioPanel.add(sevenbutton);
radioPanel.add(twbutton);
radioPanel.add(sixbutton);
radioPanel.add(eightbutton);
radioPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Age"));
radioPanel.setSize(200, 200);
JCheckBoxMenuItem listac = new JCheckBoxMenuItem();
listac.add(Horror);
listac.add(Komedia);
listac.add(Thriller);
JPanel listaChceck = new JPanel();
listaChceck.add(Horror);
listaChceck.add(Komedia);
listaChceck.add(Thriller);
listaChceck.setLayout(new GridLayout(3, 0));
JPanel p2 = new JPanel();
p2.add(dodaj);
p2.add(erease);
p2.add(dodajDoTabeli);
p2.add(radioPanel);
p2.add(listaChceck);
listFilm = new DefaultListModel<String>();
listFilm.addElement("Achacy");
listFilm.addElement("Bonifacy");
listFilm.addElement("Cezary");
lista = new JList<String>(listFilm);
JScrollPane sl = new JScrollPane(lista);
sl.setPreferredSize(new Dimension(150, 150));
sl.setBorder(BorderFactory.createTitledBorder("List"));
String[] kolumnyTabeli = {"Nr", "Movie", "Description"};
tableFilm = new DefaultTableModel(kolumnyTabeli, 0) {
};
JTable tabela = new JTable(tableFilm);
JScrollPane st = new JScrollPane(tabela);
st.setPreferredSize(new Dimension(300, 150));
st.setBorder(BorderFactory.createTitledBorder("Table"));
JPanel p3 = new JPanel();
p3.add(sl);
p3.add(st);
p1.add(p2);
p2.add(p3);
setContentPane(p1);
pack();
setPreferredSize(new Dimension(900, 900));
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SamodzielnaListaOsob("List of movies");
}
});
}
}
Radio buttons and Check Buttons don't work like textfields. In a textfield, the useful values are picked up from the "text" member (example: getText()). A radioButton instead defines a set of fixed choices (well, you can make them dynamic, but it doesn't worth it, there are better components for that kind of work) like "yes" and "no". Usually, when you pickup some rabiobutton, you use the isChecked() method (returns boolean, it may be isChecked(), I don't remember) to react in one way or another. Example:
String age = 0;
if(sevenbutton.isSelected()){
age = 7;
}
Nonetheless, I think you can get the value from the text in the sevenbutton using getText(), but you're gonna need to check which radiobutton is checked anyway. A checkButton works in a pretty similar way, but for non-exclusive choices, so you need to use the isSelected() method, or similar, anyway.
Your method should look like:
private void addMovie(){
String age = "0";
String gender = "";
//Evaluate radioButtons
if(sevenbutton.isSelected()){
age = 7;
}
//Evaluate checkbuttons
if(Horror.isSelected()){
gender = gender+" horror";
}
String movie = film+" "+age+" "+gender;
//do anything else
}

Categories

Resources