Creating JToggleButtons With For - java

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

Related

Swing - using GridLayout and JList

Apologies for my code being so messy. I've added and changed and commented out a lot of code and haven't gotten round to cleaning any of it up yet.
My main problem is being confused about how to get a 5x5 set of images. I need to be able to update it regularly as it is a map. These updates are going to happen in a separate method from the main and it will be difficult to know what image is in a particular square - hence why I've made an ArrayList called previous map.
This is so I can remove the elements of the previous map, then add the new ones. This is really ugly though so I'm trying to change the way I'm doing this by using a JList. I don't fully understand it, but it's cropped up in a lot of the examples I've seen.
What I think is happening is that I can add all my 25 images (as JLabel components) to this list, then add this list to the panel I want it to show up in.
I'm also trying to use GridLayout as that's also shown up in a lot of examples. What I think is happening with grid layout is that I set up a 5x5 grid layout, then use setLayout(<GridLayout name>) to the panel I want the grid to be in. I then add the images I want to be in the map to this grid layout.
Is my understanding correct? I've looked at lots of examples and explanations but I'm still unsure. I'm also struggling to understand how I can combine these two ideas - do I have to? If so am I doing it in the right way? If not how would I do this?
So far, I have managed to get this:
However, for some reason,the images are showing up as a column and not in a 5x5 grid.
Here's the relevant code I've been working on:
public class GameGUI3 extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JFrame f = new JFrame("Dungeons of Doom");
JPanel textPanel = new JPanel();
JPanel leftPanel = new JPanel(new GridBagLayout());
JPanel moveButtonPanel = new JPanel(new GridBagLayout());
JPanel extraButtonPanel = new JPanel(new GridBagLayout());
JPanel mapPanel = new JPanel(new GridBagLayout());
GridLayout gl = new GridLayout(5, 5);
JTextArea textArea = new JTextArea(20, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
DefaultListModel listModel = new DefaultListModel();
JList list = new JList(listModel);
String action;
ArrayList<String> previousMap = new ArrayList<String>();
GridBagConstraints mapC = new GridBagConstraints();
private static GUIClient3 client = new GUIClient3();
JButton n = new JButton("N");
JButton e = new JButton("E");
JButton s = new JButton("S");
JButton w = new JButton("W");
JButton look = new JButton("LOOK");
JButton pickup = new JButton("PICKUP");
JButton hello = new JButton("HELLO");
JButton quit = new JButton("QUIT");
public GameGUI3()
{
GridBagConstraints northC = new GridBagConstraints();
GridBagConstraints eastC = new GridBagConstraints();
GridBagConstraints southC = new GridBagConstraints();
GridBagConstraints westC = new GridBagConstraints();
GridBagConstraints leftTopC = new GridBagConstraints();
GridBagConstraints leftBottomC = new GridBagConstraints(GridBagConstraints extraC = new GridBagConstraints();
northC.insets = new Insets(10, 65, 10, 10);
eastC.insets = new Insets(10, 65, 10, 10);
southC.insets = new Insets(10, 65, 10, 10);
westC.insets = new Insets(10, 0, 10, 10);
leftTopC.insets = new Insets(10, 10, 30, 10);
mapC.insets = new Insets(30, 30, 30, 30);
extraC.insets = new Insets(10, 10, 10, 10);
f.setBounds(100, 100, 1000, 600); // (start on x-axis, start on y, width, height)
textPanel.setBounds(1000, 250, 500, 200);
textPanel.add(new JScrollPane(textArea));
f.getContentPane().add(leftPanel, BorderLayout.WEST);
leftTopC.gridx = 0;
leftTopC.gridy = 0;
leftTopC.anchor = GridBagConstraints.FIRST_LINE_START;
leftPanel.add(moveButtonPanel, leftTopC);
//mapC.gridx = 0;
//mapC.gridy = 1;
//mapC.anchor = GridBagConstraints.LINE_START;
//leftPanel.add(mapPanel, mapC);
//mapPanel.setLayout(gl);
leftPanel.add(mapPanel);
leftBottomC.gridx = 0;
leftBottomC.gridy = 2;
leftBottomC.anchor = GridBagConstraints.LAST_LINE_START;
leftPanel.add(extraButtonPanel, leftBottomC);
f.getContentPane().add(textPanel, BorderLayout.EAST);
textArea.setEditable(false);
this.setVisible(false);
northC.gridx = 0;
northC.gridy = 0;
northC.gridwidth = 3;
northC.anchor = GridBagConstraints.NORTH;
moveButtonPanel.add(n, northC);
westC.gridx = 0;
westC.gridy = 1;
westC.gridwidth = 1;
westC.anchor = GridBagConstraints.WEST;
moveButtonPanel.add(w, westC);
eastC.gridx = 2;
eastC.gridy = 1;
eastC.gridwidth = 3;
eastC.anchor = GridBagConstraints.EAST;
moveButtonPanel.add(e, eastC);
southC.gridx = 0;
southC.gridy = 2;
southC.gridwidth = 3;
southC.anchor = GridBagConstraints.SOUTH;
moveButtonPanel.add(s, southC);
mapC.gridx = 0;
mapC.gridy = 2;
//mapC.gridwidth = 10;
//mapC.anchor = GridBagConstraints.LINE_START;
//mapPanel.setLayout(gl);
leftPanel.add(mapPanel, mapC);
ImageIcon HereBeDragonsIcon = new ImageIcon("HereBeDragons.jpg", "Image");
JLabel HereBeDragonsLabel = new JLabel(HereBeDragonsIcon);
//mapPanel.add(HereBeDragonsLabel);
int count=0;
for(int i=0; i<4; i++)
{
listModel.add(count++, HereBeDragonsIcon);
//listModel.addElement(HereBeDragonsIcon);
previousMap.add("HereBeDragonsLabel");
//mapPanel.add(HereBeDragonsLabel);
}
//JList list = new JList(listModel);
//mapPanel.add(list);
mapPanel.add(list);
extraButtonPanel.add(look, extraC);
extraButtonPanel.add(pickup, extraC);
extraButtonPanel.add(hello, extraC);
extraButtonPanel.add(quit, extraC);
n.addActionListener(this);
e.addActionListener(this);
s.addActionListener(this);
w.addActionListener(this);
look.addActionListener(this);
pickup.addActionListener(this);
hello.addActionListener(this);
quit.addActionListener(this);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setVisible(true);
}
Many thanks - if anything is unclear please let me know and I will try and re-phrase my question or explain my code better.

Java create buttons dynamically in grid

I am making a desktop application in java where I want to create the buttons dynamically. The dynamically created button should be placed in a grid like structure. Now my concern is that, if I want to access those buttons, then how can i do that since I dont have the ID of the particular button ?
setLayout(new java.awt.GridLayout(4, 4));
for (int i = 0; i < dataCount; i++)
{
GridBagConstraints c = new GridBagConstraints();
jPanel1.setLayout(new GridBagLayout());
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.gridx = 0;
c.gridy = 0;
jPanel1.add(new JButton(linesArray[i]), c);
jPanel1.setBackground(Color.WHITE);
jPanel1.setBorder(BorderFactory.createMatteBorder(0,0,1,0,Color.BLACK));
}
How can i access the butons through a particular ID?
You can create an array which will hold all your buttons:
JButton[] buttons = new JButton[dataCount];
and then add buttons to it, and call the button by array:
buttons[i] = new JButton(linesArray[i]), c);
jPanel1.add(buttons[i]);

GridBagLayout anchor

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

GradBagLayout not distributing columns based on weight

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.

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

Categories