Jframe inside jpanel
hi all,
is it possible (in some way) to have a jframe inside a jpanel??
Thanks for answering
I think what you want is a JInternalFrame..
Similar Messages
-
Can we add JFrame to JPanel?
hi
I m trying to add JFrame which has JPanel with BufferedImage to another JPanel.
Is it possible? if yes kindly tell me how to achieve this.
thanxJust another cross poster.
[http://www.java-forums.org/java-2d/16085-how-add-jframe-inside-jpanel.html]
db -
Play a flash file inside a container or component like jframe or jpanel
sir ,
i want to embed a flash file inside a jframe or jpanel,
is it possible ,please give me related reference of URL providing
plugin for this.
i will be very thankful for this great help.
it is very importent for me.
byeI think JMF will support flash files.
-
Can video can be shown inside JPanel ?
Can video can be shown inside JPanel ? is there any example can do this ?
Several information can be found on this topic.
You can add video on JFrame, JInternalFrame so why not on JPanel ?
For more information you can shearch examples in the Sun's JMF examples.
I try to use video in JInternalFrame, but the frame rate is very bad ... so if you have solution... your are welcome.
Good luck! -
Problem with JFrame and JPanel
Okay, well I'm busy doing a lodge management program for a project and I have programmed this JFrame
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FinalTest extends JFrame
public JPanel contentPane;
public JImagePanel imgPanel;
private JLabel[] cottageIcon;
private boolean keepMoving;
private int selectedCottage;
public FinalTest()
super();
initializeComponent();
addActionListeners();
this.setVisible(true);
private void initializeComponent()
contentPane = (JPanel)getContentPane();
contentPane.setLayout(null);
imgPanel = new JImagePanel("back.png");
imgPanel.setLayout(null);
imgPanel.setBackground(new Color(1, 0, 0));
addComponent(contentPane, imgPanel, 10,10,imgPanel.getImageWidth(),imgPanel.getImageHeight());
cottageIcon = new JLabel[6];
keepMoving = true;
selectedCottage = 0;
cottageIcon[0] = new JLabel();
//This component will never be added or shown, but needs to be there to cover for no cottage selected
for(int a = 1; a < cottageIcon.length; a++)
cottageIcon[a] = new JLabel("C" + (a));
cottageIcon[a].setBackground(new Color(255, 0, 0));
cottageIcon[a].setHorizontalAlignment(SwingConstants.CENTER);
cottageIcon[a].setHorizontalTextPosition(SwingConstants.LEADING);
cottageIcon[a].setForeground(new Color(255, 255, 255));
cottageIcon[a].setOpaque(true);
addComponent(imgPanel,cottageIcon[a],12,(a-1)*35 + 12,30,30);
this.setTitle("Cottage Chooser");
this.setLocationRelativeTo(null);
this.setSize(new Dimension(540, 430));
private void addActionListeners()
imgPanel.addMouseListener(new MouseAdapter()
public void mousePressed(MouseEvent e)
imgPanel_mousePressed(e);
public void mouseReleased(MouseEvent e)
imgPanel_mouseReleased(e);
public void mouseEntered(MouseEvent e)
imgPanel_mouseEntered(e);
imgPanel.addMouseMotionListener(new MouseMotionAdapter()
public void mouseDragged(MouseEvent e)
imgPanel_mouseDragged(e);
private void addComponent(Container container,Component c,int x,int y,int width,int height)
c.setBounds(x,y,width,height);
container.add(c);
private void imgPanel_mousePressed(MouseEvent e)
for(int a = 1; a < cottageIcon.length; a++)
if(withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()))
System.out.println("B" + withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()));
selectedCottage = a;
keepMoving = true;
private void imgPanel_mouseReleased(MouseEvent e)
System.out.println("called");
selectedCottage = 0;
keepMoving = false;
private void imgPanel_mouseDragged(MouseEvent e)
System.out.println("XXX" + Math.random() * 100);
if(keepMoving)
int x = e.getX();
int y = e.getY();
if(selectedCottage!= 0)
cottageIcon[selectedCottage].setBounds(x-(30/2),y-(30/2),30,30);
if(!legalBounds(imgPanel,cottageIcon[selectedCottage]))
keepMoving = false;
cottageIcon[selectedCottage].setBounds(imgPanel.getWidth()/2,imgPanel.getHeight()/2,30,30);
System.out.println(cottageIcon[selectedCottage].getBounds());
private void imgPanel_mouseEntered(MouseEvent e)
System.out.println("entered");
private void but1_actionPerformed(ActionEvent e)
String input = JOptionPane.showInputDialog(null,"Enter selected cottage");
selectedCottage = Integer.parseInt(input) - 1;
public boolean legalBounds(Component containerComponent, Component subComponent)
int contWidth = containerComponent.getWidth();
int contHeight = containerComponent.getHeight();
int subComponentX = subComponent.getX();
int subComponentY = subComponent.getY();
int subComponentWidth = subComponent.getWidth();
int subComponentHeight = subComponent.getHeight();
if((subComponentX < 0) || (subComponentY < 0) || (subComponentX > contWidth) || (subComponentY > contHeight))
return false;
return true;
public boolean withinBounds(int mouseX, int mouseY, Rectangle componentRectangle)
int componentX = (int)componentRectangle.getX();
int componentY = (int)componentRectangle.getY();
int componentHeight = (int)componentRectangle.getHeight();
int componentWidth = (int)componentRectangle.getWidth();
if((mouseX >= componentX) && (mouseX <= (componentX + componentWidth)) && (mouseY >= componentY) && (mouseY <= (componentY + componentWidth)))
return true;
return false;
public static void main(String[] args)
JFrame.setDefaultLookAndFeelDecorated(true);
//JDialog.setDefaultLookAndFeelDecorated(true);
try
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
catch (Exception ex)
System.out.println("Failed loading L&F: ");
System.out.println(ex);
FinalTest ft = new FinalTest();
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JImagePanel extends JPanel
private Image image;
public JImagePanel(String imgFileName)
image = new ImageIcon(imgFileName).getImage();
setLayout(null);
public void paintComponent(Graphics g)
g.drawImage(image, 0, 0, null);
public Dimension getImageSize()
Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
return size;
public int getImageWidth()
int width = image.getWidth(null);
return width;
public int getImageHeight()
int height = image.getHeight(null);
return height;
}Now the problem I'm having is changing that class to a JFrame, it seems simple but I keep having problems like when it runs from another JFrame nothing pops up. I can do it like this:
FinalTest ft = new FinalTest();
ft.setVisible(false);
JPanel example = ft.contentPanehowever I will probably be marked down on this for bad code. I'm not asking for the work to be done for me, but I'm really stuck on this and just need some pointers so I can carry on with the project. Thanks,
SteveCeciNEstPasUnProgrammeur wrote:
I'd actually consider your GUI being a JPanel instead of a JFrame quite good design - makes it easy to put the stuff into an applet when necessary...
Anyway, you should set setVisible() to true to make it appear, not to false. Otherwise, I don't seem to understand your problem.That is actually my problem. I am trying to convert this JFrame to a JPanel -
Requesting focus for JTextField inside JPanel
I have an application with following containment hierarchy.
JFrame --> JSplitPane --> JPanel.
JPanel is itself a seperate class in a seperate file. I want to give focus to one of the JTextfields in JPanel, when the JPanel is intially loaded in the JFrame. I believe that I cannot request focus until the JPanel is constructed. I can set the focus from JFrame (which loads JPanel) but I want to do this from JPanel. Is there any technique to request focus from the JPanel itself (preferably during JPanel construction).
regards,
Nirvan.I believe that I cannot request focus until the JPanel is constructedYou can't request focus until the frame containing the panel is visible. You can use a WindowListener and handle the windowOpened event.
-
Resizing JFrames and JPanels !!!
Hi Experts,
I had one JFrame in which there are three objects, these objects are of those classes which extends JPanel. So, in short in one JFrame there are three JPanels.
My all JPanels using GridBagLayout and JFrame also using same. When I resize my JFrame ,it also resize my all objects.
My Problem is how should i allow user to resize JPanels in JFrame also?? and if user is resizing one JPanel than other should adjust according to new size ...
Plese guide me, how should i do this ...
Thanknig Java Community,
Dhwanit ShahHey there, thanx for your kind intereset.
Here is sample code .
In which there is JFrame, JPanel and in JPanel ther is one JButton.Jpanel is added to JFrame.
I want to resize JPanel within JFrame,I am able to do resize JFrame and JPanel sets accroding to it.
import java.awt.*;
import javax.swing.*;
import com.borland.jbcl.layout.*;
public class FramePanel extends JFrame {
JPanel contentPane;
GridBagLayout gridBagLayout1 = new GridBagLayout();
public FramePanel() {
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
public static void main(String[] args) {
FramePanel framePanel = new FramePanel();
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(gridBagLayout1);
this.setSize(new Dimension(296, 284));
this.setTitle("Frame and Panel Together");
MyPanel myPanel = new MyPanel();
this.getContentPane().add(myPanel);
this.setVisible(true);
class MyPanel extends JPanel {
public MyPanel() {
this.setSize(200,200);
this.setLayout(new FlowLayout());
this.setBackground(Color.black);
this.setVisible(true);
this.add(new JButton("Dhwanit Shah"));
I think i might explained my problem
Dhwanit Shah
[email protected] -
Inserting a Gui program using JFrames and JPanel
I'm trying to insert a chat program into a game that I've created! The chat program is using JFrames and JPanels. I want to insert this into a GridLayout and Panel. How can I go about doing this?
whatever is in the frame's contentPane now, you add to a separate JPanel.
you also add your chat stuff to the separate panel
the separate panel is added to the frame as the content pane -
Right, I suspect this has an easy solution, or maybe I have already happened on it, but I thought I'd best ask just in case.
I have an application that creates a JFrame from another JFrame, with a JPanel internal to it. What I want to happen is for the JPanel to do its business in its paintComponent method, and then dispose of its parent JFrame (that's dispose - no System.exit(0)'s here please :) ).
The only way I can see to do it is to pass a reference to the JFrame when the JPanel is created. But this seems to be a bit messy encapsulation-wise.
Any comers?you could make the parent JFrame have a thread that checked the status of the child JFrame's JPanel every second or so and then close itself when the JPanel is finished doing whatever it is doing.
-
How should I set maximum and minimum size of JFrame (or JPanel using BorderLayout) ? Please note setPreferredSize() and setMaximumSize() are not effective.
ThanksYou can't set the min/max size of a JPanel in a BorderLayout.
You can't directly set the min/max size of a JFrame, but you can add a ComponentListener the the JFrame and resize the JFrame when it exceeds you specified sizes.
Search the forum using "+maximum +addcomponentlistener".
Of course since this is a Swing question, you should be searching the Swing forum. -
I have a custom JPanel (CompassCalculatorPanel) that is created, setup and placed within a custom JFrame (CompassCalcFrame). Calling the JFrame constructor sets this all up and makes the Frame show up. All is good with placement and drawing initially. Then when a user changes the spinner value (change the compass heading) it is supposed to redraw the arrow within the panel. It does this just fine, but on the repaint, and subsequent paints, the Panel ends up being placed in the upper left corner of the frame, rather than at the place I positioned it. I've tried saving the upper left corner placement coordinates and calling setBounds(...) before and after the paintComponent(...) method is called. This has no effect, the panel still resides at 0, 0.
boldAny help that keeps the panel in place would be appreciated!*bold*
I am opening a new CompassCalcFrame with the following code from another GUI application like this (but this works from an example program perspective):
import com.vikingvirtual.flightsim.CompassCalcFrame;
* @author madViking
public class Main
public static void main(String[] args)
CompassCalcFrame CCF = new CompassCalcFrame();
}The CompassCalcFrame.java code:
package com.vikingvirtual.flightsim;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Point;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.JTextField;
* @author madViking
public class CompassCalcFrame extends JFrame
private CompassCalculatorPanel ccPanel;
private JButton closeButton;
private JLabel frameTitle;
private JSeparator frameSeparator1;
private JSpinner hdgSpinner;
private JTextField neField;
private JTextField eField;
private JTextField seField;
private JTextField sField;
private JTextField swField;
private JTextField wField;
private JTextField nwField;
private Point ccPanelPoint;
public CompassCalcFrame()
super ("Compass Heading Calculator");
initComponents();
this.setVisible(true);
calculateAndDraw();
private void initComponents()
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLayout(null);
this.setBackground(Color.BLACK);
this.setForeground(Color.BLACK);
Container ccPane = this.getContentPane();
Dimension panelDim = ccPane.getSize();
Font buttonFont = new Font("Tahoma", 0, 12);
Font compassFont = new Font("Digital-7", 0, 24);
Font titleFont = new Font("Lucida Sans", 1, 14);
frameTitle = new JLabel();
frameTitle.setText("Compass Heading Calculator");
frameTitle.setFont(titleFont);
frameTitle.setForeground(Color.WHITE);
closeButton = new JButton();
closeButton.setText("Close");
closeButton.setToolTipText("Click to close view");
closeButton.setFont(buttonFont);
closeButton.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt)
{closeButtonActionPerformed(evt);}});
hdgSpinner = new JSpinner();
hdgSpinner.setFont(compassFont);
hdgSpinner.setModel(new javax.swing.SpinnerNumberModel(0, 0, 359, 1));
hdgSpinner.setToolTipText("Enter heading to see angles change");
hdgSpinner.addChangeListener(new javax.swing.event.ChangeListener() {public void stateChanged(javax.swing.event.ChangeEvent evt)
{hdgSpinnerStateChanged(evt);}});
neField = new JTextField();
neField.setBackground(Color.BLACK);
neField.setEditable(false);
neField.setFont(compassFont);
neField.setForeground(Color.WHITE);
neField.setHorizontalAlignment(JTextField.CENTER);
neField.setBorder(null);
eField = new JTextField();
eField.setBackground(Color.BLACK);
eField.setEditable(false);
eField.setFont(compassFont);
eField.setForeground(Color.WHITE);
eField.setHorizontalAlignment(JTextField.CENTER);
eField.setBorder(null);
seField = new JTextField();
seField.setBackground(Color.BLACK);
seField.setEditable(false);
seField.setFont(compassFont);
seField.setForeground(Color.WHITE);
seField.setHorizontalAlignment(JTextField.CENTER);
seField.setBorder(null);
sField = new JTextField();
sField.setBackground(Color.BLACK);
sField.setEditable(false);
sField.setFont(compassFont);
sField.setForeground(Color.WHITE);
sField.setHorizontalAlignment(JTextField.CENTER);
sField.setBorder(null);
swField = new JTextField();
swField.setBackground(Color.BLACK);
swField.setEditable(false);
swField.setFont(compassFont);
swField.setForeground(Color.WHITE);
swField.setHorizontalAlignment(JTextField.CENTER);
swField.setBorder(null);
wField = new JTextField();
wField.setBackground(Color.BLACK);
wField.setEditable(false);
wField.setFont(compassFont);
wField.setForeground(Color.WHITE);
wField.setHorizontalAlignment(JTextField.CENTER);
wField.setBorder(null);
nwField = new JTextField();
nwField.setBackground(Color.BLACK);
nwField.setEditable(false);
nwField.setFont(compassFont);
nwField.setForeground(Color.WHITE);
nwField.setHorizontalAlignment(JTextField.CENTER);
nwField.setBorder(null);
frameSeparator1 = new JSeparator();
frameSeparator1.setForeground(Color.WHITE);
frameSeparator1.setBackground(Color.BLACK);
ccPanel = new CompassCalculatorPanel();
// Add components to pane
ccPane.add(frameTitle);
ccPane.add(closeButton);
ccPane.add(frameSeparator1);
ccPane.add(nwField);
ccPane.add(hdgSpinner);
ccPane.add(neField);
ccPane.add(wField);
ccPane.add(ccPanel);
ccPane.add(eField);
ccPane.add(swField);
ccPane.add(sField);
ccPane.add(seField);
// Begin Component Layout
Insets paneInsets = ccPane.getInsets();
Point P1 = new Point(0, 0);
Point P2 = new Point(0, 0);
Point P3 = new Point(0, 0);
Dimension size = frameTitle.getPreferredSize();
frameTitle.setBounds((5 + paneInsets.left), (5 + paneInsets.top), size.width, size.height);
P1.setLocation((5 + paneInsets.left), (5 + paneInsets.top + size.height + 5));
P2.setLocation((P1.x + size.width + 5), (paneInsets.top + 5));
size = closeButton.getPreferredSize();
closeButton.setBounds(P2.x, P2.y, size.width, size.height);
frameSeparator1.setBounds(P1.x, P1.y, (panelDim.width - paneInsets.left - paneInsets.right), 10);
P1.setLocation(P1.x, (P1.y + 10 + 5));
P2.setLocation((P1.x + 50 + 75), P1.y);
P3.setLocation((P1.x + 50 + 75 + 60 + 75), P1.y);
nwField.setBounds(P1.x, P1.y, 50, 26);
hdgSpinner.setBounds(P2.x, P2.y, 60, 26);
neField.setBounds(P3.x, P3.y, 50, 26);
P2.setLocation((P1.x + 50 + 5), (P1.y + 26 + 5));
P1.setLocation(P1.x, (P1.y + 26 + 5 + 87));
P3.setLocation((P1.x + 50 + 5 + 200 + 5), P1.y);
wField.setBounds(P1.x, P1.y, 50, 26);
ccPanel.setBounds(P2.x, P2.y, 200, 200);
ccPanelPoint = new Point(P2.x, P2.y);
eField.setBounds(P3.x, P3.y, 50, 26);
P1.setLocation(P1.x, (P1.y + 26 + 87 + 5));
P2.setLocation((P1.x + 50 + 80), P1.y);
P3.setLocation((P1.x + 50 + 80 + 50 + 80), P1.y);
swField.setBounds(P1.x, P1.y, 50, 26);
sField.setBounds(P2.x, P2.y, 50, 26);
seField.setBounds(P3.x, P3.y, 50, 26);
// End with Frame sizing
Dimension frameDim = new Dimension((paneInsets.left + 5 + 50 + 5 + 200 + 5 + 50 + 5 + paneInsets.right + 10), (P1.y + 26 + 5 + paneInsets.bottom + 40));
this.setPreferredSize(frameDim);
this.setSize(frameDim);
//this.setSize((paneInsets.left + 5 + 50 + 5 + 200 + 5 + 50 + 5 + paneInsets.right), (P1.y + 26 + 5 + paneInsets.bottom));
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt)
this.dispose();
private void hdgSpinnerStateChanged(javax.swing.event.ChangeEvent evt)
calculateAndDraw();
private void calculateAndDraw()
int angle = (Integer)hdgSpinner.getValue();
int[] headings = new int[7];
int addAngle = 45;
for (int i = 0; i < 7; i++)
headings[i] = angle + addAngle;
if (headings[i] >= 360)
headings[i] -= 360;
addAngle += 45;
neField.setText(String.valueOf(headings[0]));
eField.setText(String.valueOf(headings[1]));
seField.setText(String.valueOf(headings[2]));
sField.setText(String.valueOf(headings[3]));
swField.setText(String.valueOf(headings[4]));
wField.setText(String.valueOf(headings[5]));
nwField.setText(String.valueOf(headings[6]));
ccPanel.paintComponent(this.getGraphics(), angle);
ccPanel.setBounds(ccPanelPoint.x, ccPanelPoint.y, 200, 200);
//ccPanel.repaint(this.getGraphics(), angle);
}The CompassCalculatorPanel.java code:
* To change this template, choose Tools | Templates
* and open the template in the editor.
package com.vikingvirtual.flightsim;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
* @author madViking
public class CompassCalculatorPanel extends javax.swing.JPanel
private int xCent;
private int yCent;
public CompassCalculatorPanel()
super();
@Override
public void paintComponent(Graphics g)
paintComponent(g, 0);
public void repaint(Graphics g, int angle)
paintComponent(g, angle);
public void paintComponent(Graphics g, int angle)
super.paintComponent(g);
Dimension panelDim = this.getSize();
xCent = (panelDim.width / 2);
yCent = (panelDim.height / 2);
float[] dashArray = {8.0f};
Graphics2D g2D = (Graphics2D)g;
g2D.setColor(new Color(53, 153, 0));
g2D.fillRect(0, 0, panelDim.width, panelDim.height);
BasicStroke hdgLine = new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
BasicStroke northLine = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10.0f, dashArray, 0.0f);
Stroke stdStroke = g2D.getStroke();
// Setup Heading Arrow Points
Point hdgBottom = new Point(xCent, panelDim.height - 15);
Point hdgTop = new Point(xCent, 15);
Point ltHdgArr = new Point(xCent - 10, 20);
Point rtHdgArr = new Point(xCent + 10, 20);
// Setup North Arrow Points
Point nthBottom = new Point(xCent, panelDim.height - 15);
Point nthTop = new Point(xCent, 15);
Point ltNthArr = new Point(xCent - 8, 20);
Point rtNthArr = new Point(xCent + 8, 20);
// Rotate North Arrow Points
nthBottom = rotatePoint(nthBottom, (0 - angle), true);
nthTop = rotatePoint(nthTop, (0 - angle), true);
ltNthArr = rotatePoint(ltNthArr, (0 - angle), true);
rtNthArr = rotatePoint(rtNthArr, (0 - angle), true);
// Draw Heading Line
g2D.setColor(Color.RED);
g2D.setStroke(hdgLine);
g2D.drawLine(hdgBottom.x, hdgBottom.y, hdgTop.x, hdgTop.y);
g2D.drawLine(ltHdgArr.x, ltHdgArr.y, hdgTop.x, hdgTop.y);
g2D.drawLine(rtHdgArr.x, rtHdgArr.y, hdgTop.x, hdgTop.y);
g2D.setStroke(stdStroke);
// Draw North Line
g2D.setColor(Color.WHITE);
g2D.setStroke(northLine);
g2D.drawLine(nthBottom.x, nthBottom.y, nthTop.x, nthTop.y);
g2D.drawLine(ltNthArr.x, ltNthArr.y, nthTop.x, nthTop.y);
g2D.drawLine(rtNthArr.x, rtNthArr.y, nthTop.x, nthTop.y);
g2D.setStroke(stdStroke);
// Draw circles
g2D.setColor(Color.BLUE);
g2D.setStroke(hdgLine);
g2D.drawOval(5, 5, (panelDim.width - 10), (panelDim.height - 10));
g2D.setStroke(stdStroke);
g2D.fillOval((xCent - 2), (yCent - 2), 5, 5);
g2D.setStroke(stdStroke);
private Point rotatePoint(Point p, int angle, boolean centerRelative)
double ix, iy;
double hyp = 0.0;
double degrees = 0.0;
if (centerRelative == true)
ix = (double)(p.x - xCent);
iy = (double)((p.y - yCent)*-1);
else
ix = (double)p.x;
iy = (double)p.y;
if (ix == 0)
ix = 1;
hyp = Math.sqrt((Math.pow(ix, 2)) + (Math.pow(iy, 2)));
if ((ix >= 0) && (iy >= 0))
degrees = Math.toDegrees(Math.atan(ix/iy));
else if((ix >= 0) && (iy < 0))
degrees = Math.abs(Math.toDegrees(Math.atan(iy/ix)));
degrees = degrees + 90.0;
else if ((ix < 0) && (iy < 0))
degrees = Math.toDegrees(Math.atan(ix/iy));
degrees = degrees + 180.0;
else if ((ix < 0) && (iy >= 0))
degrees = Math.abs(Math.toDegrees(Math.atan(iy/ix)));
degrees = degrees + 270.0;
degrees = degrees + angle;
if (degrees >= 360)
degrees = degrees - 360;
if (degrees < 0)
degrees = degrees + 360;
double interX = Math.sin(Math.toRadians(degrees));
double interY = Math.cos(Math.toRadians(degrees));
interX = interX * hyp;
interY = ((interY * hyp) * -1);
if (centerRelative == true)
p.x = xCent + (int)Math.floor(interX);
p.y = yCent + (int)Math.floor(interY);
else
p.x = (int)Math.floor(interX);
p.y = (int)Math.floor(interY);
return p;
}In response to the first couple of comments made about using Absolute positioning (layout null), I took a look at the page on doing layouts, which happens to be the link you sent. I read about each, and decided that a GridBag layout would be best. So I created a new class called CompassCalcGridBagFrame and set it all up using the same components, but with a Grid Bag layout. I encounter the exact same problem.
Just FYI: I originally created this frame using the NetBeans (6.9.1) Frame form builder. By default that uses the Free Design setting, which creates group layouts for both vertical and horizontal spacing. This is where the problem first came to be. I next used the builder to create an absolute positioning frame, which had the same issue. That is when I started building my frames using code only - no NetBeans GUIs. This is where the absolute layout from scratch code started. Same effect. And now, I've created a Grid Bag layout from code, and same effect. There has to be something I'm missing overall, as this effects all of my different layout designs.
The one thing from gimbal2's previous comment is, should I be using this custom panel within another panel? I am currently adding all of the components (and in Grid Bag, the GridBag layout) to the frame pane itself. Is that OK, or should I use a generic JPanel, and have the components all within that?
Here is the code for the newest frame class (CompassCalcGridBagFrame):
package com.vikingvirtual.flightsim;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.JTextField;
* @author madViking
public class CompassCalcGridBagFrame extends JFrame
private CompassCalculatorPanel ccPanel;
private JButton closeButton;
private JLabel frameTitle;
private JSeparator frameSeparator1;
private JSpinner hdgSpinner;
private JTextField neField;
private JTextField eField;
private JTextField seField;
private JTextField sField;
private JTextField swField;
private JTextField wField;
private JTextField nwField;
private Point ccPanelPoint;
public CompassCalcGridBagFrame()
super ("Compass Heading Calculator");
initComponents();
this.pack();
this.setVisible(true);
calculateAndDraw();
private void initComponents()
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container ccPane = this.getContentPane();
ccPane.setLayout(new GridBagLayout());
ccPane.setBackground(Color.BLACK);
ccPane.setForeground(Color.BLACK);
Font buttonFont = new Font("Tahoma", 1, 12);
Font compassFont = new Font("Digital-7", 0, 24);
Font titleFont = new Font("Lucida Sans", 1, 14);
frameTitle = new JLabel();
frameTitle.setText("Compass Heading Calculator");
frameTitle.setFont(titleFont);
frameTitle.setHorizontalAlignment(JLabel.CENTER);
frameTitle.setPreferredSize(new Dimension(220, 25));
frameTitle.setForeground(Color.BLACK);
closeButton = new JButton();
closeButton.setText("Close");
closeButton.setToolTipText("Click to close view");
closeButton.setFont(buttonFont);
closeButton.setPreferredSize(new Dimension(75, 25));
closeButton.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt)
{closeButtonActionPerformed(evt);}});
hdgSpinner = new JSpinner();
hdgSpinner.setFont(compassFont);
hdgSpinner.setModel(new javax.swing.SpinnerNumberModel(0, -1, 360, 1));
hdgSpinner.setToolTipText("Enter heading to see angles change");
hdgSpinner.setPreferredSize(new Dimension(50, 26));
hdgSpinner.addChangeListener(new javax.swing.event.ChangeListener() {public void stateChanged(javax.swing.event.ChangeEvent evt)
{hdgSpinnerStateChanged(evt);}});
neField = new JTextField();
neField.setBackground(Color.BLACK);
neField.setEditable(false);
neField.setFont(compassFont);
neField.setForeground(Color.WHITE);
neField.setHorizontalAlignment(JTextField.CENTER);
neField.setPreferredSize(new Dimension(50, 26));
neField.setBorder(null);
eField = new JTextField();
eField.setBackground(Color.BLACK);
eField.setEditable(false);
eField.setFont(compassFont);
eField.setForeground(Color.WHITE);
eField.setHorizontalAlignment(JTextField.CENTER);
eField.setPreferredSize(new Dimension(50, 26));
eField.setBorder(null);
seField = new JTextField();
seField.setBackground(Color.BLACK);
seField.setEditable(false);
seField.setFont(compassFont);
seField.setForeground(Color.WHITE);
seField.setHorizontalAlignment(JTextField.CENTER);
seField.setPreferredSize(new Dimension(50, 26));
seField.setBorder(null);
sField = new JTextField();
sField.setBackground(Color.BLACK);
sField.setEditable(false);
sField.setFont(compassFont);
sField.setForeground(Color.WHITE);
sField.setHorizontalAlignment(JTextField.CENTER);
sField.setPreferredSize(new Dimension(50, 26));
sField.setBorder(null);
swField = new JTextField();
swField.setBackground(Color.BLACK);
swField.setEditable(false);
swField.setFont(compassFont);
swField.setForeground(Color.WHITE);
swField.setHorizontalAlignment(JTextField.CENTER);
swField.setPreferredSize(new Dimension(50, 26));
swField.setBorder(null);
wField = new JTextField();
wField.setBackground(Color.BLACK);
wField.setEditable(false);
wField.setFont(compassFont);
wField.setForeground(Color.WHITE);
wField.setHorizontalAlignment(JTextField.CENTER);
wField.setPreferredSize(new Dimension(50, 26));
wField.setBorder(null);
nwField = new JTextField();
nwField.setBackground(Color.BLACK);
nwField.setEditable(false);
nwField.setFont(compassFont);
nwField.setForeground(Color.WHITE);
nwField.setHorizontalAlignment(JTextField.CENTER);
nwField.setPreferredSize(new Dimension(50, 26));
nwField.setBorder(null);
frameSeparator1 = new JSeparator();
frameSeparator1.setForeground(Color.WHITE);
frameSeparator1.setBackground(Color.BLACK);
frameSeparator1.setPreferredSize(new Dimension(320, 10));
ccPanel = new CompassCalculatorPanel();
ccPanel.setPreferredSize(new Dimension(250, 250));
GridBagConstraints gbc = new GridBagConstraints();
// Begin Component Layout
gbc.insets = new Insets(0, 0, 0, 0);
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
ccPane.add(nwField, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 1;
gbc.weightx = 0.4;
gbc.weighty = 0.4;
gbc.anchor = GridBagConstraints.PAGE_START;
ccPane.add(hdgSpinner, gbc);
gbc.gridx = 3;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
ccPane.add(neField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
gbc.anchor = GridBagConstraints.LINE_START;
ccPane.add(wField, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 2;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.CENTER;
ccPane.add(ccPanel, gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
gbc.anchor = GridBagConstraints.LINE_END;
ccPane.add(eField, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
gbc.anchor = GridBagConstraints.LAST_LINE_START;
ccPane.add(swField, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 2;
gbc.gridheight = 1;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
gbc.anchor = GridBagConstraints.PAGE_END;
ccPane.add(sField, gbc);
gbc.gridx = 3;
gbc.gridy = 2;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
gbc.anchor = GridBagConstraints.LAST_LINE_END;
ccPane.add(seField, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 4;
gbc.gridheight = 1;
gbc.insets = new Insets(10, 5, 10, 5);
gbc.weightx = 0.6;
gbc.weighty = 0.6;
gbc.anchor = GridBagConstraints.CENTER;
ccPane.add(frameSeparator1, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gbc.gridwidth = 2;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.PAGE_START;
ccPane.add(closeButton, gbc);
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt)
this.dispose();
private void hdgSpinnerStateChanged(javax.swing.event.ChangeEvent evt)
calculateAndDraw();
private void calculateAndDraw()
int angle = (Integer)hdgSpinner.getValue();
if (angle == -1)
angle = 359;
if (angle == 360)
angle = 0;
int[] headings = new int[7];
int addAngle = 45;
for (int i = 0; i < 7; i++)
headings[i] = angle + addAngle;
if (headings[i] >= 360)
headings[i] -= 360;
addAngle += 45;
hdgSpinner.setValue(Integer.valueOf(angle));
neField.setText(String.valueOf(headings[0]));
eField.setText(String.valueOf(headings[1]));
seField.setText(String.valueOf(headings[2]));
sField.setText(String.valueOf(headings[3]));
swField.setText(String.valueOf(headings[4]));
wField.setText(String.valueOf(headings[5]));
nwField.setText(String.valueOf(headings[6]));
ccPanel.paintComponent(this.getGraphics(), angle);
} -
I have a JFrame object called mainJFrame constructed inside the main method in a program which I have made. Later I would need to use the getWidth() on the mainJFrame object in another class. Don't know how to design this. I tried to make the mainJFrame a public constant inside the class which contain the main method.
This is a school project and in the specifications it is written that all the object have to be private, so I guess I cant make it as an public constant which I have made it. my program is already working but I just need to have it running with the mainJFrame object reference not as a public reference.
/Thanks in regard from a future Java programmerbold This is where I call the JFrame....(it is called just frame and not mainFrame which I wrote earlier) bold
public class BouncePanel2 extends JPanel implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == timer) {
setSize( ( bold BounceMain.frame.getWidth() bold /2)-4, (BounceMain.frame.getHeight() )-32);
bold this is a working version of the class containing the main method bold
public class BounceMain {
bold public static final JFrame frame= new JFrame("Bounce slutversion"); bold
public static void main(String[] args) {
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel );
frame.setSize(604,632);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
bold an this is another working verison bold
public class BounceMain {
static public JFrame frame;
public static void main(String[] args) {
bold frame = new JFrame("Bounce slutversion"); bold
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel );
frame.setSize(604,632);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
but both these versions contains a public JFrame reference
I will look at your reply which you wrote but I just wanted to write this if case it would clarify anything... -
Hi,
I have a JLayeredPane containing JComponents, then I add the JLayeredPane to a JPanel. After that I set the JPanel to the contentPane of my JFrame. Now my components inside the JLayeredPane won't paint themselfs. Why is that?
This is what I do in my class extending JFrame:
JLayeredPane lp = new JLayeredPane();
lp.add(component1);
lp.add(component2);
JPanel panel = new JPanel();
panel.add(lp);
setContentPane(panel);
If I do it like this it works:
JLayeredPane lp = new JLayeredPane();
lp.add(component1);
lp.add(component2);
setContentPane(lp);
The problem is not that I haven't set the Bounds of the components.
Isn't it possible to add a JLayeredPane to a JPanel?
Thanks!
ErikThe problem was that I hadn't set prefferedSize on the JLayeredPane:)
Funny indeed! -
Advance level drawing problem with Jframe and JPanel need optimize sol?
Dear Experts,
I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
Note: i don't want to inherit jpanel or Jframe
here is my code : import java.awt.BorderLayout;
public class GameMain extends JFrame {
private static final long serialVersionUID = 1L;
public int mX, mY;
int localpoints = 0;
protected static JTextField[][] squares;
protected JLabel statusLabel = new JLabel("jugno");
Label lbl_score = new Label("score");
Label lbl_scorelocal = new Label("local score");
protected static TTTService remoteTTTBoard;
// Define constants for the game
static final int CANVAS_WIDTH = 800; // width and height of the game screen
static final int CANVAS_HEIGHT = 600;
static final int UPDATE_RATE = 4; // number of game update per second
static State state; // current state of the game
private int mState;
// Handle for the custom drawing panel
private GameCanvas canvas;
// Constructor to initialize the UI components and game objects
public GameMain() {
// Initialize the game objects
gameInit();
// UI components
canvas = new GameCanvas();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
this.setContentPane(canvas);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setTitle("MY GAME");
this.setVisible(true);
public void gameInit() {
// Shutdown the game, clean up code that runs only once.
public void gameShutdown() {
// To start and re-start the game.
public void gameStart() {
private void gameLoop() {
public void keyPressed(KeyEvent e) {
public void keyTyped(KeyEvent e) {
public void gameKeyReleased(KeyEvent e) {
PuzzleBoard bd = getBoard();
for (int row = 0; row < 4; ++row) {
for (int col = 0; col < 4; ++col) {
if (e.getSource() == squares[row][col]) {
if (bd.isOpen(col, row)) {
lbl_score.setText("Highest Score = "
+ Integer.toString(bd.getPoints()));
setStatus1(bd);
pickSquare1(col, row, squares[row][col].getText()
.charAt(0));
protected void pickSquare1(int col, int row, char c) {
try {
remoteTTTBoard.pick(col, row, c);
} catch (RemoteException e) {
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
System.exit(1);
// method "called" by remote object to update the state of the game
public void updateBoard(PuzzleBoard new_board) throws RemoteException {
String s1;
for (int row = 0; row < 4; ++row) {
for (int col = 0; col < 4; ++col) {
squares[row][col].setText(new_board.ownerStr(col, row));
lbl_score.setText("Highest Score = "
+ Integer.toString(new_board.getPoints()));
setStatus1(new_board);
protected void setStatus1(PuzzleBoard bd) {
boolean locals = bd.getHave_winner();
System.out.println("local win" + locals);
if (locals == true) {
localpoints++;
System.out.println("in condition " + locals);
lbl_scorelocal.setText("Your Score = " + localpoints);
lbl_score
.setText("Highest Score = " + Integer.toString(bd.getPoints()));
protected PuzzleBoard getBoard() {
PuzzleBoard res = null;
try {
res = remoteTTTBoard.getState();
} catch (RemoteException e) {
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
System.exit(1);
return res;
/** Custom drawing panel (designed as an inner class). */
class GameCanvas extends JPanel implements KeyListener {
/** Custom drawing codes */
@Override
public void paintComponent(Graphics g) {
// setOpaque(false);
super.paintComponent(g);
// main box; everything placed in this
// JPanel box = new JPanel();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// add(statusLabel, BorderLayout.NORTH);
// set up the x's and o's
JPanel xs_and_os = new JPanel();
xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
squares = new JTextField[5][5];
for (int row = 0; row < 5; ++row) {
for (int col = 0; col < 5; ++col) {
squares[row][col] = new JTextField(1);
squares[row][col].addKeyListener(this);
if ((row == 0 && col == 1) || (row == 2 && col == 3)
|| (row == 1 && col == 4) || (row == 4 && col == 4)
|| (row == 4 && col == 0))
JPanel p = new JPanel(new BorderLayout());
JLabel label;
if (row == 0 && col == 1) {
label = new JLabel("1");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
else if (row == 4 && col == 0) {// for two numbers or
// two
// blank box in on row
label = new JLabel("2");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
else if (row == 1 && col == 4) {
label = new JLabel("3");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
else if (row == 4) {
label = new JLabel("4");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
else {
label = new JLabel("5");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
label.setOpaque(true);
label.setBackground(squares[row][col].getBackground());
label.setPreferredSize(new Dimension(label
.getPreferredSize().width, squares[row][col]
.getPreferredSize().height));
p.setBorder(squares[row][col].getBorder());
squares[row][col].setBorder(null);
p.add(label, BorderLayout.WEST);
p.add(squares[row][col], BorderLayout.CENTER);
xs_and_os.add(p);
} else if ((row == 2 && col == 1) || (row == 1 && col == 2)
|| (row == 3 && col == 3) || (row == 0 && col == 3)) {
xs_and_os.add(squares[row][col]);
// board[ row ][ col ].setEditable(false);
// board[ row ][ col ].setText("");
squares[row][col].setBackground(Color.RED);
squares[row][col].addKeyListener(this);
} else {
squares[row][col] = new JTextField(1);
// squares[row][col].addActionListener(this);
squares[row][col].addKeyListener(this);
xs_and_os.add(squares[row][col]);
this.add(xs_and_os);
this.add(statusLabel);
this.add(lbl_score);
this.add(lbl_scorelocal);
public void keyPressed(KeyEvent e) {
public void keyReleased(KeyEvent e) {
gameKeyReleased(e);
public void keyTyped(KeyEvent e) {
// main
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GameMain();
thanks a lot for your time , consideration and efforts.
jibby
Edited by: jibbylala on Sep 20, 2010 6:06 PMjibbylala wrote:
thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well. -
Hi,
I am new to Java.
I am reading the Java materials. Sometimes they use JFrame and
sometimes they use JPanel.
Can anyone tell me in which situation they will be used ?
Many thanks in advance.
IvanThere's also the issue of LayoutManagers.
Each Container has a default LayoutManager which is used to arrange the components within the Container.
This behavior can be changed with the setLayout() method.
Often times, a single JFrame will "contain" several JPanels - each with a specific layout for its Components -
and then the panels are arranged according to the frame's LayoutManager.
Maybe you are looking for
-
Error while setting up db mirroring in sql server 2012
Hi Team, I am trying to setup DB Mirroring in our setup and Need your help here! I've 3 servers (2 (Principal and witness) of them are in one machine and 1 (Mirror) is in other machine) setup ... Firewalls are turned off on all 3 of them.... I want t
-
Error when running workflow form list item - workflow manager SharePoint 2013
I am getting the following error in the workflow services log when I tried to run a SPD 2013 workflow from as list item. The workflow page comes up with an "An unexpected error has occurred" page when opened: Error processing management request. Meth
-
Sliding background banner in fluid grid layout
Hello all... Hope someone can help me. Kind of new to programming and dream weavers fluid grids. But I've started working on a website and encounted a problem. How do you implement a sliding background banner in the fluid grid design? PS: My design l
-
Can we import a user list (CSV) into GW to create accounts?
We are needing to add a few hundred new user accounts into GroupWise 2012. Can this be done by importing a user list in the form of a .CSV file or something similar? Anything would be better than single account creation. Do we need to create a templa
-
I have a Mac Pro 8 Core and Snow Leopard won't install from the DVD.
Any idea why?