How to give a label position in Java? - java

I'm trying to give the label's a position but label1.setLocation(27, 20) doesn't work:
label = new JLabel( "Voer dag in" );
label1 = new JLabel( "Voer dag in" );
I want them under eachother
The whole code: http://pastebin.com/Gqtcqc9g
Thanks

Best practice is to use layout managers
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Each container component usually has default layout manager.
If you REALLY need absolute layout, you can set it to null. Component.setLayoutManager(null)
In your case you need to set GrigLayout (simple one) or GridBagLayout(more flexible)

try this out:
label = new JLabel( "Voer dag in" );
label.setBounds(0, 0, 100, 20);
//label.setBounds(x, y, width, height);
panel.add(label)
To move them easily you can use this aswell:
int xx = label.getBounds().getX();
int yy = label.getBounds().getY();
int ww = label.getBounds().getWidth();
int hh = label.getBounds().getHeight();
//to the right 10 units
xx+=10;
label.setBounds( xx, yy, ww, hh );
//that would be label.setBounds(xx+10,yy,ww,hh);
hope this helps ;)

You use JPanel to show components, which have FlowLayout as default, because of you can't position your components with help of setLocation().FlowLayout lyout components one by one in row.
For positioning component you need to use different LayoutManager. For example you can try GridLayout or GridBagLayout

Related

How to position objects on JPanel in a circular fashion without using NullLayout?

So my problem is this: I have a class extending JProgressBar and basically it looks like a flashing circle(it also breaks into segments depending on the amount of tasks, assigned to that indicator and I need to use setUI each time I switch indicator to the next task, which is pretty bad, but it'll do for now). I need to position 37 of those circles on a JPanel so that they form a circle of their own. Right now I do it like this:
private void addToPane(JPanel pane){
pane.setLayout(null);
Insets insets = pane.getInsets();
int width = pane.getWidth();
int height = pane.getHeight();
Dimension size = new Dimension(30, 30);
//Dimension mid = new Dimension(width/2, height/2);
Dimension mid = new Dimension(200, 250);
int r = 210;
double revox, revoy, angle = -Math.PI/2;
double revangle = 2*Math.PI/37;
for(int i=1; i<38; i++){
FlashingIndicator templabel = new FlashingIndicator();
templabel.setPreferredSize(size);
templabel.setUI(new ProgressIndicator(flash, 0, false));
templabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
indicate.add(templabel);
revox = r*Math.cos(angle);
revoy = r*Math.sin(angle);
indicate.get(i - 1).setBounds(insets.left + mid.width + (int) revox, insets.top + mid.height + (int) revoy, size.width, size.height);
pane.add(indicate.get(i - 1));
angle-=revangle;
}
}
No need to say: this is pretty bad. I wanted to locate them depending on the size of the panel, but when the function is being called in createUIComponents() (I use IntelliJ Idea's GUI builder) - the panel is not properly created yet, so getWidth() just returns 0. Using random numbers like 200 and 250 is bad for the obvious reasons. Also seems like the general consensus is: Null Layout is bad and I shouldn't use it. So here's the question:
Which LayoutManager should I use in order to locate indicators properly? All I can think of is GridLayout, but the way I do it now indicators nicely overlap a bit, using a grid will make it look rough. And if I can't use managers for this - how can I make it dependnant on the size of the panel?
Right now it looks like this:
Override the paintDeterminate() method in a custom BasicProgressBarUI to render your indicator; a related example is seen here. You can scale the rendering, as shown here, in a way that fills the component; this will obviate the need for a custom layout manager internal to your component. Override getPreferredSize(), as discussed here, so that your custom progress indicator works correctly with enclosing layouts.

JScrollPane won't scroll - Java Desktop Application

So I'm developing an application. I have a huge problem, and I know I'm probably overlooking something stupid, but my scollpanes aren't scrolling. Could someone please checkout the following code and tell me what I did wrong?
rotationPanel = new JPanel();
rotationPanel.setLayout(null);
rotationLabels = new JLabel[countStarters(team)];
resetXY(5,5);
for(int i = 0; i < countStarters(team); i++){
rotationLabels[i] = new JLabel(team.rotation.get(i).getName());
rotationLabels[i].setForeground(Color.BLACK);
addComp(rotationLabels[i], rotationPanel, labelX, labelY, labelSize);
labelY += 25;
}
//Other Code in between
rotationBar = new JScrollPane(rotationPanel);
rotationBar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
rotationBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
rotationBar.setPreferredSize(new Dimension(520, 150));
addComp(rotationBar, this, 15, 75, new Dimension(520, 150));
//addComp method:
public void addComp(JComponent comp, JComponent panel, int xPos, int yPos, Dimension size){
comp.setLocation(xPos,yPos);
comp.setSize(size);
panel.add(comp);
}
The resetXY() method just sets the x and y position for the components
Any help would be appreciated
Cheers,
Dave
JScrollPane uses either the components preferredSize or if implemented Scrollable#getPreferredScrollableViewportSize to determine what size the scroll pane and its view port can be. When the viewport is larger the the scroll pane, the scroll bars will appear
The Swing API has being designed around the use of the layout manager, choosing to do without the will cause you no end of problems and additional work.
Layout managers help you over come the difference between systems, including font rendering, DPI, screen sizes and rendering pipelines to mention a few.
I think your JPanel needs to have its size set, otherwise it will shrink to fit the JScrollPane.

java BoxLayout panel's alignment

I have browsed around and haven't found a solution that specifically tailors to my situation. I have a panel that I display in a dialog box:
//create dialog panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(headerPanel);
panel.add(type1Panel);
panel.add(type2Panel);
panel.add(type3Panel);
panel.add(type4Panel);
panel.add(type5Panel);
panel.add(type6Panel);
int result = JOptionPane.showConfirmDialog(null, panel, "Please enter values.", JOptionPane.OK_CANCEL_OPTION);
The size of the last two panels, type5 & type6, are of equal size so they look fine. However, the header and first 4 panels are of different sizes and I would like them all to be left aligned. As of yet I haven't found a good solution as how to fix this.
Question is, how can I left align the first 5 panels, but not last 2? If not how can I left align them all? The setalignmentx() isn't available for panels. I've tried using GridLayout, but then the width of the gui's main window is rather large and doesn't fit nicely onto the screen, hence the BoxLayout along Y axis.Thanks for any help or suggestions.
Here is an example that will left align all the JPanels added to the panel used as a container.
JPanel a = new JPanel();
JPanel b = new JPanel();
JPanel c = new JPanel();
a.setBackground( Color.RED );
b.setBackground( Color.GREEN );
c.setBackground( Color.BLUE );
a.setMaximumSize( new Dimension( 10, 10) );
b.setMaximumSize( new Dimension( 50, 10) );
a.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
b.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
c.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(a);
panel.add(b);
panel.add(c);
int result = JOptionPane.showConfirmDialog(null, panel, "Please enter values.", JOptionPane.OK_CANCEL_OPTION);
Create a horizontal javax.swing.Box object to contain each typenPanel object. Using horizontal struts and glue you can do whatever you want:
Box b1 = Box.createHorizontalBox();
b1.add( type1Panel );
b1.add( Box.createHorizontalGlue() );
panel.add( b1 );
For simplicity, write a helper method to do this for you:
private Component leftJustify( JPanel panel ) {
Box b = Box.createHorizontalBox();
b.add( panel );
b.add( Box.createHorizontalGlue() );
// (Note that you could throw a lot more components
// and struts and glue in here.)
return b;
}
Then:
panel.add( leftJustify( headerPanel ) );
panel.add( leftJustify( type1Panel ) );
panel.add( leftJustify( type2Panel ) );
etc.... You can get fancier with each line, adding components, glue, and struts. I've had great luck deeply nesting vertical and horizontal boxes, and writing helper methods when I want to do the same layout in a box more than once. There's no limits to what you can do, mixing components, struts, and glue as necessary.
I'm sure there's a better way to do all this, but I haven't found it yet. And the dynamic resizing lets a user with short bits of text use a small window and a user with lots of text resize it so it all fits.
You should use setAlignmentX on the panels because it is available for JPanel. The methods setAlignmentX and setAlignmentY are found in JComponent, which JPanel extends. It works...I've got code that uses those methods to align JPanels in a BoxLayout.
Ok, fine, edit your question while I'm answering it :)
Instead of using a JPanel try using a Box. I've found the Box class to be very useful as a container. From the API:
A lightweight container that uses a BoxLayout object as its layout
manager. Box provides several class methods that are useful for
containers using BoxLayout -- even non-Box containers.
If you haven't seen it yet, the tutorial How to Use BoxLayout is very helpful.

Getting the visible text in a JEditorPane

I have a JeditorPane in a JScrollPane. At certain points in the application, I would like to retrieve the text that is visible in the scrollPane (the text that is currently showing) and only this text. Is there a way to do this?
Thank you,
Elliott
You can use the viewport to get the view position and size.
JViewport viewport = scrollPane.getViewport();
Point startPoint = viewport.getViewPosition();
Dimension size = viewport.getExtentSize();
Point endPoint = new Point(startPoint.x + size.width, startPoint.y + size.height);
Once you know the start/end points of the viewport you can use:
int start = editorPane.viewToModel( startPoint );
int end = editorPane.viewToModel( endPoint );
Once you know the offsets of the text you want you can get the text from the component:
String text = editorPane.getText(start, end - start);
None of the code is tested.

Java: Fonts and Pixels

I'm making a game and in the menu I want to display the text in the center of the screen.
Is there a way in Java to get/calculate the width of a piece of text in a specified font with specified size and style.
Martijn
The FontMetrics.stringWidth method does just that -- it will return the width in pixels for a given String.
One can obtain the FontMetrics from a Graphics object by the getFontMetrics method.
For example:
g.setFont(new Font("Serif", Font.BOLD, 24));
int width = g.getFontMetrics().stringWidth("Hello World!");
System.out.println(width);
The result was:
135
In the class Font you have methods such like getLineMetrics or getStringBounds that may help you.
Just use a JLabel that is center aligned and the proper layout manager and you don't have to worry about this.
JLabel label = new JLabel("Text");
frame.add(label , SwingConstants.CENTER);

Categories