GridBagLayout anchor - java

I am trying to use Anchor for setting the alignment of my components.
Here is my code:
public void intiConOpt()
{
/*********************************** connection options ****************************************/
conOptGBC.insets = new Insets(5, 5, 5, 5);
conOptGBC.weightx = 1.0;
conOptGBC.weighty = 1.0;
conOptGBC.anchor = GridBagConstraints.NORTHWEST;
conOpt = new JPanel();
conOpt.setLayout(new GridBagLayout());
//////////////////////////////////////////cycle time////////////////////////////////////////////
readPeriodLabel = new JLabel("Node read cycle time:");
conOptGBC.gridx = 0;
conOptGBC.gridy = 0;
conOpt.add(readPeriodLabel, conOptGBC);
readPeriodNumberModel = new SpinnerNumberModel();
readPeriodSpinner = new JSpinner(readPeriodNumberModel);
JSpinner.NumberEditor readPeriodEditor = new JSpinner.NumberEditor(readPeriodSpinner,"###");
readPeriodSpinner.setEditor(readPeriodEditor);
readPeriodNumberModel.setValue(TopologyMain.settings.getSettingsList().get("nodeReadingCycleTime"));
readPeriodSpinner.setPreferredSize(new Dimension(40, 20));
conOptGBC.gridx = 1;
conOptGBC.gridy = 0;
conOpt.add(readPeriodSpinner, conOptGBC);
readPeriodLabel2 = new JLabel("<html><font size=2>(4-180 sec)</font></html>");
conOptGBC.gridx = 2;
conOptGBC.gridy = 0;
conOpt.add(readPeriodLabel2, conOptGBC);
///////////////////////////////////////////time out////////////////////////////////////////////
cliTimeoutLabel = new JLabel("CLI response timeout:");
conOptGBC.gridx = 0;
conOptGBC.gridy = 1;
conOpt.add(cliTimeoutLabel, conOptGBC);
cliTimeoutNumberModel = new SpinnerNumberModel();
cliTimeoutSpinner = new JSpinner(cliTimeoutNumberModel);
JSpinner.NumberEditor cliTimeoutEditor = new JSpinner.NumberEditor(cliTimeoutSpinner,"###");
cliTimeoutSpinner.setEditor(cliTimeoutEditor);
cliTimeoutNumberModel.setValue(TopologyMain.settings.getSettingsList().get("cliTimeout") /10);
cliTimeoutSpinner.setPreferredSize(new Dimension(40, 20));
conOptGBC.gridx = 1;
conOptGBC.gridy = 1;
conOpt.add(cliTimeoutSpinner, conOptGBC);
cliTimeoutLabel2 = new JLabel("<html><font size=2>(8-999 sec)</font></html>");
conOptGBC.gridx = 2;
conOptGBC.gridy = 1;
conOpt.add(cliTimeoutLabel2, conOptGBC);
///////////////////////////////////////busy response//////////////////////////////////////////////
cliBusySleepLabel = new JLabel("CLI busy check time:");
conOptGBC.gridx = 0;
conOptGBC.gridy = 2;
conOpt.add(cliBusySleepLabel, conOptGBC);
cliBusySleepNumberModel = new SpinnerNumberModel();
cliBusySleepSpinner = new JSpinner(cliBusySleepNumberModel);
JSpinner.NumberEditor cliBusySleepEditor = new JSpinner.NumberEditor(cliBusySleepSpinner,"###");
cliBusySleepSpinner.setEditor(cliBusySleepEditor);
cliBusySleepNumberModel.setValue(TopologyMain.settings.getSettingsList().get("cliBusySleep") /1000);
cliBusySleepSpinner.setPreferredSize(new Dimension(40, 20));
conOptGBC.gridx = 1;
conOptGBC.gridy = 2;
conOpt.add(cliBusySleepSpinner, conOptGBC);
cliBusySleepLabel2 = new JLabel("<html><font size=2>(1-999 sec)</font></html>");
conOptGBC.gridx = 2;
conOptGBC.gridy = 2;
conOpt.add(cliBusySleepLabel2, conOptGBC);
conOpt.setVisible(false);
contentPanel.add(conOpt);
}
My problem is the GridBagConstraints anchor has no effect, my components are still in the center of the panel.

The anchor property is working correctly, the issue you are having is with...
conOptGBC.weightx = 1.0;
conOptGBC.weighty = 1.0;
The problem is, you've asked GridBagLayout to allocate equal amount of space for each column, so they will take up, in this case, are third each, this is what would be consider.
By removing the conOptGBC.weightx = 1.0; you get...
It's a little difficult to see, but if we add some guides in...
You can see that the fields begin to align to the north-west...

Related

NullPointerException when adding a column to JTable

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));

Does GridBagLayout affect JLabel images?

Currently trying to add a header image to my JFrame based GUI, I've developed the layout of the project and everything looks good, but every time I run the project the image does not load (no error messages).
My code (partial):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class DeltaFlightFrame extends JFrame implements ActionListener, ChangeListener{
//<SNIPPED CODE FOR EASE OF VIEWING>
//Labels for inputs
//<SNIPPED CODE FOR EASE OF VIEWING>
private JLabel deltaLogo;
//icon
private Icon logo;
//<SNIPPED CODE FOR EASE OF VIEWING>
DeltaFlightFrame() {
GridBagConstraints layoutConst = null;
//<SNIPPED CODE FOR EASE OF VIEWING>
setTitle("Delta Flight Price Estimator");
//<SNIPPED CODE FOR EASE OF VIEWING>
//initialize delta logo
logo = new ImageIcon("../img/logo.png");
deltaLogo = new JLabel(logo);
System.out.println("Height" + logo.getIconHeight());
System.out.println("Width" + logo.getIconWidth());
//<SNIPPED CODE FOR EASE OF VIEWING>
// Create frame and add components using GridBagLayout
setLayout(new GridBagLayout());
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
//layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 0;
//layoutConst.gridwidth = 4;
add(deltaLogo, layoutConst);
//<SNIPPED CODE FOR EASE OF VIEWING>
}
//TODO: this
public void stateChanged(ChangeEvent event) {
}
//TODO, also: this
public void actionPerformed(ActionEvent event) {
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception ignored){}
DeltaFlightFrame myFrame = new DeltaFlightFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
}
My full code (I didn't want to put it all, it's a disgusting mess and I'm a first year student so this isn't... nice... hahaha):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class DeltaFlightFrame extends JFrame implements ActionListener, ChangeListener{
//Text Fields
private JTextField desCityField; // Holds destination city abbreviation,
private JTextField depCityField; // Holds departure city abbreviation.
private JTextField finalOutputField; //Shows final price
//Drop Down
//=====TODO
//Labels for inputs
private JLabel desCityLabel;
private JLabel depCityLabel;
private JLabel tripTypeLabel;
private JLabel seatTypeLabel;
private JLabel adultTravelerCountLabel;
private JLabel childTravelerCountLabel;
private JLabel finalOutput; //final price
private JLabel flightTitle;
private JLabel passengerTitle;
private JLabel deltaLogo;
//icon
private Icon logo;
//dropdown
String[] seatClassChoices = { "Basic Economy", "Business+ Comfort", "First Class" };
private JComboBox seatClassDrop;
//JSpinners
private JSpinner adultTravelerCount;
private JSpinner childTravelerCount;
//radio button
private JRadioButton oneWay;
private JRadioButton roundTrip;
//Buttons
private JButton calculateButton;
/* Constructor creates GUI components and adds GUI components
using a GridBagLayout. */
DeltaFlightFrame() {
GridBagConstraints layoutConst = null;
SpinnerNumberModel spinnerModelAdult = null;
SpinnerNumberModel spinnerModelChild = null;
String desInit = "ATL";
String depInit = "JFK";
double priceInit = 150.00;
int passCountMin = 0;
int passCountMax = 9;
int passAdultInit = 1;
int passChildInit = 0;
//Set Frame Title
setTitle("Delta Flight Price Estimator");
//create labels
depCityLabel = new JLabel("Departure City: ");
desCityLabel = new JLabel("Destination City: ");
tripTypeLabel = new JLabel("Trip Type: ");
seatTypeLabel = new JLabel("Seat Class: ");
adultTravelerCountLabel = new JLabel("Travelling Adults: ");
childTravelerCountLabel = new JLabel("Travelling Children: ");
finalOutput = new JLabel("Price: ");
flightTitle = new JLabel("Flight Information");
flightTitle.setFont(new Font("Sans-Serif", Font.BOLD, 20));
passengerTitle = new JLabel("Passenger Information");
passengerTitle.setFont(new Font("Sans-Serif", Font.BOLD, 20));
//create dropdown
seatClassDrop = new JComboBox<String>(seatClassChoices);
//create spinners
spinnerModelAdult = new SpinnerNumberModel(passAdultInit, passCountMin, passCountMax, 1);
adultTravelerCount = new JSpinner(spinnerModelAdult);
spinnerModelChild = new SpinnerNumberModel(passChildInit, passCountMin, passCountMax, 1);
childTravelerCount = new JSpinner(spinnerModelChild);
//initialize delta logo
logo = new ImageIcon("../img/logo.png");
deltaLogo = new JLabel(logo);
System.out.println("Height" + logo.getIconHeight());
System.out.println("Width" + logo.getIconWidth());
//initialize text fields
desCityField = new JTextField("JFK");
desCityField.setEditable(true);
desCityField.setDocument(new LengthRestrictedDocument(3));
desCityField.setColumns(3);
depCityField = new JTextField("ATL");
depCityField.setEditable(true);
depCityField.setDocument(new LengthRestrictedDocument(3));
depCityField.setColumns(3);
//radio button
oneWay = new JRadioButton("One Way");
roundTrip = new JRadioButton("Round Trip");
//button
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
ButtonGroup tripType = new ButtonGroup();
tripType.add(oneWay);
tripType.add(roundTrip);
// Create frame and add components using GridBagLayout
setLayout(new GridBagLayout());
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
//layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 0;
//layoutConst.gridwidth = 4;
add(deltaLogo, layoutConst);
setLayout(new GridBagLayout());
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 1;
layoutConst.gridwidth = 4;
add(flightTitle, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(desCityLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 2;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(depCityLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 1;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(desCityField, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 3;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(depCityField, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 0;
layoutConst.gridy = 4;
layoutConst.gridwidth = 1;
add(roundTrip, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 2;
layoutConst.gridy = 4;
layoutConst.gridwidth = 2;
add(seatClassDrop, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 0;
layoutConst.gridy = 5;
layoutConst.gridwidth = 1;
add(oneWay, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(50, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 6;
layoutConst.gridwidth = 4;
add(passengerTitle, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 1);
layoutConst.fill = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(adultTravelerCountLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 1;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(adultTravelerCount, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 10);
layoutConst.fill = GridBagConstraints.LINE_START;
layoutConst.gridx = 2;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(childTravelerCountLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 3;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(childTravelerCount, layoutConst);
}
//TODO: this
public void stateChanged(ChangeEvent event) {
}
//TODO, also: this
public void actionPerformed(ActionEvent event) {
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception ignored){}
DeltaFlightFrame myFrame = new DeltaFlightFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
}
I did do some messing around, here:
logo = new ImageIcon("../img/logo.png");
deltaLogo = new JLabel(logo);
System.out.println("Height: " + logo.getIconHeight());
System.out.println("Width: " + logo.getIconWidth());
And the output of that was:
Height: -1
Width: -1
Which I do find odd, if that's a starting point.
SO, my question is: Does my setup with GridBagLayout affect the display of the of the JLabel image?
Using the website provided by #camickr, I was able to successfully render the image using their "createImageIcon" method.

Why is this wrong? Making 10 Components within 1 pane easily

Before i begin, i have this whole pane being opened as an action. I was wondering why if I run this program, it doesn't output 10 lines of equations, with text areas to the right of them. It outputs a window, with nothing inside.
(Program is being run in a different part of the code- this is a snippet.)
`
pane2.setLayout(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints(); //Creates New GBC
if (shouldFill)
{
//natural height, maximum width
d.fill = GridBagConstraints.HORIZONTAL;
}
if(multiTable >= 1 && multiTable <= 12)
{
for(int r = 1; r <= 10; r++)
{
int[] answer = {1};
JPanel[] prob = new JPanel[10];
JLabel[] probOutput = new JLabel[10];
JTextArea[] uAnswer = new JTextArea[10];
prob[r] = new JPanel();
rand1 = random1.nextInt(12)+1;
rand2 = random1.nextInt(2)+1;
answer[r] = multiTable * rand1;
if(rand2 == 1)
probType =( r+") "+multiTable+" x "+rand2);
if(rand2 == 2)
probType =( r+") "+rand2+" x "+multiTable);
probOutput[r] = new JLabel(probType);
d.gridx = 0;
d.gridy = r;
pane2.add(probOutput[r], d);
uAnswer[r] = new JTextArea();
d.gridx = 1;
d.gridy = r;
pane2.add(uAnswer[r], d);
}
frame2.add(pane2);
frame2.pack();
}
}`
Here is a link to a pastebin link for the full program (It's a school program I don't care for much, just need the grade.)

JTable sizing issue

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."

Creating JToggleButtons With For

I want to create 100 JToggleButtons and do it with a for loop and save them in a link list. Then show them in grid bag layout.
ArrayList<JToggleButton> buttons = new ArrayList<JToggleButton>();
for(int i=0; i<100; i++){
buttons.add(new JToggleButton(""));// = new JToggleButton("");
GridBagConstraints gbc_ = new GridBagConstraints();
gbc_tglbtnNewToggleButton.fill = GridBagConstraints.VERTICAL;
gbc_tglbtnNewToggleButton.insets = new Insets(0, 0, 5, 5);
gbc_tglbtnNewToggleButton.gridx = i;
gbc_tglbtnNewToggleButton.gridy = j;
frame.getContentPane().add(tglbtnNewToggleButton, gbc_tglbtnNewToggleButton);
}
I tried something like that, but i can't.
You're not adding the created button to the content pane. And you create a constraint named gbc_, but never use it. Change the code to
gbc_tglbtnNewToggleButton.fill = GridBagConstraints.VERTICAL;
gbc_tglbtnNewToggleButton.insets = new Insets(0, 0, 5, 5);
gbc_tglbtnNewToggleButton.gridy = j;
for (int i = 0; i < 100; i++) {
JToggleButton button = new JToggleButton("");
buttons.add(button);
gbc_tglbtnNewToggleButton.gridx = i;
buttons.add(button, gbc_tglbtnNewToggleButton);
}

Categories