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);
}
}
Related
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");
}
I have assigned the JButton cl to clear,
however in my program, and using (e.getSource() == cl)... it does not setText("") for each text field
I am not sure wether it is because I used an array for the JTextField or what...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EmployeesApplet extends JApplet implements ActionListener
{
public JButton sd = new JButton ("Salaried");
public JButton hr = new JButton ("Hourly");
public JButton cm = new JButton ("Commissioned");
public JButton cl = new JButton ("Clear");
private final int FIELDS = 8,
FIELD_WIDTH = 20;
private String[] strings = new String[FIELDS];
private TextFieldWithLabel[] tf = new TextFieldWithLabel[FIELDS];
private JTextArea ta = new JTextArea(5,25);
// Add arrays for readFields() method
public void init()
{
String[] s = {"First Name", "Last Name", "Employee ID", "(a) Salaried: Weekly Salary", "(b1) Hourly 1: Rate Per Hour",
"(b2) Hourly 2: Hours Worked" , "(c1) Commissioned: Rate", "(c2) Commissioned: Gross Sales" };
//----------------------
// Set up the Structure
//----------------------
Container c = getContentPane();
JPanel f = new JPanel(new FlowLayout());
JPanel b = new JPanel(new BorderLayout(2,0));
JPanel glb = new JPanel(new GridLayout(8,1,0,2));
JPanel gtf = new JPanel(new GridLayout(8,1,0,2));
JPanel flb = new JPanel(new FlowLayout());
// Add FlowLayout to the container
c.add(f);
// Add BorderLayout to the FlowLayout
f.add(b);
//---------------------------------------
//Add JPanels to the BorderLayout regions
//---------------------------------------
// Add JLables to GridLayout in West
b.add(glb, BorderLayout.WEST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
glb.add(tf[i].getLabel());
}
// Add JTextFeilds to GridLayout in East
b.add(gtf, BorderLayout.EAST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
tf[i].getTextField();
gtf.add(tf[i].getTextField());
}
// Add JButtons to FlowLayout in South
b.add(flb, BorderLayout.SOUTH);
flb.add(sd);
flb.add(hr);
flb.add(cm);
flb.add(cl);
sd.addActionListener(this);
hr.addActionListener(this);
cm.addActionListener(this);
cl.addActionListener(this);
// Add JTextArea and make it not editable
f.add(ta);
ta.setEditable(false);
}
//---------------------------------------
// Read all the JTextFields and
// save the contents in a parallel array
//---------------------------------------
private void readFields()
{
for (int i = 0; i < tf.length; i++) // or FIELDS
strings[i] = tf[i].getText();
}
//---------------------------------------------------------------------------
// Returns true if required JTextFields for selected employee are not empty
// Checks required JTextFields in top down order,
// displays error in stats are for first req that is empty and places focus
//----------------------------------------------------------------------------
private boolean fieldsExist(int i, int i2)
{
for (int index = 0; index < tf.length; index++)
{
}
showStatus("field is empty"); // Diplays error message in status area
tf[i].requestFocus(); // places focus in JTextField
return true;
}
//-----------------------------------------------------------------------------------------
// Returns true if all non-required JTextFields for the seleceted employee are empty
// Checks non-required JTextFields in top-down order ,
// displays error message in first non-req JTextField that is not empty and places focus
//-----------------------------------------------------------------------------------------
private boolean fieldsEmpty(int i, int i2)
{
showStatus("field should be empty"); // Diplays error message in status area
tf[i].requestFocus(); // Places focus in JTextField
return true;
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == cl)
{
for (int i = 0; i < tf.length; i++)
{
tf[i].setText("");
tf[1].requestFocus();
}
} // End clear if
}
}
and here is the TextFieldWithLabel class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class TextFieldWithLabel extends JTextField
{
private JTextField text_field;
private JLabel label;
private final static int WIDTH = 20;
public TextFieldWithLabel (String s, int w)
{
label = new JLabel(s);
text_field = new JTextField(w);
}
public JLabel getLabel() {return label;}
public JTextField getTextField() {return text_field;}
public String getText() {return text_field.getText();}
}
You want to set the text of the text_field field of your TextFieldWithLabel, not the text of TextFieldWithLabel.
tf[i].getTextField().setText("");
tf[1].getTextField().requestFocus();
Note that you could get rid of this text_field attribute, and use TextFieldWithLabel directly as the JTextField instead .
Better yet, have TextFieldWithLabel not extend JTextField, since it has no use, it is only a container class for two components.
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.
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();
}
}
I'm pretty new to programming, and I need to create a GUI for a pethouse program that allows the user to add, delete, and sort the records.
The problem is that for whatever reason my ActionListeners are not working. The GUI opens fine enough, but if I click on a menu item, nothing happens. The Quit MenuItem doesn't do anything, nor does the add animal do anything. The delete doesn't work either (though that may also be a programming error on my part.)
Here's the Code:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
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.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
import scrap.knockoff;
public class knockoff extends JFrame {
private ButtonHandler handler;
static int animals;
static Color Backgroundcolor = Color.red;
private JTable thelist;
private JTextField search, breed, category, buyprice, sellprice;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuAdd, menuDelete, menuQuit;
private JLabel maintitle, breedquery, categoryquery, buypricequery, sellpricequery;
private JButton sortbreed, sortcat, sortdog, sortratios, searchButton, add, delete, modify;
private JPanel animalPane, sortPane, titlePane, searchPane, tablePane, optionPane;
static Container container;
static int recnumber;
static String control[] = new String[100];
static double buyprices, sellprices, profitratios;
static String BreedName, CategoryName;
static String Pets[][] = new String[50][5];
public knockoff() {
super("The Peel Pet House Program"); //This just changes the name at the top there.
setSize(700, 600);
Border paneEdge = BorderFactory.createEmptyBorder(0, 10, 10, 10);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setLocation(0, 30);
tabbedPane.setSize(200, 100);
//These are our panels. The sortPane just keeps the buttons responsible for sorting the animals where they are. The animalPane is for the other functions (add, delete, whatnot) and the title pane
//just holds the title. The AnimalPane is just a constant, it's there just so that the Animals menu process has a place to be. The Table Pane holds the table.
tablePane = new JPanel();
tablePane.setLocation(200, 35);
tablePane.setSize(500, 500);
titlePane = new JPanel();
titlePane.setSize(700, 30);
animalPane = new JPanel();
Border greenline = BorderFactory.createLineBorder((Color.green).darker());
animalPane.setBorder(greenline);
animalPane.setLocation(0, 135);
animalPane.setSize(200, 400);
sortPane = new JPanel();
sortPane.setBorder(paneEdge);
search = new JTextField();
searchButton = new JButton("Search");
searchPane = new JPanel();
FlowLayout searchLayout = new FlowLayout();
searchPane.setLayout(searchLayout);
searchPane.setBorder(paneEdge);
search.setPreferredSize(new Dimension(190, 30));
searchPane.add(search);
searchPane.add(searchButton);
optionPane = new JPanel();
optionPane.setSize(100, 30);
//This establishes our table
String[] columns = {"Breed", "Category", "Buying Price", "Selling Price", "Profit Ratio"};
thelist = new JTable(Pets, columns);
JScrollPane listbrowser = new JScrollPane(thelist);
tablePane.add(listbrowser);
//These establish the buttons for our various sorting sprees.
sortbreed = new JButton("Breed");
sortcat = new JButton("Cat");
sortdog = new JButton("Dog");
sortratios = new JButton("Profit Ratio");
sortPane.add(sortbreed);
sortPane.add(sortcat);
sortPane.add(sortdog);
sortPane.add(sortratios);
//Our ever reliable menu bar maker.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
menu = new JMenu("File");
menuBar.add(menu);
//The items of the file menu.
menuQuit = new JMenuItem("Quit");
menuQuit.addActionListener(handler);
menu.add(menuQuit);
//Animal Menu Creation
menu = new JMenu("Animals");
menuBar.add(menu);
menuAdd = new JMenuItem("Add an Animal");
menuAdd.addActionListener(handler);
menu.add(menuAdd);
menuDelete = new JMenuItem("Delete Animal");
menuDelete.addActionListener(handler);
menu.add(menuDelete);
//Adding everything to the container now.
Container container = getContentPane();
container.setLayout(null);
maintitle = new JLabel("The Piddly Penultimate Peel Pet House Program");
titlePane.add(maintitle);
container.setBackground(Backgroundcolor.darker()); //This just makes a darker version of red to set as the background on the Content Pane. Grey is boring.
container.add(tablePane);
container.add(titlePane);
container.add(tabbedPane);
container.add(animalPane);
container.add(optionPane);
tabbedPane.addTab("Sort By:", null, sortPane, "Sorts the Table");
tabbedPane.addTab("Search", null, searchPane, "The Search Function");
}
public static void main(String args[]) {
knockoff application = new knockoff();
application.setVisible(true);
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.equals("Add an Animal")) {
addananimal();
} else if (event.equals("Delete Animal")) {
deleteanimal();
} else if (event.getSource().equals(add)) //getsource relates to the button, it just makes it so that anybody programming can freely change the text of the button without worrying about this.
{
addanimal();
} else if (event.getSource().equals(delete)) {
deleteanimal();
} else if (event.getSource().equals(sortbreed)) {
breedsort();
} else if (event.getSource().equals(sortcat)) {
} else if (event.getSource().equals(sortdog)) {
} else if (event.getSource().equals(sortratios)) {
} else if (event.equals("Quit")) {
hide();
System.exit(0);
}
}
//Add new Record Method
public void addananimal() {
container = getContentPane();
//Plate cleaner. Or dishwasher.
if (animalPane != null) {
container.remove(animalPane);
}
animalPane = new JPanel();
Border greenline = BorderFactory.createLineBorder((Color.green).darker());
animalPane.setBorder(greenline);
animalPane.setLocation(0, 135);
animalPane.setSize(200, 400);
FlowLayout animalLayout = new FlowLayout();
animalPane.setLayout(animalLayout);
breedquery = new JLabel("Add Animal Name:");
categoryquery = new JLabel("Cat or Dog?");
buypricequery = new JLabel("Buying Price:");
sellpricequery = new JLabel("Selling Price:");
animalPane.add(breedquery);
breed = new JTextField(18);
animalPane.add(breed);
animalPane.add(categoryquery);
category = new JTextField(18);
animalPane.add(category);
animalPane.add(buypricequery);
buyprice = new JTextField(18);
animalPane.add(buyprice);
animalPane.add(sellpricequery);
sellprice = new JTextField(18);
add = new JButton("Add Animal");
//The above list of .add and JComponent things were just to establish the
// contents of our new animalPane.
profitratios = Double.parseDouble(sellprice.getText()) / Double.parseDouble(buyprice.getText());
//This just makes finding the profit ratio an autonomous action.
add.addActionListener(handler);
animalPane.add(add);
container.add(animalPane);
setVisible(true);
}
public void addanimal() {
animals = animals + 1;
Pets[animals][0] = breed.getText();
Pets[animals][1] = category.getText();
Pets[animals][2] = buyprice.getText();
Pets[animals][3] = sellprice.getText();
Pets[animals][4] = profitratios + "";
breed.setText(" ");
category.setText(" ");
buyprice.setText(" ");
sellprice.setText(" ");
thelist.repaint(); //This is supposed to update the JTable in real time.
}
public void deleteanimal() {
removeSelectedRows(thelist);
}
public void removeSelectedRows(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int[] rows = table.getSelectedRows();
for (int x = 0; x < rows.length; ++x) {
model.removeRow(rows[x] - x);
}
for (int x = 0; x < animals; ++x) {
if (Pets[x][0].equalsIgnoreCase(table.getValueAt(table.getSelectedRow(), 0) + "")) {
Pets[x][0] = null;
Pets[x][1] = null;
Pets[x][2] = null;
Pets[x][3] = null;
Pets[x][4] = null;
}
}
}
public void breedsort() {
for (int x = 0; x < animals; ++x) {
}
}
}
}
You never initialize the ButtonHandler, meaning that every time you call addActionListener(handler) you are essentially calling addActionListener(null)
Try initializing the handler in the constructor BEFORE you add it to anything...
public knockoff() {
super("The Peel Pet House Program"); //This just changes the name at the top there.
handler = new ButtonHandler();
Updated
Better yet, take a look at the Action API instead
You're not instantiating and regstering ButtonHandler anywhere...