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."
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));
All I want is to make my entire last row a single button. Actually, this is a part of my calculator program. I have created another panel for trigonometric calculations. When I remove the sin,cos,tan buttons the calculator doesn't look very good with only a single button on the last row and the rest of the row blank. So after removing the sin,cos,tan buttons I tried to increase the size of the CE button by .setsize(), but in vain. I was hoping if someone could help me with that.
public final class Cal implements ActionListener, KeyListener {
Font font = new Font("SansSerif", Font.BOLD, 32);
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(6, 4, 4, 4));
JTextField field = new JTextField("0.0");
JButton[][] keys = new JButton[6][5];
final int plus = 1;
final int minus = 2;
final int times = 3;
final int divide = 4;
final int sin = 5;
final int cos = 6;
final int ce = 7;
final int perc = 8;
int op;
double ans = 0;
double accum = 0;
boolean newNumb = true;
String calc = "";
//Assign method
public void assign() {
frame.setTitle("Scientific Calculator");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
field.setHorizontalAlignment(JTextField.RIGHT);
field.setEditable(true);
field.setForeground(Color.red);
field.setBackground(Color.white);
field.setToolTipText("Input Box");
field.setFont(font);
frame.add(field, BorderLayout.NORTH);
frame.setVisible(true);
frame.setSize(430, 430);
frame.addKeyListener(this);
// field.addKeyListener(this); //renders field uneditable
field.requestFocus();
panel.setBackground(Color.black);
}
[enter image description here][1]//buttons Method
public void buttons() {
String action;
int i, j;
// create the keys
keys = new JButton[6][5];
keys[0][0] = new JButton("7");
keys[0][1] = new JButton("8");
keys[0][2] = new JButton("9");
keys[0][3] = new JButton("+");
keys[1][0] = new JButton("4");
keys[1][1] = new JButton("5");
keys[1][2] = new JButton("6");
keys[1][3] = new JButton("-");
keys[2][0] = new JButton("1");
keys[2][1] = new JButton("2");
keys[2][2] = new JButton("3");
keys[2][3] = new JButton("x");
keys[3][0] = new JButton("0");
keys[3][1] = new JButton(".");
keys[3][2] = new JButton("=");
keys[3][3] = new JButton("/");
keys[4][0] = new JButton("x³");
keys[4][1] = new JButton("x²");
keys[4][2] = new JButton("%");
keys[4][3] = new JButton("√");
keys[5][0] = new JButton("sin");
keys[5][1] = new JButton("tan");
keys[5][2] = new JButton("cos");
keys[5][3] = new JButton("CE");
//i = rows j =colums
for (i = 0; i < 6; i++) {
for (j = 0; j < 4; j++) {
keys[i][j].setFont(font);
action = (new Integer(i)).toString() + (new Integer(j)).toString();
keys[i][j].setActionCommand(action);
keys[i][j].addActionListener(this);
keys[i][j].setBackground(Color.white);
keys[i][j].setForeground(Color.red);
panel.add(keys[i][j]);
}
}//end of For loops
}
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.)
I created a JPanel Grid and now I want add Array of image Slices to Grid with loop
in last line I have error.
public static final int WIDTH = 1024;
public static final int HEIGHT = 640;
private static final int GRID_ROWS = 20;
private static final int GRID_COLS = 20;
private static final int GAP = 1;
private static final Dimension LAYERED_PANE_SIZE = new Dimension(WIDTH, HEIGHT);
private static final Dimension LABEL_SIZE = new Dimension(60, 40);
private GridLayout gridlayout = new GridLayout(GRID_ROWS, GRID_COLS, GAP, GAP);
private JPanel backingPanel = new JPanel(gridlayout);
private JPanel[][] panelGrid = new JPanel[GRID_ROWS][GRID_COLS];
private JLabel redLabel = new JLabel("Red", SwingConstants.CENTER);
private JLabel blueLabel = new JLabel("Blue", SwingConstants.CENTER);
// code in constructor
backingPanel.setSize(LAYERED_PANE_SIZE);
backingPanel.setLocation(2 * GAP, 2 * GAP);
backingPanel.setBackground(Color.black);
for (int row = 0; row < GRID_ROWS; row++) {
for (int col = 0; col < GRID_COLS; col++) {
panelGrid[row][col] = new JPanel(new GridBagLayout());
backingPanel.add(panelGrid[row][col]);
}
}
setLayout(new GridLayout(GRID_ROWS, GRID_COLS));
BufferedImage bi = null;
try {
bi = ImageIO.read(new File("assets/image.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
for (int r = 0; r < GRID_ROWS; r++) {
for (int c = 0; c < GRID_COLS; c++) {
int w = bi.getWidth() / GRID_ROWS;
int h = bi.getHeight() / GRID_COLS;
BufferedImage b = bi.getSubimage(c * w, r * h, w, h);
list.add(new JLabel(new ImageIcon(b)));
panelGrid[r][c] = new JPanel(new GridBagLayout());
backingPanel.add(panelGrid[r][c]);
panelGrid[r][c].add(list.get(r));
}
}
Since list is an instance of List, and Java is not C++, you cant specify methods like operator[]. You need to use list.get(), like this:
panelGrid[r][c].add(list.get(r));
Also, you should use a GridBagLayout with GridBagConstraints. Therefore, call
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
And change the lines where you add the panel to this:
panelGrid[r][c] = new JPanel(new GridBagLayout());
panelGrid[r][c].add(list.get(r));
gbc.gridx = r; gbc.gridy = c;
backingPanel.add(panelGrid[r][c], gbc);
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...