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.)
Related
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;
Sorry, I have a hitch to fix, I was able to map a File array with a String array, and now, I want to get a random File from the mapped arraylist to play when a button is clicked, but I don't get it.... It doesn't work...
Here's my code:
private static File[] word =
//Here, I announce the contents of the File array named word, about 50 Files
private String []answer =
//String array to be mapped with File array
//Other swing parameters to be used
private static JLabel sound;
private static JButton check;
private static JTextField spell;
private JButton click;
//Font to be used for all text typed in JTextField
private Font fonty;
//Icon to be displayed when sound is played
JLabel icon = new JLabel (new ImageIcon("C:\\Users\\HP\\Pictures\\Photos\\#010.jpg"));
public Quest1() {
// Mapping of String array to File array
Map<String, File> mapping = new HashMap();
Map<String, File>mpl = new HashMap();
mpl.putAll(mapping);
//Layout for the JFrame set (the class extends JFrame)
setLayout (new BorderLayout());
setContentPane(icon);
fonty = new Font("Script MT Bold", Font.PLAIN, 15);
//JPanel to hold swing components
JPanel hold = new JPanel ();
hold.setLayout(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
g.anchor = GridBagConstraints.WEST;
g.gridx = 2;
g.gridy = 1;
g.gridwidth = 2;
g.insets = new Insets(2, 20, 2,2);
sound = new JLabel (new ImageIcon("C:\\Users\\HP\\Downloads\\JLabelSoundImage.jpg"));
sound.setPreferredSize(new Dimension(70,70));
hold.add(sound, g);
click = new JButton ("Play");
click.setFont(fonty);
g.anchor = GridBagConstraints.WEST;
g.gridx = 2;
g.gridy = 5;
g.gridwidth = 2;
g.insets = new Insets(2, 20, 8, 2);
hold.add(click, g);
click.addActionListener (new ActionListener (){
public void actionPerformed (ActionEvent t) {
//Where my Problem lies.... getting a random File from the mapped array list to play when the button is clicked.
List key = new ArrayList (mapping.keySet());
Collections.shuffle(key);
for (Object o: key){
mapping.get(o);
InputStream in = new InputStream(mapping.get(o),(word));
}
}
});
spell = new JTextField (10);
spell.setFont(fonty);
g.anchor = GridBagConstraints.EAST;
g.gridx = 5;
g.gridy = 2;
g.gridwidth = 3;
g.insets = new Insets (2, 2, 2, 20);
hold.add (spell, g);
check = new JButton ("Check my answer");
check.setFont(fonty);
g.anchor = GridBagConstraints.SOUTH;
g.gridx = 8;
g.gridy = 8;
g.gridwidth = 3;
g.insets = new Insets (2, 2, 20, 2);
hold.add (check, g);
check.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
if (spell.getText().equals(mapping.get(key))) {
String c = "Correct!";
JOptionPane.showMessageDialog(null, c);
}
else {
String d = ("Wrong! the Answer is ") + (mapping.get(key)) ;
JOptionPane.showMessageDialog(null, d);
}
}
});
hold.setVisible(true);
hold.setSize(400,400);
hold.setLocation(50, 50);
hold.setOpaque(false);
add(hold, BorderLayout.CENTER);
}
One problem is not providing the type to your List. This is very risky, so define what type of List it actually is:
List<File> ...
Another problem is mpl.keySet returns a Set, not an ArrayList. You also don't really want to redefine this every time they click the button. Set this Set once, after you've defined your Map.
Set<File> songs = mpl.keySet();
File[] songArray = songs.toArray();
At this point, all you need to do is generate an index and then create a local variable with a reference to the file. This can be done with the Math class.
int index = (int) (Math.random() * songArray.length);
File song = songArray[index];
You may need to add 1 to the index at the end. I don't recall if it will be inclusive or exclusive for all indices.
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...
This is what my GUI looks like now:
I want it to have the three columns to be equally distributed. To do this, I set each of the weights equal to 1/3. Obviously, it's not working.
Here is my code for creating the Frame:
public static JPanel createLayout(int rows) {
JPanel product = new JPanel(new GridBagLayout());
String[] lables = {"School ", "Advanced #", "Novice # "};
double weight = .3333333333333;
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(3, 3, 3, 3);
c.weightx = weight;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.gridy = 1;
for (int j = 0; j < lables.length; j++) {
c.gridx = j;
JLabel l = new JLabel(lables[j]);
product.add(l, c);
}
for (int i = 0; i < rows; i++) {
c.gridy++;
for (int j = 0; j < lables.length; j++) {
c.gridx = j;
JTextField f = new JTextField();
product.add(f, c);
}
}
c.gridy++;
c.gridx = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.NONE;
JPanel b = new JPanel();
JButton add = new JButton("+");
b.add(add);
JButton delete = new JButton("-");
b.add(delete);
product.add(b, c);
return product;
}
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("Debate Calculator");
JPanel debates = new JPanel();
frame.add(createLayout(5), BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
The problem is that you components are not equally sized to begin with. I can't explain exactly why it does what it does, but the size of your labels is each different because they have a different number of characters. I know you tried to make then the same size, but a " " is not the same as "W".
I changed your code to use the following and it seems to work:
JTextField f = new JTextField(10);
Now the width of each text field is greater than the label, so that is the width that is used to give each column a proportional size.
You might consider using a GridLayout. The default behaviour is to make each cell the same size.
The problem is your button bar at the bottom. Set the gridwidth to REMAINDER on that element.
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."