Formlayout and JPanel
Hi,
Its been some time since I last programmed with Java and I am happy to revisit it, but my knowledge is somewhat rusty. This is so elementary I feel a bit dim for asking it!
I'm trying to create a JApplet which will have two JPanels next to each other, in a FormLayout. The first
JPanel will be something of a canvas allowing the applet to draw images on it; the second is an image that
the routine uploads.
Below is the bare bones programme. I can get the second JPanel to display the image, but the first won't show;
at the moment, its just a simple override of paintComponent showing a green circle to ensure that I can display
something on screen. Is there anything obviously wrong?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class DeaApplet extends JApplet
zapPanel zap_panel;
deaPanel dea_panel;
public void init ()
Container content_pane = getContentPane ();
// Grab the image.
Image img = getImage (getCodeBase (), "zap_perch.PNG");
// Create an instanceof DrawingPanel
zap_panel = new zapPanel (img);
dea_panel = new deaPanel();
dea_panel.setSize(100,100);
dea_panel.setVisible(true);
// Add the DrawingPanel to the content pane.
content_pane.add (dea_panel);
content_pane.add (zap_panel);
content_pane.setVisible(true);
class deaPanel extends JPanel
deaPanel ()
public void paintComponent(Graphics g)
//super.paintComponent(g);
int width = getWidth();
int height = getHeight();
//System.out.println(width);
g.setColor( Color.GREEN );
g.drawOval(0, 0, width, height);
class zapPanel extends JPanel implements MouseListener
Image img;
zapPanel (Image img)
{ this.img = img;
public void paintComponent (Graphics g) {
super.paintComponent (g);
// Use the image width & height to find the starting point
int imgX = getSize ().width/2 - img.getWidth (this);
int imgY = getSize ().height/2 - img.getHeight (this);
//Draw image centered in the middle of the panel
g.drawImage (img, imgX, imgY, this);
} // paintComponent
public void mousePressed (MouseEvent e)
public void mouseReleased (MouseEvent e)
public void mouseEntered (MouseEvent e)
public void mouseExited (MouseEvent e)
public void mouseClicked (MouseEvent e)
//saySomething ("Mouse clicked (# of clicks: "
// + e.getClickCount () + ")", e);
// Between 62,53 and 127,202
int mx = e.getX();
int my = e.getY();
}
I'm trying to create a JApplet which will have two JPanels next to each other, in a FormLayout.1. FormLayout isn't a standard JDK class. Why not use one of the standard layouts? For just adding two components side by side, many of them would fit the bill. Or use a JSplitPane if you want the contents to be resizable.
2. The code you posted doesn't in fact use any FormLayout but rather the JApplet's default BorderLayout. So it's expected that you could see only the last component added to the default location of CENTER.\
3. setSize is redundant and undesired when the component is added to a container with a non-null layout manager.
Similar Messages
-
What's difference between JPanel.remove(); and JPanel = null
nice day,
how can remove JPanel (including its JComponents), safe way, can you explain the difference between JPanel.remove () and JPanel = null,
1/ because if JPanel does not contain any static JComponents
2/ or any reference to static objects,
then works as well as JPanel.remove or JPanel = null,
or what and why preferred to avoid some action (to avoid to remove or to avoid to null)mKorbel wrote:
nice day,
how can remove JPanel (including its JComponents), safe way, can you explain the difference between JPanel.remove () and JPanel = null, Remove the JPanel from the container it was part of and make sure you do not keep any references to it from your own classes. Don't make it any more difficult than it has to be. -
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 -
Htmlb:formLayout and htmlb:listBox problem
Hi, i have a problem with the htmlb:formLayout and the htmlb:listBox. When I try to integrate a listbox element in the formLayout
<hbj:formLayoutRow>
<hbj:formLayoutCell ...>
<hbj:listBox .......>
</hbj:listBox>
</hbj:formLayoutCell>
</hbj:formLayoutRow>
all subsequent row definitions are ignored.
All the elements are rendered into the same row.
Any idea how to come around this?
Regards
EdmundThe difference between our two code snippets is, I am using the model as input for the listBox and you are using the listBoxItem. The rest seems to be fine, for me.
But in my example the button is rendered into the same line into the next column.
<hbj:documentHead title="Administration"/>
<hbj:documentBody>
<jsp:useBean id="RoomsBean" tzpe="com.mgi.portalDev.test.iView.helper.RoomsBean" scope="session"></jsp:useBean>
<hbj:form id="ContactPersonsAdminForm">
<hbj:formLayout id="form_rooms" debugMode="false" marginTop="0" marginBottom="0" marginRight="0" marginLeft="0">
<hbj:formLayoutRow>
<hbj:formLayoutCell align="center">
<hbj:label id="lRoomsListBox" labelFor="rooms" text='XXX'/>
</hbj:formLayoutCell>
</hbj:formLayoutRow>
<hbj:formLayoutRow>
<hbj:formLayoutCell align="center" rowspan="10">
<hbj:listBox width="145" size="12"
id="rooms"
model="RoomsBean.model"
onSelect="selectRoom"
selection="1"/>
</hbj:formLayoutCell>
</hbj:formLayoutRow>
<hbj:formLayoutRow>
<hbj:formLayoutCell align="left">
<hbj:button id="delete_room" text='delete' design="STANDARD" disabled="true" onClick="deleteRoom"/>
</hbj:formLayoutCell>
</hbj:formLayoutRow>
</hbj:formLayout>
Regards
Edmund
P.S.: How can you format your source code in this forum? -
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. -
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 -
Problem with JTable and JPanel
Hi,
I'm having problems with a JTable in a JPanel. The code is basicly as follows:
public class mainFrame extends JFrame
public mainFrame()
//A menu is implemeted giving rise to the following actions:
public void actionPerformed(ActionEvent evt)
String arg = evt.getActionCommand();
if(arg.equals("Sit1"))
//cells, columnNames are initiated correctly
JTable table = new JTable(cells,columnNames);
JPanel holdingPanel = new JPanel();
holdingPanel.setLayout( new BorderLayout() );
JScrollPane scrollPane = new JScrollPane(holdingPanel);
holdingPanel.setBackground(Color.white);
holdingPanel.add(table,BorderLayout.CENTER);
add(scrollPane, "Center");
if(arg.equals("Sit2"))
if(scrollPane !=null)
remove(scrollPane);validate();System.out.println("ScrollPane");
if(holdingPanel !=null)
remove(holdingPanel);
if(table !=null)
remove(table);table.setVisible(false);System.out.println("table");
//Put other things on the holdingPanel....
private JScrollPane scrollPane;
private JPanel holdingPanel;
private JTable table;
}The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
Best regards
SchwartzIf you reuse the panel and scroll pane throughout the application,
instantiate them in the constructor, not in an often-called event
handler. In the event handler, you only do add/remove of the table
on to the panel. You can't remove the table from the container
which does not directly contain it.
if (arg.equals("Sit2")){
holdingPanel.remove(table);
holdingPanel.revalidate();
holdingPanel.repaint(); //sometimes necessary
} -
Problem with jframe has jtextfield and jpanel
hi all
i ve a jframe with some components on it
of these components a jpanel that i repaint each time i want
and a textfield for chatting between players
the problem is as follows
some times when i click the textfield after repaining the panel
it can not be activated and the caret does not appear
when i click any other component out or in the frame
and return i get it active and in a good state
i use single buffer for repapint
thanks for reading
i'm waiting for responseYour best bet here is to show us your code. We don't want to see all of it, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
[http://homepage1.nifty.com/algafield/sscce.html|http://homepage1.nifty.com/algafield/sscce.html]
Again, if the code is compilable and runnable more people will be able to help you.
Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. You may want to click on the Preview tab to make sure that your code is formatted correctly. Another way is to place the tag [code] at the top of your block of code and the tag [/code] at the bottom, like so:
[code]
// your code block goes here.
// note the differences between the tag at the top vs the bottom.
[/code] -
JMenuItem and JPanel issues!
I have a JMenuBar set up for my program and I want each JMenuItem to show a seperate JPanel when clicked. I've tried container.add(panel1); and panel1.setVisible(true); // (Previously set to false) but neither work.
This is how I've implemented it:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LibraryGUI extends JFrame {
private Container container;
private JPanel addStaffPanel, addStudentPanel;
private JLabel addStaffTitle, addStudentTitle;
// Set up GUI
public LibraryGUI() {
super("Visual Library 2.0");
container = getContentPane();
// Main menu items
JMenu fileMenu = new JMenu("File");
JMenu addMenu = new JMenu("Add");
JMenu removeMenu = new JMenu("Remove");
JMenu displayMenu = new JMenu("Display");
// Set up 'File' menu items
JMenuItem exit = new JMenuItem("Exit");
// Set up 'Add' menu items
JMenuItem addStaff = new JMenuItem("Add Staff Member");
JMenuItem addStudent = new JMenuItem("Add Student Member");
// Set up the 'File' menu
fileMenu.add(exit);
// Set up the 'Add' menu
addMenu.add(addStaff);
addMenu.add(addStudent);
// Create menu bar and attach it to the window
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
// Add menu's to the menu bar
bar.add(fileMenu);
bar.add(addMenu);
// File --> Exit (THIS WORKS FINE!)
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
// Set up 'Add Staff Member' title
addStaffTitle = new JLabel();
addStaffTitle.setText("Add Staff Member");
// Set up 'Add Student Member' title
addStudentTitle = new JLabel();
addStudentTitle.setText("Add Student Member");
// Set up 'Add Staff Member' panel
addStaffPanel = new JPanel();
addStaffPanel.setLayout(new GridLayout(1,1));
addStaffPanel.add(addStaffTitle);
// Add --> Add Staff Member (THIS DOESN'T WORK)
addStaff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
container.add(addStaffPanel);
// Set up 'Add Student Member' panel
addStudentPanel = new JPanel();
addStudentPanel.setLayout(new GridLayout(1,1));
addStudentPanel.add(addStudentTitle);
// Window settings
container.setBackground(Color.WHITE);
setSize(600, 400);
setVisible(true);
public static void main(String args[]) {
LibraryGUI application = new LibraryGUI();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}It compiles fine, no errors. But when the menu items are clicked it just does nothing. Any ideas?
- WillHmm, normally after adding/remove component to/from a panel you would need to use panel.revalidate. However, this didn't seem to work. Playing around I came up with the following:
container.setVisible(false);
container.removeAll();
container.add(addStudentPanel);
container.setVisible(true);
However, instead of using this approach I suggest you look at using a CardLayout. This Layout Manager was designed for this situation, to replace the entire contents of a panel with multiple different panels. Read this section from the Swing tutorial on Using Layout Managers:
http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html
An added bonus when using the CardLayout is that you can share the same ActionListeners for all panels. When adding a panel to the CardLayout you need to give a name to the panel (eg. "staff", "student"). When you create your menu items you can use the setActionCommand(...) method:
addStaff.setActionCommand("staff");
addStudend.setActionCommand("student");
Now in your action listener you would just use the event.getActionCommand() method to determine which card panel to display. -
Hello. I've been to this forum many times, but have always been a bit gunshy about posting anything of my own. Now I have a problem I haven't seen before, so here goes. I have a JPanel in a java program that has all sorts of other componants added to it. I am trying to display the whole thing in a jsp page. This is what I am doing in the java file to return the image ("display" is the JPanel):
public byte[] getImage(){
int w = display.getWidth();
int h = display.getHeight();
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
display.paint(img.createGraphics());
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, "jpeg", os);
return os.toByteArray();
}and then in the jsp page I say:
<%@ page contentType="image/jpeg" %>
<%@ page import="myPackage.MyClass" %>
<%
MyClass picture = new MyClass();
byte[] b = picture.getImage();
OutputStream os;
os = response.getOutputStream();
os.write(b);
os.flush();
%>And the problem is that the page is displaying a blank JPanel and none of the componants that were added to it. If I save the the JPanel as a jpeg in the java program, though, it does contain all the componants, so I am not sure what I am doing wrong here. If there is some way to get the all the JPanel componants returned, that would be great to know. Thanks for any help.nope, that didn't work.
Maybe I am going about solving the problem all wrong. The JPanel and its componants are kind of like a template. When a user of the system submits their information it automatically puts the data into the template and displays it on screen as a jpg. It works when I save the jpg as a file from the java program but not when i send the byte array to the jsp server. It just shows the blank panel....
Is there a better way to go about doing this? -
JScrollPane, JTextPane and JPanel... wtf?
i am working on a extending a JPanel to have a JTextPane in a JScrollPane. When i add the JTextPane to the JScrollPane inside of the JPanel object it doesn't scroll horizontally, but when i add the whole panel to a JScrollPane in the JFrame that i have testing it, it does scroll horizontally, the JScrollPane in both instances the JScrollBar has both horizontal and vertical scrolling set to as needed.
why is this happening?Thanks for your answers!
Revalidating did the trick, however I still have a problem with the JScrollPane... I created a new JScrollPane and wrote so:
myScrollPane = new JScrollPane(internalPanel);
myScrollPane.setPreferredSize(new java.awt.Dimension(2, 205));
myScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//Added Code
handScrollPane.setViewportView(handPanel);
//End Added Code
mainPanel.add(myScrollPane, BorderLayout.SOUTH);Then whenever items were added to the internalPanel I changed the scroll-bar's maximum value to the height of the internalPanel by writing:
myScrollPane.getVerticalScrollBar().setMaximum(internalPanel.getHeight());But when I run my application, the scroll-bar's maximum value doesn't change even though items are added to the internalPanel. Why is this?
With Thanks,
laginimaineb.
B.U.M.P (Sorry) -
Difference between content pane and jpanel?
can anyone please tell me the difference between a contentPane and a JPanel?
streetfi8er wrote:
can anyone please tell me the difference between a contentPane and a JPanel?Print the return value of its getClass() method and see for yourself.
kind regards,
Jos -
Help with BufferedImage and JPanel
I have a program that should display some curves, but thats not the problem, the real problem is when i copy the image contained in the JPanel to the buffered image then i draw something there and draw it back to the JPanel. My panel initialy its white but after the operation it gets gray
Please if some one could help with this
here is my code divided in three classes
//class VentanaPrincipal
package gui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.border.LineBorder;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
public class VentanaPrincipal extends javax.swing.JFrame {
//Set Look & Feel
try {
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch(Exception e) {
e.printStackTrace();
private JMenuItem helpMenuItem;
private JMenu jMenu5;
private JMenuItem deleteMenuItem;
private JSeparator jSeparator1;
private JMenuItem pasteMenuItem;
private JLabel jLabel4;
private JLabel jLabel5;
private JLabel jLabel3;
private JLabel jLabel2;
private JLabel jLabel1;
private JButton jSPLineButton;
private JButton jHermiteButton;
private JButton jBezierButton;
private JPanel jPanel2;
private JPanel jPanel1;
private JMenuItem jResetMenuItem1;
private JMenuItem copyMenuItem;
private JMenuItem cutMenuItem;
private JMenu jMenu4;
private JMenuItem exitMenuItem;
private JSeparator jSeparator2;
private JMenu jMenu3;
private JMenuBar jMenuBar1;
* Variables no autogeneradas
private int botonSeleccionado;
* Auto-generated main method to display this JFrame
public static void main(String[] args) {
VentanaPrincipal inst = new VentanaPrincipal();
inst.setVisible(true);
public VentanaPrincipal() {
super();
initGUI();
private void initGUI() {
try {
this.setTitle("Info3 TP 2");
jPanel1 = new pizarra();
getContentPane().add(jPanel1, BorderLayout.WEST);
jPanel1.setPreferredSize(new java.awt.Dimension(373, 340));
jPanel1.setMinimumSize(new java.awt.Dimension(10, 342));
jPanel1.setBackground(new java.awt.Color(0,0,255));
jPanel1.setBorder(BorderFactory.createCompoundBorder(
new LineBorder(new java.awt.Color(0, 0, 0), 1, true),
null));
BufferedImage bufimg = (BufferedImage)jPanel1.createImage(jPanel1.getWidth(), jPanel1.getHeight());
((pizarra) jPanel1).setBufferedImage(bufimg);
jPanel2 = new JPanel();
getContentPane().add(jPanel2, BorderLayout.CENTER);
GridBagLayout jPanel2Layout = new GridBagLayout();
jPanel2Layout.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0};
jPanel2Layout.rowHeights = new int[] {69, 74, 76, 71};
jPanel2Layout.columnWeights = new double[] {0.0, 0.0, 0.1};
jPanel2Layout.columnWidths = new int[] {83, 75, 7};
jPanel2.setLayout(jPanel2Layout);
jBezierButton = new JButton();
jPanel2.add(jBezierButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jBezierButton.setText("Bezier");
jBezierButton.setFont(new java.awt.Font("Tahoma",0,10));
jBezierButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
bezierActionPerformed();
jHermiteButton = new JButton();
jPanel2.add(jHermiteButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jHermiteButton.setText("Hermite");
jHermiteButton.setFont(new java.awt.Font("Tahoma",0,10));
jSPLineButton = new JButton();
jPanel2.add(jSPLineButton, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jSPLineButton.setText("SP Line");
jSPLineButton.setFont(new java.awt.Font("Tahoma",0,10));
jLabel1 = new JLabel();
jPanel2.add(jLabel1, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jLabel1.setText("Posicion Mouse");
jLabel2 = new JLabel();
jPanel2.add(jLabel2, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
jLabel2.setText("X:");
jLabel3 = new JLabel();
jPanel2.add(jLabel3, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
jLabel3.setText("Y:");
jLabel4 = new JLabel();
jPanel2.add(jLabel4, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
jLabel4.setText("-");
jLabel5 = new JLabel();
jPanel2.add(jLabel5, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
jLabel5.setText("-");
this.setSize(600, 400);
jMenuBar1 = new JMenuBar();
setJMenuBar(jMenuBar1);
jMenu3 = new JMenu();
jMenuBar1.add(jMenu3);
jMenu3.setText("Archivo");
jSeparator2 = new JSeparator();
jMenu3.add(jSeparator2);
exitMenuItem = new JMenuItem();
jMenu3.add(exitMenuItem);
exitMenuItem.setText("Exit");
jResetMenuItem1 = new JMenuItem();
jMenu3.add(jResetMenuItem1);
jResetMenuItem1.setText("Reset");
jMenu4 = new JMenu();
jMenuBar1.add(jMenu4);
jMenu4.setText("Edit");
cutMenuItem = new JMenuItem();
jMenu4.add(cutMenuItem);
cutMenuItem.setText("Cut");
copyMenuItem = new JMenuItem();
jMenu4.add(copyMenuItem);
copyMenuItem.setText("Copy");
pasteMenuItem = new JMenuItem();
jMenu4.add(pasteMenuItem);
pasteMenuItem.setText("Paste");
jSeparator1 = new JSeparator();
jMenu4.add(jSeparator1);
deleteMenuItem = new JMenuItem();
jMenu4.add(deleteMenuItem);
deleteMenuItem.setText("Delete");
jMenu5 = new JMenu();
jMenuBar1.add(jMenu5);
jMenu5.setText("Help");
helpMenuItem = new JMenuItem();
jMenu5.add(helpMenuItem);
helpMenuItem.setText("Help");
} catch (Exception e) {
e.printStackTrace();
private void bezierActionPerformed(){
botonSeleccionado = 1;
((pizarra) jPanel1).setTipoFigura(botonSeleccionado);
((pizarra) jPanel1).pintarGrafico();
//class graphUtils
package func;
import java.awt.Image;
import java.awt.Point;
import java.awt.image.BufferedImage;
public class graphUtils {
public static void dibujarPixel(BufferedImage img, int x, int y, int color){
img.setRGB(x, y, color);
public static void dibujarLinea(BufferedImage img, int x0, int y0, int x1, int y1, int color){
int dx = x1 - x0;
int dy = y1 - y0;
if (Math.abs(dx) > Math.abs(dy)) { // Pendiente m < 1
float m = (float) dy / (float) dx;
float b = y0 - m*x0;
if(dx < 0) dx = -1; else dx = 1;
while (x0 != x1) {
x0 += dx;
dibujarPixel(img, x0, Math.round(m*x0 + b), color);
} else
if (dy != 0) { // Pendiente m >= 1
float m = (float) dx / (float) dy;
float b = x0 - m*y0;
if(dy < 0) dy = -1; else dy = 1;
while (y0 != y1) {
y0 += dy;
dibujarPixel(img, Math.round(m*y0 + b), y0, color);
public static void dibujarBezier(BufferedImage img, Point puntos, int color){
//class pizarra
package gui;
import javax.swing.*;
import sun.awt.VerticalBagLayout;
import sun.security.krb5.internal.bh;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import func.graphUtils;
* esta clase pizarra extiende la clase JPanel y se agregan las funciones de pintado
* y rellenado que se muestra en pantalla dentro del panel que se crea con esta clase
* @author victorg
public class pizarra extends JPanel implements MouseListener{
private int tipoFigura;
BufferedImage bufferImagen;
Image img;
Graphics img_gc;
private Color colorRelleno, colorLinea;
private Point puntosBezier[] = new Point[3];
public pizarra(){
super();
addMouseListener(this);
//this.setBackground(Color.BLUE);
colorLinea = Color.BLUE;
public void setTipoFigura(int seleccion){
// se setea para ver si es bezier, hermite, SP line
tipoFigura = seleccion;
public void setTipoRelleno(int seleccion){
public void setColorRelleno(Color relleno){
colorRelleno = relleno;
public void setColorLinea(Color linea){
colorLinea = linea;
public void setBufferedImage(BufferedImage bufimg){
bufferImagen = bufimg;
public void pintarGrafico(){
Graphics g = this.getGraphics();
g.setColor(colorLinea);
//accion ejecutada cuando se selecciona para graficar un poligono
if(tipoFigura == 1){// bezier
if(bufferImagen == null){
//mantiene guardada la imagen cuando la pantalla pasa a segundo plano
bufferImagen = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
this.setBackground(Color.WHITE);
bufferImagen = (BufferedImage)createImage(getWidth(), getHeight());
//bufferImagen = this.createImage(getWidth(), getHeight());
//g.drawImage(bufferImagen,0,0,this);
graphUtils.dibujarLinea(bufferImagen,10, 10, 50, 50, colorLinea.getRGB());
g.drawImage(bufferImagen,0,0,this);
protected void paintComponent(Graphics g) { // llamado al repintar
//setBackground(colorFondo);
super.paintComponent(g);
// Graphics2D g2 = (Graphics2D)g;
// g2.drawImage(bufferImagen, 0,0, this);
// g2.dispose();
public void mouseClicked(MouseEvent arg0) {
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}1) Swing related questions should be posted in the Swing forum.
Custom painting should be done in the paintComponent(..) method. You created a "pintarGraphico" method to do the custom painting, but that method is only execute once. When Java determines that the panel needs to be repainted, the paintComponent() method is executed which simply does a super.paintComponent(), which in turn simply paints the background of the panel overwriting you custom painting. -
UIManager and Jpanel back ground on metal LnF
Hi
what wold be the property to change the back ground of all JPanels to lets say Color.WHITE
UIManager.put("what value",Color.white);also where would i be able to fine a list of the standard properties that the Metal LnF has? for colors?UIManager background color JPanel
i am ASSUMING it is UIManger.put("Panel.background",Color.WHITE);
but how can i be sure? for other values? there must be some documentation?
but i wanted to know where i could find a list of all of these "string values"
i did search the forum only found
UIManager.put("TextField.background", Color.WHITE);
UIManager.put("Label.background", Color.WHITE);but i would really more then just finding this ONE answer i would like to know where i can go and look them up for my self?
Very usefull to have!!
Maybe you are looking for
-
Problem with File panel and Local files
I am having a couple of problem using Dreamweaver (which may be related) and can't find any appropriate help on the web site. I have created a small website and have it up and running. I'm now trying to do some minor modifications. But Dreamw
-
N95restore didn't work with calendar??? any ideas?
Hi just updated to the latest 12.0.014 firmware.... was very careful to back up my phone to the memory card before I did this, update went fine... have just restored the back up and everything's ok except the calendar details! all to-do's and other c
-
Generate DP BOM check box without any description - /SAPAPO/CURTO_GEN_DP
I am using APO 5.1. In transaction /SAPAPO/CURTO_GEN_DP, there is a checkbox that is blank right below the "Expl. Quantity" field. I am trying to determine the purpose of that check box. Just recently since support stack 12, I am finding that if i
-
SAP Business Connector 4.8 and Webmethods EDI Package WmEDI
Hello, we want to upgrade our SAP Business Connector to 4.8 and need to install the EDI package provided by Webmethods earlier. We now figured out, that the EDI package is not provided anymore for download in the SAP Service Marketplace. Any idea, ho
-
Before the tab loads and takes you to the website, I now have to click a small arrow at the far right of the location bar for it to load the page. What setting changed in Firefox 4?