I have a Problem with my code.
When I launch it, 2 panels are overlapingeven though, I declared one Panel as North and one as South.
EingabePanel is suppose to be on top and SchnittpunktPanel is suppose to be on the bottom.
here is the code, maybe someone can help me.
It's the first time I'm working on an GUI
package P2_pruefung.Frame;
import java.awt.*;
import javax.swing.*;
import P2_pruefung.Frame.Funktionen.CustomMath;
import P2_pruefung.Frame.Funktionen.MyActionListener;
import P2_pruefung.Objekte.Ungleichung;
import P2_pruefung.Objekte.UngleichungListe;
#SuppressWarnings("serial")
public class LinearFrame extends JFrame{
LayoutManager design1 = new BorderLayout();
LayoutManager design2 = new GridBagLayout();
GridBagConstraints rules = new GridBagConstraints();
public static JTextField tf_a = null;
public static JTextField tf_b = null;
public static JTextField tf_c = null;
public static JTextField tf_g = null;
public static JTextField tf_h = null;
public static JPanel eingabe = null;
public static JPanel schnittp = null;
public static JPanel grafik = null;
public static JPanel rechnen = null;
public static UngleichungListe unge = new UngleichungListe();
public static double g = 1;
public static double h = 1;
public LinearFrame(){
// Voreinstellung des Fensters
super("Lineare Optimierung");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1024,760);
this.setLocation(400,250);
JPanel oben = EingabePanel();
this.add(oben, BorderLayout.NORTH);
JPanel schnittp = SchnittpunktePanel();
this.add(schnittp, BorderLayout.SOUTH);
}
public JPanel EingabePanel() {
//Voreinstellungen für das Panel
eingabe = new JPanel();
eingabe.setLayout(design2);
rules.insets = new Insets(5,5,5,5);
rules.fill = GridBagConstraints.HORIZONTAL;
//Inhalt des Panels
// 1.Label
JLabel label1 = new JLabel("Bitte geben sie füre eine Ungleichung \"ax + bx <= c\" jeweils a, b und c ein");
rules.gridx = 1;
rules.gridy = 1;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label1, rules);
// Eingabe
JLabel label2 = new JLabel("a = ");
rules.gridx = 2;
rules.gridy = 2;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label2, rules);
JLabel label3 = new JLabel(" b = ");
rules.gridx = 3;
rules.gridy = 2;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label3, rules);
JLabel label4 = new JLabel(" c = ");
rules.gridx = 4;
rules.gridy = 2;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label4, rules);
tf_a = new JTextField();
rules.gridx = 2;
rules.gridy = 3;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(tf_a, rules);
tf_b = new JTextField();
rules.gridx = 3;
rules.gridy = 3;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(tf_b, rules);
tf_c = new JTextField();
rules.gridx = 4;
rules.gridy = 3;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(tf_c, rules);
JButton hinzu = new JButton("hinzufügen");
rules.gridx = 4;
rules.gridy = 4;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(hinzu, rules);
hinzu.addActionListener(MyActionListener.getInstance());
JLabel label5 = new JLabel("Bitte geben sie für eine Zielfunktion \"f(x;y) = gx + hx\" jeweils g und h ein");
rules.gridx = 1;
rules.gridy = 5;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label5, rules);
JLabel label6 = new JLabel("g = ");
rules.gridx = 2;
rules.gridy = 6;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label6, rules);
tf_g = new JTextField("1");
rules.gridx = 2;
rules.gridy = 7;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(tf_g, rules);
JLabel label7 = new JLabel("h = ");
rules.gridx = 3;
rules.gridy = 6;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label7, rules);
tf_h = new JTextField("1");
rules.gridx = 3;
rules.gridy = 7;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(tf_h, rules);
JButton akt = new JButton("Aktualisieren");
rules.gridx = 4;
rules.gridy = 7;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(akt, rules);
akt.addActionListener(MyActionListener.getInstance());
return eingabe;
}
public JPanel SchnittpunktePanel(){
//Voreinstellung des Panels
schnittp = new JPanel();
schnittp.setLayout(design2);
rules.insets = new Insets(5,5,5,5);
rules.fill = GridBagConstraints.HORIZONTAL;
JLabel label1 = new JLabel("Folgende Schnittpunkte des Lösungsploynoms sind bekannt: ");
rules.gridx = 1;
rules.gridy = 1;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label1, rules);
JLabel label2 = new JLabel("");
rules.gridx = 2;
rules.gridy = 2;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label2, rules);
int anz = unge.getSize();
boolean test = false;
Ungleichung[] id = new Ungleichung[anz];
String eingabe = "";
for( int i = 0; i <= anz; i++){
for ( Ungleichung s: unge.UngeListe){
if(s.getI() == i) {
id[i] = s;
}
}
}
for( int i = 0; i <= anz; i++){
for(int j = i+1; j < anz; j++){
double[] spunkt = CustomMath.getSchnittpunkt(id[i], id[j]);
if(spunkt == null) //nichts tun
for(Ungleichung s: unge.UngeListe){
if(s.checkUngleichung(spunkt[0], spunkt[1])){
test = true;
}
else{
test = false;
break;
}
}
if(test){
eingabe = eingabe + "(" + (Math.round(spunkt[0]*100)/100) + ";" + (Math.round(spunkt[1]*100)/100) + "), ";
}
}
}
return schnittp;
}
}
You should add components not to JFrame itself, but to JFrame.getContentPane().
this.getContentPant().setLayout(new BorderLayout());
this.getContentPant().add(BorderLayout.NORTH, new EingabePanel());
this.getContentPant().add(BorderLayout.SOUTH, new SchnittpunktePanel());
Okay guys, thanks for the help. I found it out myself. the problem was this part of code:
schnittp = new JPanel();
schnittp.setLayout(design2);
rules.insets = new Insets(5,5,5,5);
rules.fill = GridBagConstraints.HORIZONTAL;
JLabel label1 = new JLabel("Folgende Schnittpunkte des Lösungsploynoms sind bekannt: ");
rules.gridx = 1;
rules.gridy = 1;
rules.weightx = 1;
rules.weighty = 1;
eingabe.add(label1, rules);
I didn't add the labels to the Panel "schnittp", but to the Panel "eingabe"
Related
I am writing a program that displays patient records when entering a practitioner number (FHIR HAPI), but that is besides the point. I want to display basic patient details, and then through a checkbox, allow the user to add an extra column to the JTable that displays their details.
This extra column should be able to be added and removed depending on the state of the checkbox. However, when I try to use my DefaultTableModel variable to perform the model.addColumn() method, I always get a NullPointer exception.
The very last method is the one creating issues. I also provided code to the other methods that are called. I have tried using various types of arrays (Object and String) for the values and even arraylists. You will also see that in my second piece of code for the method getAllPatientObservationValues() I performed a println to see if it goes into the method and it does not. Any help will be much appreciated.
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener;
import java.text.ParseException;
public class GUIManager extends JFrame{
private Operations op;
private JPanel pnPnlMain;
private JPanel pnPnlTop;
private JCheckBox cbChkCholesterol;
private JPanel pnPnlMiddle;
private JTable tblLeft;
private DefaultTableModel tblLeftModel;
private JTable tblRight;
private DefaultTableModel tblRightModel;
private JButton btBtnAdd;
private JButton btBtnRemove;
private JPanel pnPnlBottom;
private JButton btBtnExit;
private JLabel lbLblTime;
private JTextField tfTxtSeconds;
private JLabel lbLblThreshhold;
private JTextField tfTxtThreshold;
public GUIManager(Operations inOP)
{
setSize(1000, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("FHIR Patient Monitor");
pnPnlMain = new JPanel();
pnPnlMain.setBorder( BorderFactory.createTitledBorder( "FHIR" ) );
GridBagLayout gbPnlMain = new GridBagLayout();
GridBagConstraints gbcPnlMain = new GridBagConstraints();
pnPnlMain.setLayout( gbPnlMain );
pnPnlTop = new JPanel();
pnPnlTop.setBorder( BorderFactory.createTitledBorder( "Column Details" ) );
GridBagLayout gbPnlTop = new GridBagLayout();
GridBagConstraints gbcPnlTop = new GridBagConstraints();
pnPnlTop.setLayout( gbPnlTop );
cbChkCholesterol = new JCheckBox( "Cholesterol");
gbcPnlTop.gridx = 2;
gbcPnlTop.gridy = 1;
gbcPnlTop.gridwidth = 6;
gbcPnlTop.gridheight = 1;
gbcPnlTop.fill = GridBagConstraints.BOTH;
gbcPnlTop.weightx = 1;
gbcPnlTop.weighty = 0;
gbcPnlTop.anchor = GridBagConstraints.NORTH;
gbPnlTop.setConstraints( cbChkCholesterol, gbcPnlTop );
pnPnlTop.add( cbChkCholesterol );
gbcPnlMain.gridx = 0;
gbcPnlMain.gridy = 0;
gbcPnlMain.gridwidth = 20;
gbcPnlMain.gridheight = 4;
gbcPnlMain.fill = GridBagConstraints.BOTH;
gbcPnlMain.weightx = 1;
gbcPnlMain.weighty = 0;
gbcPnlMain.anchor = GridBagConstraints.NORTH;
gbPnlMain.setConstraints( pnPnlTop, gbcPnlMain );
pnPnlMain.add( pnPnlTop );
pnPnlMiddle = new JPanel();
pnPnlMiddle.setBorder( BorderFactory.createTitledBorder( "Tables" ) );
GridBagLayout gbPnlMiddle = new GridBagLayout();
GridBagConstraints gbcPnlMiddle = new GridBagConstraints();
pnPnlMiddle.setLayout( gbPnlMiddle );
String [][]dataTblLeft = new String[1][2];
String []colsTblLeft = new String[] { "ID", "Full Name" };
tblLeftModel = new DefaultTableModel(dataTblLeft, colsTblLeft);
tblLeft = new JTable(tblLeftModel);
tblLeftModel.removeRow(0);
JScrollPane scpLeftTable = new JScrollPane(tblLeft);
scpLeftTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scpLeftTable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
gbcPnlMiddle.gridx = 0;
gbcPnlMiddle.gridy = 0;
gbcPnlMiddle.gridwidth = 9;
gbcPnlMiddle.gridheight = 12;
gbcPnlMiddle.fill = GridBagConstraints.NONE;
gbcPnlMiddle.weightx = 1;
gbcPnlMiddle.weighty = 1;
gbcPnlMiddle.anchor = GridBagConstraints.CENTER;
gbPnlMiddle.setConstraints( scpLeftTable, gbcPnlMiddle );
pnPnlMiddle.add(scpLeftTable);
String [][]dataTblRight = new String[1][7] ;
String []colsTblRight = new String[] { "ID", "Full Name", "Birthdate","Gender","City","State","Country"};
tblRightModel = new DefaultTableModel(dataTblRight, colsTblRight);
tblRight = new JTable(tblRightModel);
tblRight.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tblRightModel.removeRow(0);
JScrollPane scpRightTable = new JScrollPane(tblRight);
scpRightTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scpRightTable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
gbcPnlMiddle.gridx = 10;
gbcPnlMiddle.gridy = 0;
gbcPnlMiddle.gridwidth = 9;
gbcPnlMiddle.gridheight = 12;
gbcPnlMiddle.fill = GridBagConstraints.NONE;
gbcPnlMiddle.weightx = 1;
gbcPnlMiddle.weighty = 1;
gbcPnlMiddle.anchor = GridBagConstraints.CENTER;
gbPnlMiddle.setConstraints( scpRightTable, gbcPnlMiddle );
pnPnlMiddle.add( scpRightTable );
btBtnAdd = new JButton( "Add" );
gbcPnlMiddle.gridx = 2;
gbcPnlMiddle.gridy = 12;
gbcPnlMiddle.gridwidth = 5;
gbcPnlMiddle.gridheight = 2;
gbcPnlMiddle.fill = GridBagConstraints.NONE;
gbcPnlMiddle.weightx = 1;
gbcPnlMiddle.weighty = 0;
gbcPnlMiddle.anchor = GridBagConstraints.NORTH;
gbPnlMiddle.setConstraints( btBtnAdd, gbcPnlMiddle );
pnPnlMiddle.add( btBtnAdd );
btBtnRemove = new JButton( "Remove" );
gbcPnlMiddle.gridx = 12;
gbcPnlMiddle.gridy = 12;
gbcPnlMiddle.gridwidth = 5;
gbcPnlMiddle.gridheight = 2;
gbcPnlMiddle.fill = GridBagConstraints.NONE;
gbcPnlMiddle.weightx = 1;
gbcPnlMiddle.weighty = 0;
gbcPnlMiddle.anchor = GridBagConstraints.NORTH;
gbPnlMiddle.setConstraints( btBtnRemove, gbcPnlMiddle );
pnPnlMiddle.add( btBtnRemove );
gbcPnlMain.gridx = 0;
gbcPnlMain.gridy = 4;
gbcPnlMain.gridwidth = 20;
gbcPnlMain.gridheight = 15;
gbcPnlMain.fill = GridBagConstraints.BOTH;
gbcPnlMain.weightx = 1;
gbcPnlMain.weighty = 0;
gbcPnlMain.anchor = GridBagConstraints.NORTH;
gbPnlMain.setConstraints( pnPnlMiddle, gbcPnlMain );
pnPnlMain.add( pnPnlMiddle );
pnPnlBottom = new JPanel();
GridBagLayout gbPnlBottom = new GridBagLayout();
GridBagConstraints gbcPnlBottom = new GridBagConstraints();
pnPnlBottom.setLayout( gbPnlBottom );
btBtnExit = new JButton( "Exit" );
gbcPnlBottom.gridx = 16;
gbcPnlBottom.gridy = 0;
gbcPnlBottom.gridwidth = 4;
gbcPnlBottom.gridheight = 2;
gbcPnlBottom.fill = GridBagConstraints.NONE;
gbcPnlBottom.weightx = 1;
gbcPnlBottom.weighty = 0;
gbcPnlBottom.anchor = GridBagConstraints.EAST;
gbPnlBottom.setConstraints( btBtnExit, gbcPnlBottom );
pnPnlBottom.add( btBtnExit );
lbLblTime = new JLabel( "Refresh Rate:" );
gbcPnlBottom.gridx = 0;
gbcPnlBottom.gridy = 0;
gbcPnlBottom.gridwidth = 6;
gbcPnlBottom.gridheight = 1;
gbcPnlBottom.fill = GridBagConstraints.BOTH;
gbcPnlBottom.weightx = 1;
gbcPnlBottom.weighty = 1;
gbcPnlBottom.anchor = GridBagConstraints.NORTH;
gbPnlBottom.setConstraints( lbLblTime, gbcPnlBottom );
pnPnlBottom.add( lbLblTime );
tfTxtSeconds = new JTextField( );
gbcPnlBottom.gridx = 6;
gbcPnlBottom.gridy = 0;
gbcPnlBottom.gridwidth = 8;
gbcPnlBottom.gridheight = 1;
gbcPnlBottom.fill = GridBagConstraints.BOTH;
gbcPnlBottom.weightx = 1;
gbcPnlBottom.weighty = 0;
gbcPnlBottom.anchor = GridBagConstraints.WEST;
gbPnlBottom.setConstraints( tfTxtSeconds, gbcPnlBottom );
pnPnlBottom.add( tfTxtSeconds );
lbLblThreshhold = new JLabel( "Threshold:" );
gbcPnlBottom.gridx = 0;
gbcPnlBottom.gridy = 1;
gbcPnlBottom.gridwidth = 6;
gbcPnlBottom.gridheight = 1;
gbcPnlBottom.fill = GridBagConstraints.BOTH;
gbcPnlBottom.weightx = 1;
gbcPnlBottom.weighty = 1;
gbcPnlBottom.anchor = GridBagConstraints.NORTH;
gbPnlBottom.setConstraints( lbLblThreshhold, gbcPnlBottom );
pnPnlBottom.add( lbLblThreshhold );
tfTxtThreshold = new JTextField( );
gbcPnlBottom.gridx = 6;
gbcPnlBottom.gridy = 1;
gbcPnlBottom.gridwidth = 8;
gbcPnlBottom.gridheight = 1;
gbcPnlBottom.fill = GridBagConstraints.BOTH;
gbcPnlBottom.weightx = 1;
gbcPnlBottom.weighty = 0;
gbcPnlBottom.anchor = GridBagConstraints.NORTH;
gbPnlBottom.setConstraints( tfTxtThreshold, gbcPnlBottom );
pnPnlBottom.add( tfTxtThreshold );
gbcPnlMain.gridx = 0;
gbcPnlMain.gridy = 19;
gbcPnlMain.gridwidth = 20;
gbcPnlMain.gridheight = 2;
gbcPnlMain.fill = GridBagConstraints.BOTH;
gbcPnlMain.weightx = 1;
gbcPnlMain.weighty = 0;
gbcPnlMain.anchor = GridBagConstraints.NORTH;
gbPnlMain.setConstraints( pnPnlBottom, gbcPnlMain );
pnPnlMain.add( pnPnlBottom );
getContentPane().add(pnPnlMain);
}
public void addExitListener(ActionListener listen)
{
btBtnExit.addActionListener(listen);
}
public void addAddListener(ActionListener listen)
{
btBtnAdd.addActionListener(listen);
}
public void addRemoveListener(ActionListener listen)
{
btBtnRemove.addActionListener(listen);
}
public void addCholesterolListener(ActionListener listen) { cbChkCholesterol.addActionListener(listen);}
public JCheckBox getChkCholesterol() { return cbChkCholesterol;}
public DefaultTableModel getRightTableModel()
{
return this.tblRightModel;
}
public DefaultTableModel getLeftTableModel()
{
return this.tblLeftModel;
}
public JTable getLeftTable()
{
return this.tblLeft;
}
public JTable getRightTable()
{
return this.tblRight;
}
public void addRowToRightTable(Object[] newData)
{
tblRightModel.insertRow(tblRight.getRowCount(), newData);
}
public void populateLeftTable(String[][] data)
{
for(int i = 0; i < data.length; i++)
{
Object[] tempData = data[i];
tblLeftModel.insertRow(tblLeft.getRowCount(), tempData);
}
}
public void addColumnToRightTable(String code) throws ParseException {
tblRightModel.addColumn("Cholesterol",op.getAllPatientObservationValues(code));
}
}
public Object[] getAllPatientObservationValues(String code) throws ParseException {
System.out.println("In this method");
ArrayList<String> values = new ArrayList<>();
for (int i = 0; i < allPatients.size(); i++)
{
values.add(allPatients.get(i).getObservationValue(code));
}
return values.toArray();
}
Update: I saw that when I create my table I have a 2D array for the data set as one row 7 columns and thought that was the problem, but when I increased the size of it to say 8 or left it blank, then it still threw an error
It seems like you've forgotten to set the Operations object op to inOP.
This:
public GUIManager(Operations inOP)
{
setSize(1000, 650);
Should be this:
public GUIManager(Operations inOP)
{
op = inOP;
setSize(1000, 650);
I'm not sure what you were planning to do with inOP and op (deep copy of inOP?), but right now op is null. That's probably where your NullPointerException is coming from, in the line:
tblRightModel.addColumn("Cholesterol",op.getAllPatientObservationValues(code));
How to expand JButton in GridBagLayout?
I tried setting the weights of the GridBagConstraints to non-zero values:
gbc.weightx = gbc.weighty = 1.0;
But it's only expanding width of the buttons, I want buttons to expand vertically too.
Here is the code in which I add buttons in grid:
private void initGui(){
setTitle("Calculator");
setSize(400,500);
var grid = new GridBagLayout();
setLayout(grid);
GridBagConstraints gridCon = new GridBagConstraints();
gridCon.weightx = gridCon.weighty = 1.0;
gridCon.gridy = 0;
gridCon.gridx = 0;
gridCon.gridwidth = 4;
gridCon.fill = gridCon.HORIZONTAL;
add(text,gridCon);
gridCon.gridwidth = 1 ;
String names[] = {"+","-","/","*","="};
for(int i = 0;i < 5; i++){
opeButtons[i] = new JButton(names[i]);
}
gridCon.gridx = 3;
for( int y = 1; y < 6; y++ ){
gridCon.gridy = y;
add(opeButtons[y-1],gridCon);
}
for(int y = 2, i = 1; y < 5; y++ ){
for(int x = 0 ; x < 3; x++,i++) {
gridCon.gridx = x;
gridCon.gridy = y;
numButtons[i] = new JButton(Integer.toString(i));
add(numButtons[i],gridCon);
}
}
gridCon.gridx = 0;
gridCon.gridy = 1;
add(lb,gridCon);
gridCon.gridx = 1;
add(rb,gridCon);
gridCon.gridx = 2;
add(cb,gridCon);
numButtons[0] = new JButton("0");
gridCon.gridx = 0;
gridCon.gridy = 5;
gridCon.gridwidth = 2;
add(numButtons[0],gridCon);
gridCon.gridwidth = 1;
gridCon.gridx = 2;
add(decb,gridCon);
}
Replace
gridCon.fill = gridCon.HORIZONTAL;
with
gridCon.fill = GridBagConstraints.BOTH;
How to validate a textfield to enter only 10 digits mobile number in Swing?
I have three text field.
For name
For Contact
No. For Email
I want to click on submit button then check name, contact and email right or wrong. I also want to set limit of character
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class UpDateProfile extends JFrame implements ActionListener
{
JLabel name_lbl,email_lbl,contact_lbl;
JTextField name_text,email_text,contact_text;
JButton submit_btn;
public UpDateProfile()
{
super("Velidation demo");
setSize(650,450);
setLocation((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2-325,(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2-225);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
setResizable(false);
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.insets = new Insets(5,3,5,3);
name_lbl = new JLabel("Name :");
gbc1.gridx = 0;
gbc1.gridy = 0;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(name_lbl,gbc1);
name_text = new JTextField(30);
gbc1.gridx = 1;
gbc1.gridy = 0;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 3;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(name_text,gbc1);
email_lbl = new JLabel("E-mail :");
gbc1.gridx = 0;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(email_lbl,gbc1);
alt_email_text = new JTextField(30);
gbc1.gridx = 1;
gbc1.gridy = 1;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 3;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(alt_email_text,gbc1);
contact_lbl = new JLabel("Contact No. :");
gbc1.gridx = 0;
gbc1.gridy = 2;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(contact_lbl,gbc1);
contact_text = new JTextField(10);
gbc1.gridx = 1;
gbc1.gridy = 2;
gbc1.ipadx = 0;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 1;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.anchor = GridBagConstraints.WEST;
add(contact_text,gbc1);
submit_btn = new JButton("Submit");
submit_btn.addActionListener(this);
gbc1.gridx = 2;
gbc1.gridy = 7;
gbc1.ipadx = 10;
gbc1.ipady = 0;
gbc1.gridheight = 1;
gbc1.gridwidth = 2;
gbc1.anchor = GridBagConstraints.CENTER;
add(submit_btn,gbc1);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit_btn)
{
}
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit_btn)
{
String text = contact_text.getText();
if(text.matches("\\d{10}")){
// The text entered is a 10-digit number
}else{
// The text is not valid
}
}
}
This GUI is made from javax.swing. I'm wondering why it throws Array Index Out of Bounds exception but I'm sure that it's declared properly. I also tried running tests inside the for loops of the instantiation of the cells and the resetting of the cells but it still won't work. When I tried printing the i and j of the loop in the resetFields actionEvent it doesn't really go out of bounds but it says it goes out of bounds.
I found out that col adds one to itself when it goes to the actionPerformed function which is kinda weird.
NOTE: I get the row and col from the main class in another Java file.
Here's the full code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExperimentalFrame extends JFrame implements ActionListener
{
private int row, col;
private JTextField cells[][];
private JPanel matrix;
private JButton compute1;
private JButton reset;
private JButton showSolution1;
private JButton resetFields;
private JPanel matrixPanel;
private JPanel mainPanel;
private JPanel buttonPanel;
private JLabel theory;
private JPanel theoryPanel;
private JLabel header[];
public ExperimentalFrame(int row, int col)
{
this.row = row; this.col = col;
theoryPanel = new JPanel();
theory = new JLabel("Theory here");
mainPanel = new JPanel();
matrix = new JPanel();
matrixPanel = new JPanel();
buttonPanel = new JPanel();
cells = new JTextField[row][col];
header = new JLabel[col];
compute1 = new JButton("Compute");
reset = new JButton("Reset");
showSolution1 = new JButton("Show Solution");
resetFields = new JButton("Reset Fields");
GridBagConstraints gbc = new GridBagConstraints();
GridBagConstraints gbc2 = new GridBagConstraints();
GridBagConstraints gbc1 = new GridBagConstraints();
matrixPanel.setLayout(new GridBagLayout());
matrix.setLayout(new GridBagLayout());
mainPanel.setLayout(new GridBagLayout());
theoryPanel.setLayout(new GridBagLayout());
buttonPanel.setLayout(new GridBagLayout());
compute1.addActionListener(this);
reset.addActionListener(this);
showSolution1.addActionListener(this);
resetFields.addActionListener(this);
gbc1.gridx = 1;
gbc1.gridy = 1;
gbc1.insets = new Insets(10,10,10,10);
theoryPanel.add(theory);
mainPanel.add(theoryPanel, gbc1);
for (int j = 0; j < col; j++)
{
gbc.gridy = 1;
gbc.gridx = j + 2;
if (j != (col - 1))
header[j] = new JLabel("I" + (j + 1));
else
header[j] = new JLabel("x");
matrix.add(header[j], gbc);
}
gbc.insets = new Insets(5, 5, 5, 5);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
gbc.gridx = j + 2;
gbc.gridy = i + 3;
cells[i][j] = new JTextField(3);
System.out.println(i + " " + j);
matrix.add(cells[i][j], gbc);
}
}
for (int i = 0; i < row; i++)
{
gbc.gridx = 1;
gbc.gridy = i + 3;
matrix.add(new JLabel("Equation " + (i + 1) + ": "), gbc);
}
gbc2.insets = new Insets(10, 10, 10, 10);
gbc1.gridx = 1;
gbc1.gridy = 1;
gbc1.insets = new Insets(10,10,10,10);
matrixPanel.add(matrix, gbc1);
gbc1.gridy = 2;
gbc1.insets = new Insets(0, 10, 10, 10);
matrixPanel.add(compute1, gbc1);
matrixPanel.setBorder(BorderFactory.createLineBorder(Color.gray));
gbc1.gridx = 1;
gbc1.gridy = 2;
mainPanel.add(matrixPanel, gbc1);
//gbc1.gridy = 3;
gbc1.anchor = GridBagConstraints.LINE_END;
gbc1.gridx = 1; gbc1.gridy = 1;
gbc1.insets = new Insets(0, 5, 0, 0);
buttonPanel.add(reset, gbc1);
gbc1.gridx = 2; gbc1.gridy = 1;
buttonPanel.add(resetFields, gbc1);
gbc1.gridx = 1; gbc1.gridy = 3;
gbc1.insets = new Insets(0, 10, 10, 10);
mainPanel.add(buttonPanel, gbc1);
add(mainPanel);
pack();
setTitle("Experimental");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent ae)
{
Object o = ae.getSource();
JButton jb = (JButton) o;
if (jb == reset)
{
this.setVisible(false);
this.dispose();
new Experiment10();
}
else if (jb == resetFields)
{
System.out.println(row + " " + col);
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
{
System.out.println(i + " " + j);
cells[i][j].setText(""); //here
}
}
}
}
Here's the error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:6
at ExperimentalFrame.actionPerformed(ExperimentalFrame.java:140)
It's because, when you declare cells = new JTextField[row][col]; col is not equal to this.col (this.col = col + 1)
So when you go for for(int j = 0; j < col; j++) in actionPerformed j is out of bound for this.cells
For example, when you instantiate your class with col = 5, the cells will be created with a 5 width, however, this.col will be equal to 6, and j will go the 5 value in you for loop.
To correct you issue, do that
public ExperimentalFrame(int row, int col){
this.row = row; this.col = col;
or, if you really need col to be increased by one, which I personnaly think is odd,
public ExperimentalFrame(int row, int col){
col++;
this.row = row; this.col = col;
Ditch the class variables (row, col) and iterate based on the array size. There is no need to maintain row and column variables once the array is created.
for (int i = 0; i < cells.length; i++)
for (int j = 0; j < cells[i].length; j++) {
System.out.println(i + " " + j);
cells[i][j].setText("");
}
Works as expected.
I am having an issue with JTables
I know my code is a little hard to follow, it's also a little jumbled around because it's coming from a fairly big program. And yes I just learned about the java naming convention in which you don't start a variable with an uppercase letter.
final JFrame Menu = new JFrame("Crime Database 2013");
Dimension screenSize0 = Menu.getToolkit().getScreenSize();
Menu.setBounds(screenSize0.width / 4, screenSize0.height / 4,
screenSize0.width / 2, screenSize0.height / 2);
Menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Menu.setVisible(true);
JPanel options = new JPanel(new GridBagLayout());
GridBagConstraints a = new GridBagConstraints();
Menu.add(options);
JButton show = new JButton("Show all records");
a.gridx = 0;
a.gridy = 1;
options.add(show, a);
final JFrame Show = new JFrame("Crime Database 2013 - Show Records");
Dimension screenSize3 = Show.getToolkit().getScreenSize();
Show.setBounds(screenSize3.width/3 - 250, screenSize3.height/7,
screenSize3.width - 150, screenSize3.height-200);
Show.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Show.setLayout(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
final JPanel data = new JPanel(new FlowLayout());
JPanel sortselect = new JPanel(new GridBagLayout());
GridBagConstraints h = new GridBagConstraints();
g.gridx = 0;
g.gridy = 2;
Show.add(sortselect, g);
g.gridx = 0;
g.gridy = 0;
g.gridheight = 2;
g.gridwidth = 5;
Show.add(data, g);
JLabel label = new JLabel("Sort options");
JRadioButton none = new JRadioButton("No Sort",true);
JLabel frname = new JLabel("By First Name");
JRadioButton frnameup = new JRadioButton("First name - Alphabetical");
JRadioButton frnamedn = new JRadioButton("First name - Reverse-Alphabetical");
JLabel lsname = new JLabel("By Last Name");
JRadioButton lsnameup = new JRadioButton("Last name - Alphabetical");
JRadioButton lsnamedn = new JRadioButton("Last name - Reverse-Alphabetical");
JLabel byage = new JLabel("By Age");
JRadioButton ageup = new JRadioButton("Age - Increasing");
JRadioButton agedn = new JRadioButton("Age - Decreasing");
JLabel bycrime = new JLabel("By Crime");
JRadioButton crimeup = new JRadioButton("Crime - Alhabetically");
JRadioButton crimedn = new JRadioButton("Crime - Reverse-Alphabetical");
JLabel year = new JLabel("By Year of release");
JRadioButton yearup = new JRadioButton("Expected Year of Release - First");
JRadioButton yeardn = new JRadioButton("Expected Year of Release - Last");
ButtonGroup sortgroup = new ButtonGroup();
sortgroup.add(none);
sortgroup.add(frnameup);
sortgroup.add(frnamedn);
sortgroup.add(lsnameup);
sortgroup.add(lsnamedn);
sortgroup.add(ageup);
sortgroup.add(agedn);
sortgroup.add(crimeup);
sortgroup.add(crimedn);
sortgroup.add(yearup);
sortgroup.add(yeardn);
h.insets = new Insets(10,10,10,10);
h.gridx = 0;
h.gridy = 2;
sortselect.add(frname, h);
h.gridx = 0;
h.gridy = 3;
sortselect.add(frnameup, h);
h.gridx = 0;
h.gridy = 4;
sortselect.add(frnamedn, h);
h.gridx = 1;
h.gridy = 2;
sortselect.add(lsname, h);
h.gridx = 1;
h.gridy = 3;
sortselect.add(lsnameup, h);
h.gridx = 1;
h.gridy = 4;
sortselect.add(lsnamedn, h);
h.gridx = 2;
h.gridy = 2;
sortselect.add(byage, h);
h.gridx = 2;
h.gridy = 3;
sortselect.add(ageup, h);
h.gridx = 2;
h.gridy = 4;
sortselect.add(agedn, h);
h.gridx = 3;
h.gridy = 2;
sortselect.add(bycrime, h);
h.gridx = 3;
h.gridy = 3;
sortselect.add(crimeup, h);
h.gridx = 3;
h.gridy = 4;
sortselect.add(crimedn, h);
h.gridx = 4;
h.gridy = 2;
sortselect.add(year, h);
h.gridx = 4;
h.gridy = 3;
sortselect.add(yearup, h);
h.gridx = 4;
h.gridy = 4;
sortselect.add(yeardn, h);
h.gridwidth = 5;
h.gridheight = 1;
h.gridx = 0;
h.gridy =0;
sortselect.add(label, h);
h.gridx = 0;
h.gridy = 1;
sortselect.add(none, h);
show.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e1) {
Menu.setVisible(false);
int entries = 0;
BufferedReader lines = null;
try {
lines = new BufferedReader(new FileReader("L:\\workspace\\new java\\sources\\c-database.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
while (lines.readLine() != null) {
entries++;
}
} catch (IOException e2) {
e2.printStackTrace();
}
BufferedReader crimeinfo = null;
try {
crimeinfo = new BufferedReader(new FileReader("L:\\workspace\\new java\\sources\\c-database.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String namelist[] = new String[entries];
String agelist[] = new String[entries] ;
String crimelist[] = new String[entries];
String release[] = new String[entries];
for (int i = 0; i < entries; i++) {
String full = null;
try {
full = crimeinfo.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String split[] = full.split(",");
namelist[i] = split[0];
agelist[i] = split[1];
crimelist[i] = split[2];
release[i] = split[3];
}
String firstnamelist[] = new String[entries];
String lastnamelist[] = new String[entries];
for (int i = 0; i < entries; i++) {
String namesplit[] = namelist[i].split(" ");
firstnamelist[i] = namesplit[0];
lastnamelist[i] = namesplit[1];
}
final String[] headers = {"First Name",
"Last Name",
"Age",
"Crime committed",
"Expected Year of Release"
};
final String[][] crimedata = new String[entries][5];
for (int i = 0; i < entries; i++) {
crimedata[i][0] = firstnamelist[i];
crimedata[i][1] = lastnamelist[i];
crimedata[i][2] = agelist[i];
crimedata[i][3] = crimelist[i];
crimedata[i][4] = release[i];
};
for (int i = 0; i < entries; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(headers[j]);
System.out.println(crimedata[i][j]);
}
}
final JTable crimetable = new JTable(crimedata, headers);
JScrollPane scrollpane = new JScrollPane(crimetable);
crimetable.setAutoCreateRowSorter(true);
data.add(scrollpane);
Show.setVisible(true);
}
}
);
I did just put this code here into eclipse and then took out all the radio buttons, and it sorta worked. Although I am not sure why
JTable can't returns proper Dimension or PreferredSize, there are three ways
table.setPreferredScrollableViewportSize(table.getPreferredSize()); but notice for small JTables with a few Rows and Columns too
to calculate desired size for (part) of Columns and (part) Rows too, then pass this Dimension in form table.setPreferredScrollableViewportSize(new Dimension(x, y));
override getPreferredSize for JScrollPane
then JFrame.pack(before JFrame.setVisible(true)) to calculate desired Size on the screen
JPanel has FlowLayout implemented in API, I'd to suggest to change to BorderLayout, then JScrollPane in CENTER area can fill whole (available) area and will be resizable with JFrame, not possible to resize JComponent (together with its container) layed by FlowLayout
have to call data.revalidate(), data.repaint() and Show.pack() as last code lines instead of (remove this code line) Show.setVisible(true);
rename Show to myFrame and show to myButton
What exactly does the setPreferredScrollableViewportSize do? Does it just force the table to always be that size? What is the whole pack thing?
The getPreferredScrollableViewportSize() method is defined in the Scrollable interface, discussed in Implementing a Scrolling-Savvy Client. Rather than setting the preferred size, you can override getPreferredScrollableViewportSize() to change the default. Making the height a multiple of getRowHeight() is illustrated here. More on preferred size may be found here. Conveniently, the pack() method "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents."