How can I make a spacing? - java

We have a program in Java using Eclipse Kepler which I am testing for any errors. I found out that one of the modules in which, Product maintenance has a slight misplacement of the design. The problem that I saw was that the product description (text area which has 3,20 for the scroll pane in-case the description was long) exceeded its space and is now colliding with the product price (another text area who has only 0,20 or "",20). Now I believe that the programmer used a Windows Builder to assist him in his design but never told me how to use it. We have our own copies of the system in case we want something change. But I don't think he taught me how to setup it up and use it. Now I was wondering how I should code this by myself so that I could understand how it should go. Frankly, I am not a Java person but willing to learn. Can you help me? If you need more info, feel free to ask.
taProdDesc = new JTextArea(3,20);
spProdDesc = new JScrollPane(taProd, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tfProdPrice = new JTextField("",20);
it looks something like this
I wanted more space in between the two cause I know it should look like a perfect rectangular shape and then a spacing then the next text area/field.
That's what it looks like in the code but I don't think this is the one is where the actual code that I should edit. But for the meantime so me and the programmer can see it, I want to place it there so later on I could tell him where to place it.

depending on the layout manager you are using, you could create space by adding a border,
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
or by using 'setAutoCreateGaps' and 'setAutoCreateContainerGaps' in GroupLayout:
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
For more about the LayoutManagers, you should take a look here
For more about borders: take a look here

Related

JPanel not updating, no matter what i try

Im making a small program that shows teams/ players/ then their twitter feeds, tweets, etc. My problem seems to be unrelated to that though, it just my jPanel isn't updating. I got pretty far in the project, and i keep throwing random code segments in my method to make it so once i click something, the "left" jpanel either is replaced with the jbuttons, or the jbuttons are put into it, ive tried both. Heres the code segment ive been trying to get to work, which it does, just not as intended.
public void mousePressed(MouseEvent e) {
System.out.println("You clicked on " + ap.getTeams() [addPlayers.OPTIC].getTeamName());
for(int i = 0; i<4; i++){
//JPanel temp = ap.makePanel(ap.getTeams()[ap.OPTIC].getPlayers().get(i).getTwitterScreenName());
//temp.setBounds(0,(i*125), 450,125);
//left.add(temp);
JButton b = new JButton("Test");
b.setBounds(30,30,30,30);
left.add(b);
left.revalidate();
add(left);
add(b);
right.add(b);
left.setVisible(false);
left.setVisible(true);
System.out.println(i);
}
}
}
the commented out code is my main code, but i am just using jbuttons to test. As you can see, i just keep adding random bits, hoping something will work. Ive also tried invoke later, but sadly, that didn't work either.Not sure why the jpanels not updating, but any feedback would be great, thanks.
Avoid null layout and setBounds since this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Instead you will want to study and learn the layout managers and then nest JPanels, each using its own layout manager to create pleasing and complex GUI's that look good on all OS's.
The best way to swap JPanels or any component is to use a CardLayout.
If still stuck, then post a minimal example program. It's the best way for us to actually see and experience your problem.
Don't add a component to more than one container like you're doing with your b JButton variable. You're in fact adding it to three containers.
You seem to be trying to add four JButtons to containers, giving them all the same bounds, one exactly on top of the other?? Sorry, but the more I look at your code, the more screwy it becomes. Again, stop this nonsense, learn about the layout managers at the Swing tutorials, and use them.
"and i keep throwing random code segments in my method to make it so ..." -- throwing things at the wall to see what sticks is not a good heuristic for creating a program. Start with the knowledge base -- here the Swing tutorials and Java API, then plan your program structure, and then create your code.
Edit
You ask:
..... All im asking is whats the problem with the whole thing not updateing?
If you don't use a CardLayout and change components manually, then you would need to call revalidate() and repaint() on the container after the change, and the container should update with its new components. If this does not fix the problem, then likely you have an issue in code not shown us, and you will again then want to create and post a minimal example program. Again it's the best way for us to actually see and experience your problem.

Creating a Grid in Java

As a way of learning Java, I'm writing this little application for grade schoolers to practice basic math. The idea is that the kid does any number of math problems, as long as they are in the app, it just continues to throw problems at them until they click a 'Done' button. When they decide to be done, I want a new JFrame to come up that will show them all of the problems they attempted, along with their answer, and whether they got the problem right or wrong.
The advice that I am looking for is what is the best way for me present these results. I looked into the GridLayout and the GroupLayout, but I don't think that these are exactly right. I did something similar in VBA for Excel, and there I just ran a for loop with one iteration for every problem they attempted. Each iteration would add a row of labels to the frame with the elements of the problem displayed in the various labels. I tried this in Java, but I'm not even able to get the labels to even display.
So before I get all specific and start posting my code, I want to ask a bigger question, which is "what is the best method to create a view like this?" Often, I go off in one direction only to waste time before somebody suggests a totally different (and better) approach.
Thanks!
(edit: here's an image of how I did this in Excel. I'm trying to repeat basically the same thing in Java)
One simple way to make that design would be to use a mix of components. You could have a bunch of JLabels and JPanels stacked in a vertical FlowLayout. The grid you have described would be best designed in a JTable, something like the below:
If you like tables like Excel then, Java provides JTable class to create tables, if you want.
Tutorial : http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

Netbeans! Components moved from design to runtime

Things look one way in the design area, but are re-sizing moving around.
It does this with every LAF, its not a style issue, its creating large empty spaces where there are none on the design area.
Any ideas?
Sorry I can't post pictures, I created the profile to ask this question
What am I doing to cause this discrepancy and how can I fix it?
You might try changing the panel layout. Right click a jPanel -> set Layout -> grid bag or one of the others. I've had a lot better luck with GridBag than with Free Design. Then you can go right click-> Customize Layout to customise
As for what you're doing on your installation that might cause this, I'm afraid I can't say.

Swing JTable Hack

I have a fairly complicated JTable subclass (WidgetTable and its WidgetTableModel) that works fine when I add it to a dummy JPanel for testing purposes.
Since I am absolutely horrid at working with LayoutManagers, I like to use the NetBeans built-in GUI Builder for all my layout work. Then I usually just code-around the autogenerated (GUI builder) code and that has always worked for me. It is the best of both worlds: I get my presentation looking exactly the way I want it, and I also get fine-grained control over the componentry.
However, I have never used the GUI Builder tool to make tables. After tinkering around with it for a while last night, it looks as though it is only good for making pretty basic (fixed # of rows, fixed # of columns, etc.) JTables.
My WidgetTable actually has a dynamic number of both rows and columns, special editors/renderers and many other bells and whistles.
My problem:
I have two conflicting constraints: (1) I need to use the GUI builder to position and size the table exactly where I want it in the container, but, (2) The table component available through the GUI builder is too basic to handle my WidgetTable.
I need a way to design a "table placeholder" into my container with the GUI builder, such that, once NetBeans autogenerates that placeholder code, I tweak the code and instruct it to dynamically instantiate one of my WidgetTables instead, consuming the location and size that I defined the placeholder component to take up.
This way I can have my cake, and eat it too. The only problem is, I don't think the GUI builder supports this ability to drag-n-drop abstract JComponents, position and size them, and then plug subclasses into them elsewhere in the codebase.
Anybody ever have this problem before or have any interesting recommendations? I imagine the best thing to do would be for me to just roll up my sleeves and learn LayoutManagers, but I'm mostly a server-side developer and only come over to the client-side every once in a blue moon; and honestly, don't have the energy to learn the intricacies and nastiness of GroupLayout and its sinister cousins.
Thanks for any help!
Insert a JTable using the GUI builder, reset its model property to the default value, and tweak the construction code so that it looks like
jTable1 = new WidgetTable(this.widgetTableModel);
You may tweak the creation code by right-clicking on the JTable, selecting "Customize code", choosing "custom creation" instead of "default code" in the first combo box, and typing the code for the constructor call.
If you need your jTable1 variable to be of type WidgetTable rather than JTable, edit the "Variable declaration code" in the same dialog box.
NetBeans also allows you to create custom components for building UIs. This may be more work than you want to put into your WidgetTable, but if you think you're going to have to build more UIs with custom components, it could be worth learning.
I do this all the time. I have an subclassed JTable that I use with the GUI editor and it is Dynamic.
Add a JTable to your project using the GUI editor and the layout of your choice.
Once the table is added, right click on it and click on custom code.
In the constructor of the JTable, change it to say new WidgetTable(new WidgetModel()) instead of new JTable(new DefaultTableModel()).
Create a global variable for you WidgetTable. Something like private WidgetTable widgetTable;
In you constructor, after the call to initComponents(), cast your JTable to a Widget table and use that from now on.
`widgetTable = (WidgetTable)jTable1;

Which Layout Manager do you use?

What java GUI layout manager does everyone use? Lately, I have been using MigLayout, which has some powerful component controls. Just wanted to see what other developers are using other than the standard JDK ones.
MiGLayout is the GUI layout manager which is widely used by Java Developers.
GridBagLayout is usable. Once you get used to using it, it works great. I think the standard JDK layout managers are pretty powerful on their own. Plus, you get to minimize dependency on 3rd party libraries.
MiG and FormLayout (JGoodies) are both excellent for manual layout (And almost all layout eventually becomes manual). My biggest piece of advice is to design your views so that you can completely rip out the layout and re-implement it without impacting your application (good separation of view and controller is key here).
Definitely take a look at JGoodie's PresentationModel approach for implementing 'dumb' views. I use this technique with a GUI builder (I use GroupLayout with the Jigloo GUI builder plugin) for tossing off quick prototypes. After 3 or 4 iterations, that usually goes out the window and we do a re-implement using MiG or FormLayout.
EDIT: Since I wrote this, I have moved to using MiG for all of my layouts, and I no longer use a GUI builder - it's just way too easy to lay things out using MiG.
The last Swing application I worked on used JGoodies' FormsLayout.
I use the GridBagLayout. It seems to take alot of code, but it makes very good looking layouts.
I also like to combine BorderLayout with GridBagLayout panels for great customizability.
I'm a big fan of using TableLayout instead of GridBagLayout. Everything just makes sense, whereas every time I try to use GridBagLayout it crushes my soul.
I use to go for GridBagLayout for the control, but since java1.6 I'm going to use GroupLayout Is awsome.
Here an screenshot and sample code to use it!.
alt text http://img145.imageshack.us/img145/7844/screenshot1dz8.png
private void layoutComponents(){
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
SequentialGroup hGroup = layout.createSequentialGroup();
JLabel nameLbl = new JLabel("Name");
JLabel countLbl = new JLabel("Amount");
JLabel dateLbl = new JLabel("Date(dd/MM/yy)");
hGroup.addGroup(layout.createParallelGroup().
addComponent(nameLbl).
addComponent(countLbl).
addComponent(dateLbl).
addComponent(go));
hGroup.addGroup(layout.createParallelGroup().
addComponent(name).
addComponent(count).
addComponent(date));
layout.setHorizontalGroup(hGroup);
SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(nameLbl).addComponent(name));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(countLbl).addComponent(count));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(dateLbl).addComponent(date));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(go));
layout.setVerticalGroup(vGroup);
frame.add( panel , BorderLayout.NORTH );
frame.add( new JScrollPane( textArea ) );
}
I use DesignGridLayout for most of my panels.
For the rare panels that DesignGridLayout cannot fully handle, I use a mix of Borderlayout and DesignGridLayout.
With DesigngridLayout you can manually code your layouts with a minimum number of lines of code, that are easy to type and read:
DesignGridLayouut layout = new DesignGridLayout(myPanel);
layout.row().grid(lblFirstName).add(txfFirstName).grid(lblSurName).add(txfSurName);
layout.row().grid(lblAddress).add(txfAddress);
layout.row().center().add(btnOK, btnCancel);
Each row of the panel grid is defined by one line of code. As you can see, "drawing" your panel is quite straightforward.
In addition, I find DesignGridLayout has some unique features (such as its "smart vertical resize").
GridBagLayout is powerful but quite primitively: the code that wires up the layout is very verbose. This utility library (actual just 1 jar file containing about 10 classes) simplifies a lot of works: http://code.google.com/p/painless-gridbag/ The following snippet is quoted from the home page of that site:
PainlessGridBag gbl = new PainlessGridBag(getContentPane(), false);
gbl.row().cell(lblFirstName).cell(txtFirstName).fillX()
.cell(lblFamilyName).cell(txtFamilyName).fillX();
gbl.row().cell(lblAddress).cellXRemainder(txtAddress).fillX();
gbl.doneAndPushEverythingToTop();
As a general overview, you might find an article I wrote a loooong time ago at sun to be useful. It's not up to date with the latest layout managers, but it concentrates on effective nesting of layout managers, rather than trying to do everything with one layout.
See http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr
I've found that for any non-trivial GUI I use multiple layouts with nested sub-panels where the main panel may have a GridBagLayout and each sub-panel (typically without a border or indication that it is a panel) uses a simpler layout where possible. Typically I'll use BorderLayout, FlowLayout, and BoxLayout for smaller, simpler sub-panels. By dividing small sections of the GUI into sub-panels and using the simplest layout possible to control that section of the GUI you can create complex, well arranged displays without too much headache from GridBagLayout's many options. Also, by grouping like display functionality into a panel, it creates more readable code.
Spring layout which was developed for the mantissa gui builder which is part of netbeans.
I've used GroupLayout as well. Again, its a standard JDK layout manager as of Java6, but you can find the library separate as well.
I've always been a big fan of the GridBagLayout. It resembles HTML tables a lot so it is intuitive to those web programmers.
I started off using various nested layouts, then moved over to GridBagLayout (which is pretty frustrating). Since then I tried FormLayout (but found it wasn't suited to anything but forms) and settled firmly on TableLayout, which overall I'm very happy with.
Since then I've discovered MiGLayout and although I haven't done much more than play with it, it seems very capable, quite similar to TableLayout and probably a little cleaner.
The big plus for me is that MiGLayout is set to become part of the JDK, so I intend to use it pretty much exclusively when it does.
The other thing to remember is that no matter which heavy-weight LayoutManager you settle on, there is always a place for some of the simpler layout managers such as GridLayout. I've seen some horrible things done with GridBagLayout that could have been done much more easily with a simpler layout manager.
I prefer to minimize dependencies on 3rd party libs, so it's usually BoxLayout for dialogs and GridBagLayout for "complicated" layouts. GridBagLayout is easy enough to understand, but a bit hard to configure. I wrote myself a tool for creating the code from HTML layouts (hope that helps others too):
http://www.onyxbits.de/content/blog/patrick/java-gui-building-gridbaglayout-manager-made-easy
The only layout manager that I have found, that I actually like is the Relative Layout Manager. The Relative Layout Manager works in a way that is consistent with how dialog boxes are conceptually organized. One draw-back is that while this layout manager deals with additive constraints. It does not seem to deal with ratio constraints. Fortunately it is pretty well designed, and I was able to implement this feature.
I use BorderLayout 90% of the time while nesting BoxLayout and SpringLayout
I'm a bit of Java newbie.
I tried GridBagLayout, gave up, then tried BoxLayout, then gave up, then made my own Custom Layout which worked. With GridBag and Box I put my best guess in and the Layout engines decided to do something different, without any apparent way to debug them.
With my custom layout, I could print out coordinates and widths and heights, to find out where it was going wrong. Its a bit mathy placing things but you've got the full power of java to use rather than the limited vocabulary of one of the builtin layout managers.
Of course it was just for a home project, you'd never be allowed to do this at work.
I use GridBagLayout for form like layouts, use BorderLayout for simple layouts, and FlowLayout for number of horizontal icons/buttons that have some spaces in between. Netbeans is also a good GUI builder that can avoid a lot of tedious layout codings to save your time.
I have started using Swing recently and I am using GridBagLayout.
I was sick of all those layoutmanagers that needed alot of setup, werent very readable or exhausting to do manually, so I wrote my own very simple laoutmanager which uses the abstraction of two photocorners keeping each component in place. You can add your component like this: parent.add(child,"topleft(0, 0.5)bottomright(0.5,1.0)");
Have a look here https://github.com/hageldave/UsefulStuff/blob/master/src/PhotoCornersLayout.java ;)
you're responisble for a correct layout yourself though, cause it's not checking overlappings or other shortcommings of your layout.

Categories

Resources