Java - Draw a circle ON JButton and JTextArea - java

So I'm trying to draw a sort of oval on a button and textarea. Yes, there is a reason why I can't just use a Panel or Frame.
So the button and textarea already has text on it and needs to stay as a button and textarea for the reason of the program.
So far, I only got one button to have this circle, but none of the other buttons show up with the circles. And the textareas aren't showing any circles at all.
My Code so Far for the buttons:
for (int i = 0; i < (label.length) / 2; i++) {
butt = new JButton(label[i]); // label contains the text on button
butt.setPreferredSize(new Dimension(83, 100));
butt.add(smallPit); //smallpit is the circle graphics
game.add(butt); // game is a panel
// butt.setLayout(null);
}
for (int i = 6; i < label.length; i++) {
butt = new JButton(label[i]);
butt.setPreferredSize(new Dimension(83, 100));
butt.add(smallPit);
game.add(butt);
}
Code for textarea
score2.setBounds(0, 50, 100, 210);
score1.setBounds(700, 50, 100, 210);
score2.add(scorePit);
score1.add(scorePit);
The outcome so far:

My guess is that this butt.add(smallPit); is causing your issues.
My guess is that smallPit extends from something like JComponent (something that extends from JComponent), the problem is a component can only reside within a single container, so each time you call butt.add(smallPit);, smallPit is removed from it's previous container before been added to the new one.
Instead, create an instance of smallPit (or what ever it is) and add it to each button which needs it.
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
You should also have a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

Related

Java JPanel subclass ignores bounds on adding components

I have a subclass of JPanel that I'm trying to add labels to
for(int i = 0; i < 10; i++)
{
JLabel lblPID = new JLabel("" + i);
lblPID.setBounds(55, i * 50, 15, 15);
this.add(lblPID);
}
But when this runs, the labels line up horizontally next to each other at the same y point, ignoring the bounds I'm setting. How do I have the panel lay them out vertically the way they're supposed to appear?
The likely problem is, the container you are adding your label to is using a layout manager, which is making it's own decisions about how your label should be laid out.
You should avoid using setBounds as you can not guarantee that the label will be rendered the same on different computers, even if they are running the same OS. Instead you should make use of appropriate layout managers, which make these decisions for you.
Take a look at Laying out Components within a Container for more details

JLabel does not appear over JButton? [duplicate]

This question already has an answer here:
How do I get a JLabel to show over a JButton?
(1 answer)
Closed 8 years ago.
I have a grid of 16 buttons which will represent dice. When a score is added, I want a JLabel to pop up in the middle and display the added score. The 16 buttons and one label are all within one JLabel. Why do the buttons always show on top of the JLabel, even when the JLabel is set to visible?
Thank you for any help!
Pictures
JButtons visible, JLabel is not:
When the JButtons are setVisible to false, the JLabel is seen:
Code
Here is the constructor to my code. The label does not show up if the buttons are visible.
public Grid()
{
super();
setLayout(null);
setBounds(125,205,290,290);
setBackground(new Color(139,69,19));
setBorder(new LineBorder(Color.black,5));
for(int a = 0; a < piece.length; a ++)
{
for(int b = 0; b < piece[0].length; b ++)
{
piece[a][b] = new DiceButton(0,0,a,b,null);
piece[a][b].addActionListener(this);
add(piece[a][b]);
}
}
scoringVisual = new JLabel("+ 200");
scoringVisual.setBounds(110, 135, 70, 30);
scoringVisual.setFont(new Font("Arial Rounded MT Bold", Font.BOLD, 20));
scoringVisual.setOpaque(true);
scoringVisual.setBackground(new Color(0,87,0));
scoringVisual.setForeground(new Color(38,224,2));
scoringVisual.setHorizontalAlignment(JLabel.CENTER);
scoringVisual.setBorder(new LineBorder(Color.black,1));
add(scoringVisual);
}
In your last posting I stated:
Basically the last component added is painted first.
However, I then posted example code (which was the same as your code):
c.add(button);
c.add(label);
Of course I meant to post:
c.add(label);
c.add(button);
Of course this is still a terrible way to do what your want. You should NOT be using a null layout. You should not be using setBounds() to position your components on the panel.
I don't have a background with glasspanes or anything,
That is why I gave you the link to the tutorial. It contains working exmaples.
but I wish to do this in the easiest way possible.
That is why I gave you the link to the tutorial. Sometimes you need to learn the basics to take advantage of what Swing has to offer. Since you don't know how Swing works you don't know that drawbacks of your current approach. We are trying to point you in the right direction at the start of your design phase so you don't have to revisit the design in the future when you encounter problems and it will become harder to change.

applet button filling area

I'm creating an applet and having problems with the positioning as size of my buttons. I've added two buttons, but the "OK" button seems to position and size itself correctly, but the "CLEAR" button fills the entire applet area behind the "OK" button. Any suggestions as to what is the problem?
#Override
public void init()
{
super.init();
setSize(J_WIDTH, J_HEIGHT);
setLayout(new BorderLayout());
btn_OK = new Button("OK");
btn_CLEAR = new Button("CLEAR");
btn_OK.setBounds(50, 450, 75, 50);
btn_CLEAR.setBounds(125, 50, 75, 50);
add(btn_OK);
add(btn_CLEAR);
btn_OK.addActionListener(this);
btn_CLEAR.addActionListener(this);
}
When using a BorderLayout, you should specify a location where you want to place the component. If you don't, the default is BorderLayout.CENTER. Also, each position can only contain one component. So when you call add(btn_OK), the OK button is added to the center of the panel. But then you replace it with the Clear button by calling add(btn_CLEAR);.
In addition, each position in the BorderLayout takes up a certain amount of space. The component at that position will stretch to fill that space. In particular, the CENTER takes up all remaining space not used by the other positions.
I think that BorderLayout is not what you want here. Check out the Visual Guide to Layout Managers for more information on each LayoutManager. You can also follow the rest of the tutorial trail for details about how to implement each of them.
You should also bookmark and familiarize yourself with the Java API docs. These are an essential tool for every Java programmer and will help you answer many questions on your own.

java applet buttons

OK so I have this applet thats like this
BorderLayout.CENTER - (Within this is JPanel)
BorderLayout.EAST - (Within this is a new GridLayout (4,5)
BorderLayout.SOUTH - (Within this is a TextArea)
Anyway, on the applet, I have to HOVER over the buttons to see them. They don't paint there I guess but I'm adding them in the init() method... so I don't know what I am doing wrong and why it's doing this.
setLayout( new BorderLayout() );
JPanel invOne = new JPanel(new GridLayout(5,4));
JPanel game = new JPanel();
add(invOne, BorderLayout.EAST);
add(game, BorderLayout.CENTER);
add(c, BorderLayout.SOUTH);
invOne.setBounds(416,0, 60, 28);
for (int i = 0, j = 20; i < 20; i = i+1, j = j-1) {
invOne.add(new JButton("SLOT " + j));
invOne.setBounds(32,32,100,100);
invOne.setFocusable(false);
}
game.setBounds(0,0, 416, 288);
repaint();
What are you trying to accomplish with all the setBounds() calls? Either you let pack() set your panel's size according to what's inside, or you set bounds once to where you want to see that panel sit. Especially the calls with a size of 32x32 pixels are not helping at all.
EDIT:
I found these problems:
As one other poster mentioned, you're mixing Swing and AWT components. That doesn't work well. Essentially, if some of the components you use have a "J" at the beginning, you'll want to go with "J"'s for all of them. AWT is now considered "old school". It's a bit confusing because some classes and components used in GUIs don't have J's. I guess you need to work carefully with good examples or look the classes up.
For some reason, the applet didn't want to work well until I gave explicit row/column counts to the TextArea (now called JTextArea). I changed new TextArea() to new JTextArea(3,20).
The biggest problem may have been the empty paint() method. I wonder how the applet displayed anything at all? You could have removed the paint() method; I fixed it by calling super.paint().
Finally, class names (such as bl) should start with uppercase characters. The compiler in IdeOne grumbled at me for that.
Here's my fixed code.
Happy hacking!
Found one page (in german language) which describes the same problem: JButton widgets only show up after hovering over them.
The problem there was that AWT and Swing components/widgets have been mixed. I can't see from your code fragment if this is the case, but if you have java.awt.* imports, disable them, refactor your code to only use Swing classes and try again / hope for the best.
Another suggestion was to explicitely do a setVisible(true) for every button, but the questioner said, that this didn't help in his case.
After adding all your components in the panel, do you explicitely call the "pack()" (or the "repaint()") method ?
Not calling theses methods can result in graphic troubles in your Frames...
You are using Swing components in an Applet. You should use JApplet. Just change extends Applet to extends JApplet.

Moving and resizing JPanels object inside JFrame

Continuing my quest of learning Java by doing a simple game, i stumbled upon a little issue. My gameboard extends JPanel as well as each piece of the board. Now, this presents some problems:
Cant set size of each piece, therefore, each piece JPanel ocupy the whole JFrame, concealing the rest of the pieces and the background (gameboard).
Cant set the position of the pieces.
I have the default flow manager. Tried setbounds and no luck.
Perhaps i should make the piece to extend other JComponent?
Added image:
That's the piece, now the greyed area is also the piece! Checked that by making a mousePressed listener and assigning some stuff to it. Below the grey area, is the gameboard (or at least, should be!), another JPanel.
alt text http://img42.imageshack.us/img42/2227/screenshotvdy.png
Some code:
package TheProject;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameWindow extends JFrame {
public GameWindow() {
setSize(800, 600);
setLocationRelativeTo(null);
Map map = new Map(800, 600, 2);
add(map);
MilitaryUnit imperialRussia = new MilitaryUnit(30, Color.BLACK, Color.YELLOW, Color.WHITE);
imperialRussia.setPreferredSize(new Dimension(30, 30));
add(imperialRussia);
}
}
This happens when i apply the pack() method:
alt text http://img442.imageshack.us/img442/5813/screenshot2ml.png
Packs around the Unit, not the map which is bigger and fills the JFrame.
For a game that has random movement of pieces you would probably use a "null layout".
Read the section from the Swing tutorial on Absolute Positioning for more information.
I wrote a few games using JPanel. Basically the way I use JPanel is like I'm using a Canvas, viz I draw directly on it by overriding the paint() method. The reason why I use JPanel is because I can determine the size of my game world, then use the setPreferredSize() to set the size of the panel. I then add the panel to a JScrollPane. So this will take care of the panning, etc.
Say I'm writing a 2D game. This is how I use JPanel. I have a logical map (a 2D array) which holds my game map. Say each location is 32x32 pixel. So you start drawing the ground and what is on that ground in that location. eg in x=1, y=2 which is screen location x=32, y=64, you draw the ground first, then draw what is on the ground. So a rough outline of the render loop would be something like this
for (int y = 0; y < map.length; y++)
for (int x = 0; x < map[y].length; x++) {
drawGround(map[y][x])
for very element on on map[y][x] - render them
}
You set a MouseListener listener to the JPanel, so every mouse click you translate back to the map eg. mouse click x=54, y=72 would correspond to x=1, y=2. The calculation is a bit tricky if you have an isometric view.
The thing you have to be careful here is that everytime when you scroll the panel via the scroll panel, paint() will be called. So it is good to render your game board on a BufferedImage and then in the paint() method just draw the BufferedImage otherwise it'll be too slow.
Have you tried NetBeans' visual editor? You can use it to drag, drop, and resize to your convenience Swing objects in Design View, and can then switch to Code View to see the generated code. You can learn that way.
Have you tried setPreferredSize(Dimension d)?
Edit: You need to call pack() on your JFrame, after you've added your components:
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(800,600));
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(200,200));
frame.add(panel);
frame.pack();
frame.setvisible(true);
Also, you add a Map to your JFrame, which has the same dimensions as your JFrame - fine. But then afterwards, you add another component, to the default flowlayout. This cannot fit into your frame, as the Map already occupies 100% of the space.

Categories

Resources