JMenuBar Layout
The default Layout manage of a JMenuBar is BoxLayout.
Suppose two menus "File" and "Edit" are added to a JMenuBar, so every menu's width should be 50% width of the whole bar.
But from L&F, the width of menu "File" or "Edit" is much small, why?
Thanks!
And if only two menus are added to the bar, so each menu should
have a width of 512 pixels because of BoxLayout manager.The reason is because that's not how BoxLayout works.
Now, if you want them to be equally sized, then you should change the menubar's layout to a GridLayout.
If you don't want them equally sized (you want them like you see them) then you should leave it alone.
If you want to shift some to the right, put a glue component (see Box) before adding the right-side items.
Similar Messages
-
Error with dynamic array of class??
I have tried to create a new GUI java project. Maybe it's stupid but I can't try to find how to fix this error anymore :((
Can you help me please?
this is my code of project:
* JButton2.java
* Created on December 5, 2006, 2:15 AM
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
package javaapplication9;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
* @author Nguyen
public class JButton2 {
public JButton button;
public JButton2(String s) {
button = new JButton(s);
public void buttonmouseClick(MouseEvent evt, boolean check) {
if (button.getText()=="")
if (check == true) {
button.setText("X");
check = false;
else {
button.setText("O");
check = true;
* Main.java
* Created on December 5, 2006, 10:22 PM
package javaapplication9;
import javaapplication9.JButton2;
//import javaapplication9.JButton2;
* @author Nguyen
public class Main extends javax.swing.JFrame {
int N = 3, i, j;
boolean check = true;
public javaapplication9.JButton2[][] mas = new javaapplication9.JButton2[10][10];
/** Creates new form Main */
public Main() {
initComponents();
initComponents2();
//initComponents();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
menuBar = new javax.swing.JMenuBar();
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
pack();
}// </editor-fold>
private void initComponents2() {
for (i=0; i<N; i++)
for (j=0; j<N; j++) {
mas[i][j] = new JButton2("o");
mas[i][j].button.setFont(new java.awt.Font("Tahoma", 1 , (70-(N-3)*200/10)));
mas[i][j].button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
mas[i][j].buttonmouseClick(evt, check); //I'VE TRIED IN MANYWAY BUT I STILL GOT ERROR HERE
/* if (mas[i][j].button.getText()=="") //INCLUDED THIS :((
if (check == true) {
mas[i][j].button.setText("X");
check = false;
else {
mas[i][j].button.setText("O");
check = true;
jPanel1.add(mas[i][j].button);
mas[i][j].button.setBounds(30 + i*(270/N), 40 + j*(270/N), 270/N, 270/N);
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton jButton_exit;
private javax.swing.JMenuBar menuBar;
// End of variables declaration
}Thanks in advance.
Message was edited by:
[email protected]
Message was edited by:
[email protected]
Message was edited by:
[email protected]here is the method:
//add member
public void addMember() {
String output,firstName,secondName,address1,address2,phoneNumberAsString;
long phoneNumber;
boolean isMember=true;
this.memberCounter++;
Player temp;
//create HashMap
HashMap memberList = new HashMap();
output="Squash Court Booking System \n";
output=output+"Enter Details \n\n";
firstName=askUser("Enter First Name: ");
secondName=askUser("Enter Second Name: ");
address1=askUser("Enter Street Name and Number: ");
address2=askUser("Enter Town: ");
phoneNumberAsString=askUser("Enter Phone Number: ");
phoneNumber=Long.parseLong(phoneNumberAsString);
Player p = new Player(firstName,secondName,address1,address2,phoneNumber,isMember);
//place member into HashMap
memberList.put(new Integer(memberCounter),p);
//JOptionPane.showMessageDialog(null,"Membercounter="+memberCounter,"Test",JOptionPane.INFORMATION_MESSAGE);
//create iterator
Iterator members = memberList.values().iterator();
//create output
output="";
while(members.hasNext()) {
temp = (Player)members.next();
output=output + temp.getFirstName() + " ";
output=output + temp.getSecondName() + "\n";
output=output + temp.getAddress1() + "\n";
output=output + temp.getAddress2() + "\n";
output= output + temp.getPhoneNumber() + "\n";
output= output + temp.getIsMember();
//display message
JOptionPane.showMessageDialog(null,output,"Member Listings",JOptionPane.INFORMATION_MESSAGE);
}//end addMemberOn running this, no matter how many details are input, the HashMap only gives me the first one back....
Any ideas?
Sam -
Side-bar: Thought I'd share...
I was looking to get an effect similar to the side bar in Internet explorer, with a close button, and elegant expansion/retraction.
Partly by accident, I hit upon a nice little combination:
JSplitPane, containing the SidePanel on the left.
Make the SideBar panel a GridBagLayout. Use some padding in the layout to set the minimum size.
Add a JMenuBar to the top of the SidePanel
Set the JMenuBar layout to border layout.
Add a JMenu to the WEST part of the JMenuBar, and set the label to the label of the SidePanel. This serves dual function as title and speed menu
Add a JButton("X") to the EAST part of the JMenuBar. Turn off border and focus painting, and set the margins to (2,4,2,4)
Make the split pane one-touch expandable
I thought the end effect was quite pleasing (see screen-shots retracted, expanded, menu extended). A bit more tweaking and this could be made quite elegant. I particularly liked the effect of the GridBagLayout padding - the SplitPane used this information to resist being undersized, which meant that clicking on the retracted edge of the pane instantly resized it to the minimum size, and the pane can't be shrunk too much by dragging the border.
Anyway, I was quite pleased with the effect. Hope it helps someone.Not bad. First, the only thing I would change is using a TableLayout. Gridbag layout is just too complicated for my tastes. TableLayout allows a lot more dynamic control, including adding/removing rows/columsn. In the example you gave, if you set the SplitPane left component to a JPanel that has a TableLayout, you can use a single column multi-row layout, perhaps like so:
double[][] leftLayout =
{TableLayout.MINIMUM},
{20, TableLayout.FILL},
TableLayout tl = new TableLayout(leftLayout);
JPanel leftPanel = new JPanel(tl);
splitPane.setLeftComponent(leftPanel);
Now, when you want to collapse the left pane, listen for the change of the split bar and if it is to be fully collapsed, simply do:
prevDividerLocation = splitPane.getLastDividerLocation();
tl.setColumn(0,0);
and to make it reappear:
tl.setColumn(0,prevDividerLocation);
I am not 100% sure this exact bit of code would do the trick, but I feel it offers a much easier and more flexible layout to more easily add components.
Now, what would really be the shit is if you could get your component to do the Outlook thing, with vertical bars that can slide up or down, each revealing a panel of info. We did something like this before, although I was not the one who did it. I know we used grid bag layout and stuff. I am actually going to be creating a component like this for my own use in the not too distant future.
Regardless, great work! Looks like a pretty kewl component. There are no doubt many ways to implement the same thing, who's to say anyone is better than the other. Just keep on churning out great components and combo-components like this for the rest of the java world to use! -
How do I use different Layouts?
I am trying to make a program that runs in a window like this:
http://www.exyt-web.com/Window.gif
The problem I'm having is with the layout.
How do I have more than one layout ?
For example - as you can see in the image (hyperlink above) I wish to have a border layout with a JFrame at the North position and then in the South position I want to have buttons laid out in a FlowLayout.
Also with my radio buttons I want these in a GridLayout(3, 0) layout.
I made up some example code to test using different layouts - but it seems one layout always overrides the other...
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class LayoutTest extends JFrame
public LayoutTest()
setTitle("Hello World");
Container contents = getContentPane();
Container contents2 = getContentPane();
contents.setLayout(new FlowLayout());
contents.add(new JLabel("<FILTER [Type a th| ]>"));
contents.add(contents2);
contents.add(new JLabel("< Filter Button >"));
contents.add(new JLabel("< Add Button >"));
contents2.setLayout(new GridLayout());
contents2.add(new JLabel("< Button 1 >"));
contents2.add(new JLabel("< Button 2 >"));
contents2.add(new JLabel("< Button 3 >"));
contents2.add(new JLabel("< Button 4 >"));
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
} // HelloWorld
public static void main(String [] args)
LayoutTest theLayoutTest = new LayoutTest();
theLayoutTest.show();
} // main
} // class HelloWorldI know this obviously doesn't work but I hoped it would show what I was trying to do.
I also tried creating a new 'contents2' and then adding it into 'contents'
e.g. contents.add(contents2); My current code for the window I'm trying to create so far is:
import java.awt.*;
import javax.swing.*;
public class Menus extends JFrame
public static void Menus()
// Creates a new JFrame, with the title specified in quotation marks.
JFrame frame = new JFrame("Film Database");
// Sets the default close operation of the frame.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creates a new menu bar for the frame.
JMenuBar menuBar = new JMenuBar();
// Creates a new menu for the menu bar.
JMenu menu = new JMenu("File");
addFrameContents(frame, menuBar, menu);
// Sets the new menu bar on the frame
frame.setJMenuBar(menuBar);
frame.pack();
frame.setVisible(true);
} // HelloWorld
public static void addFrameContents(JFrame frame, JMenuBar menuBar, JMenu menu)
// Adds the menu to the menu bar.
menuBar.add(menu);
// Creates a new item for the menu with a small icon.
JMenuItem menuLoad = new JMenuItem("Load", new ImageIcon("C:/load.gif"));
// Adds the new item to the menu.
menu.add(menuLoad);
JMenuItem menuSave = new JMenuItem("Save", new ImageIcon("C:/save.gif"));
menu.add(menuSave);
JMenuItem menuQuit = new JMenuItem("Quit", new ImageIcon("C:/quit.gif"));
menu.add(menuQuit);
// Creates a new container.
Container contents = frame.getContentPane();
// Sets a new layout for contents, in this case FlowLayout.
contents.setLayout(new GridLayout(2, 0));
// Adds new JLabels to the container.
contents.add(new JLabel("< JLabel 1 >"));
contents.add(new JLabel("< JLabel 2 >"));
contents.add(new JLabel("< JLabel 3 >"));
contents.add(new JLabel("< JLabel 4 >"));
JLabel thisLabel = new JLabel("Hello");
thisLabel.setLayout(new FlowLayout());
JLabel thisLabel2 = new JLabel("Hello2");
thisLabel2.setLayout(new FlowLayout());
contents.add(thisLabel);
contents.add(thisLabel2);
public static void main(String [] args)
Menus();
} // main
} // class HelloWorldAny help on how I can use two separate layouts in the same frame would be great!
Regards,
Tomdoing this:
Container contents = getContentPane();
Container contents2 = getContentPane();
does not create 2 different containers. It's just creating 2 variables that refer to the same container. There is only 1 content pane in a window/frame. A container can only have 1 layout.
If you want to have 2 layouts, you create 2 panels with separate layouts and put what you want in each panel, and put both panels in the content page. -
How to add a JMenubar and a JTable in a JFrame in a single application
Hi all,
I require an urgent help from you.I am a beginer in programming Swing.I want to add a menu,combobox,and a table in a single application.I did coding as below:
package com.BSS;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class newssa extends JFrame
public JMenuBar menuBar;
public JToolBar toolBar;
public JFrame frame;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel jLabel4;
private JLabel jLabel5;
private JLabel jLabel6;
private JComboBox jComboBox1;
private JComboBox jComboBox2;
private JComboBox jComboBox3;
private JComboBox jComboBox4;
private JComboBox jComboBox5;
private JComboBox jComboBox6;
private JTable jTable1;
private JScrollPane jScrollPane1;
private JPanel contentPane;
public newssa()
super();
initializeComponent();
this.setVisible(true);
private void initializeComponent()
jLabel1 = new JLabel();
jLabel2 = new JLabel();
jLabel3 = new JLabel();
jLabel4 = new JLabel();
jLabel5 = new JLabel();
jLabel6 = new JLabel();
jComboBox1 = new JComboBox();
jComboBox2 = new JComboBox();
jComboBox3 = new JComboBox();
jComboBox4 = new JComboBox();
jComboBox5 = new JComboBox();
jComboBox6 = new JComboBox();
frame=new JFrame();
//Included here
JMenuBar menuBar = new JMenuBar();
JMenu general = new JMenu("General");
menuBar.add(general);
JMenu actions =new JMenu("Actions");
menuBar.add(actions);
JMenu view=new JMenu("View");
menuBar.add(view);
JMenu Timescale=new JMenu("TimeScale");
menuBar.add(Timescale);
Timescale.add("Today CTRL+D");
Timescale.add("Current Week CTRL+W");
Timescale.add("Current Month CTRL+M");
Timescale.add("Current Quarter CTRL+Q");
Timescale.add("Current Year CTRL+Y");
Timescale.add("Custom TimeScale CTRL+U");
JMenu start=new JMenu("Start");
menuBar.add(start);
JMenu options=new JMenu("Options");
menuBar.add(options);
JMenu help=new JMenu("Help");
menuBar.add(help);
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setJMenuBar(menuBar);
frame.pack();
frame.setVisible(true);
toolBar = new JToolBar("Formatting");
toolBar.addSeparator();
//Before this included new
String columnNames[] = { "ColorStatus", "Flash", "Service Order","Configuration","Configuration Description"};
// Create some data
String dataValues[][] =
{ "blue", "flash", "ORT001" },
{ "AVCONF", "av configuration with warrenty"}
// Create a new table instance
//jTable1 = new JTable( dataValues, columnNames );
jTable1 = new JTable(dataValues,columnNames);
jScrollPane1 = new JScrollPane(jTable1);
contentPane = (JPanel)this.getContentPane();
//scrollPane = new JScrollPane( table );
//topPanel.add( scrollPane, BorderLayout.CENTER );
// jLabel1
jLabel1.setText("Service Centers");
// jLabel2
jLabel2.setText("Service Areas");
// jLabel4
jLabel3.setText("Skills");
jLabel4.setText("Availablity Types");
// jLabel5
jLabel5.setText("From Date");
// jLabel6
jLabel6.setText("To");
// jComboBox1
jComboBox1.addItem("Coimbatore");
jComboBox1.addItem("Chennai");
jComboBox1.addItem("Mumbai");
jComboBox1.addItem("New Delhi");
jComboBox1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox1_actionPerformed(e);
// jComboBox2
jComboBox2.addItem("North Zone");
jComboBox2.addItem("South Zone");
jComboBox2.addItem("Central Zone");
jComboBox2.addItem("Eastern Zone");
jComboBox2.addItem("Western Zone");
jComboBox2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox2_actionPerformed(e);
// jComboBox3
jComboBox3.addItem("Microsoft Components");
jComboBox3.addItem("Java Technologies");
jComboBox3.addItem("ERP");
jComboBox3.addItem("Others");
jComboBox3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox3_actionPerformed(e);
// jComboBox4
jComboBox4.addItem("One");
jComboBox4.addItem("Two");
jComboBox4.addItem("Three");
jComboBox4.addItem("Four");
jComboBox4.addItem("Five");
jComboBox4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox4_actionPerformed(e);
// jComboBox5
jComboBox5.addItem("12/12/2004");
jComboBox5.addItem("13/12/2004");
jComboBox5.addItem("14/12/2004");
jComboBox5.setEditable(true);
jComboBox5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox5_actionPerformed(e);
// jComboBox6
jComboBox6.addItem("12/11/2004");
jComboBox6.addItem("13/11/2004");
jComboBox6.addItem("14/11/2004");
jComboBox6.setEditable(true);
jComboBox6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox6_actionPerformed(e);
// jTable1
jTable1.setModel(new DefaultTableModel(4, 4));
// jScrollPane1
jScrollPane1.setViewportView(jTable1);
// contentPane
contentPane.setLayout(null);
addComponent(contentPane, jLabel1, 2,29,84,18);
addComponent(contentPane, jLabel2, 201,33,76,18);
addComponent(contentPane, jLabel3, 384,32,59,18);
addComponent(contentPane, jLabel4, 2,77,85,18);
addComponent(contentPane, jLabel5, 197,79,84,18);
addComponent(contentPane, jLabel6, 384,80,60,18);
addComponent(contentPane, jComboBox1, 85,32,100,22);
addComponent(contentPane, jComboBox2, 276,32,100,22);
addComponent(contentPane, jComboBox3, 419,30,100,22);
addComponent(contentPane, jComboBox4, 88,76,100,22);
addComponent(contentPane, jComboBox5, 276,79,100,22);
addComponent(contentPane, jComboBox6, 421,78,100,22);
addComponent(contentPane, jScrollPane1, 33,158,504,170);
// newssa
this.setTitle("SSA Service Scheduler");
this.setLocation(new Point(0, 0));
this.setSize(new Dimension(560, 485));
/** Add Component Without a Layout Manager (Absolute Positioning) */
private void addComponent(Container container,Component c,int x,int y,int width,int height)
c.setBounds(x,y,width,height);
container.add(c);
// TODO: Add any appropriate code in the following Event Handling Methods
private void jComboBox1_actionPerformed(ActionEvent e)
int index = jComboBox1.getSelectedIndex();
switch(index)
case 0: System.out.println("Area Coimbatore Selected "); break;
case 1: System.out.println("Area Chennai selected"); break;
case 2: System.out.println("Mumbai being selected"); break;
case 3: System.out.println("New Delhi being selected"); break;
private void jComboBox2_actionPerformed(ActionEvent e)
int index = jComboBox2.getSelectedIndex();
switch(index)
case 0: System.out.println("North Zone Selcted "); break;
case 1: System.out.println("South Zone being selected"); break;
case 2: System.out.println("Central Zone being selected"); break;
case 3: System.out.println("Eastern Zone being selected"); break;
case 4: System.out.println("Western Zone being selected"); break;
private void jComboBox3_actionPerformed(ActionEvent e)
int index = jComboBox3.getSelectedIndex();
switch(index)
case 0: System.out.println("Microsoft Components being selected"); break;
case 1: System.out.println("Java Technologies being selected"); break;
case 2: System.out.println("ERP Tehnologies being selected"); break;
case 3: System.out.println("Other's selected"); break;
private void jComboBox4_actionPerformed(ActionEvent e)
int index = jComboBox4.getSelectedIndex();
switch(index)
case 0: System.out.println("One selected"); break;
case 1: System.out.println("Two selected"); break;
case 2: System.out.println("Three selected"); break;
case 3: System.out.println("Four selected"); break;
case 4: System.out.println("Five selected"); break;
private void jComboBox5_actionPerformed(ActionEvent e)
int index = jComboBox5.getSelectedIndex();
switch(index)
case 0: System.out.println("12/12/2004 being selected"); break;
case 1: System.out.println("13/12/2004 being selected"); break;
case 2: System.out.println("14/12/2004 being selected"); break;
private void jComboBox6_actionPerformed(ActionEvent e)
int index = jComboBox6.getSelectedIndex();
switch(index)
case 0: System.out.println("12/11/2004 being selected"); break;
case 1: System.out.println("13/11/2004 being selected"); break;
case 2: System.out.println("14/11/2004 being selected"); break;
public static void main(String[] args)
newssa ssa=new newssa();
//JFrame.setDefaultLookAndFeelDecorated(true);
//JDialog.setDefaultLookAndFeelDecorated(true);
//JFrame frame = new JFrame("SSA Service Scheduler");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setJMenuBar(ssa.menuBar);
//frame.getContentPane( ).add(ssa.toolBar, BorderLayout.NORTH);
//frame.getContentPane( ).add(ssa.pane, BorderLayout.CENTER);
//frame.pack( );
//frame.setVisible(true);
try
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
catch (Exception ex)
System.out.println("Failed loading L&F: ");
System.out.println(ex);
But as a O/P ,I am getting menu in a seperate windos and the rest of the combobox and jtable in a seperate window.Kindly help me to solve the application.
VERY URGENT PLEASE..
Thanks in advance
with kind regds
Satheesh.KBut did u mean this as the next problem,Which I will come across..Yes, the second setVisible(true) seemed to be producing a smaller frame behind the main frame.
And your JMenuBar is declared twice, but not sure if this will affect the code - haven't read it all. -
How do I add a JMenuBar to a GridBagLayout
Hi All,
I've got a GridBagLayout on a JFrame and want to add a menu bar to row 0. How do I do that? What I've tried to do is create a JPanel, add the JPanel (menuPanel) to my GridBagLayout in column 0, row 0, width 4 and height of 1. Then add the JMenuBar (bar) to menuPanel. I get the JPanel on the screen because it takes up space, but now File menu.
Please help.
// create JPanel
menuPanel = new JPanel();
constraints.fill = GridBagConstraints.BOTH;
constraints.anchor = GridBagConstraints.NORTHWEST;
constraints.weightx = 0;
constraints.weighty = 0;
addComponent(menuPanel, 0, 0, 4, 1); // object, row, column, width, height
// set up menu bar
fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
newSearch = new JMenuItem("New Search");
newSearch.setMnemonic('N');
fileMenu.add(newSearch);
exit = new JMenuItem("Exit");
exit.setMnemonic('x');
fileMenu.add(exit);
bar = new JMenuBar();
setJMenuBar(bar);
menuPanel.add(bar);Thanks,
KarlYou don't add a MenuBar to the layout, you add directly to the frame using
setJMenuBar(myMenuBar);HTH,
Radish21 -
Problem in layout, please help in correcting code
Hello Friends,
I am facing a very strange problem. I have 1 DespktopPane, say DT in which I have created two InternalFrames, say IF1 and IF2. Also there are two JPanels, say P1 and P2. P1 contains various controls and IF1s ContentPane is set to P1 and P2 contains nothing. There two MenuItems, say M1 and M2. On M1s click I displayed IF1 and on M2s click I displayed IF2. Before adding IF2 everything is working fine, i.e. all the controls are able to display on IF1 but after adding IF2 allthe controls are transferred from IF1 to IF2 and now IF1 displays as a blank screen and IF2 contains allthe controls which are added in JPanel p2 whereas IF2s ContenPane is set to P2 and no control is added in P2.
For your reference, here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MDILayout extends JFrame implements ActionListener
private static JFrame frame = null;
private static JDesktopPane desktop = null;
private static JInternalFrame intframe = null;
private static JInternalFrame rangeframe = null;
private static JPanel panel = null;
private static Image img = null;
private static JMenuBar menubar = null;
private static JMenu mfile = null;
private static JMenuItem bexit = null;
private static JMenuItem borders = null;
private static JMenuItem boption = null;
JButton bcancel,bquery,bexecute,bupdate,bnext,bprev;
JLabel lheader,lheader1,lheader2,lheader3,lline,lline1,
lodate,lquality,ltype,lparty,lindent,lsize,lmul,lgsm,lquantity,ldest,lorderno;
JTextField todate,tquality,ttype,tparty,tindent,tlength,twidth,tgsm,tquantity,tdest,torderno;
JComboBox cbotype;
Font bigfont,bigfont1;
static String ltext="",ltext1="",ltext2="",ltext3="";
Panel p; Graphics g;
MDILayout()
frame = new JFrame("Deckle Suite (Board)");
desktop = new JDesktopPane();
intframe = new JInternalFrame("Orders",true,true,true,true);
rangeframe = new JInternalFrame("Machine - Deckle Range",true,true,true,true);
frame.setSize(1024,738);
frame.setResizable(false);
intframe.setSize(1000,680);
rangeframe.setSize(500,350);
JPanel p1=(JPanel)getContentPane();
p1.setLayout(null);
JPanel p2=(JPanel)getContentPane();
p2.setLayout(null);
intframe.setContentPane(p1);
rangeframe.setContentPane(p2);
frame.setContentPane(desktop);
desktop.add(intframe);
desktop.add(rangeframe);
intframe.setMaximizable(true);
intframe.setResizable(false);
rangeframe.setMaximizable(true);
rangeframe.setResizable(false);
intframe.setContentPane(p1);
intframe.setDefaultCloseOperation(HIDE_ON_CLOSE);
rangeframe.setContentPane(p2);
rangeframe.setDefaultCloseOperation(HIDE_ON_CLOSE);
menubar = new JMenuBar();
mfile = new JMenu("File");
bexit = new JMenuItem("Exit");
borders = new JMenuItem("Orders");
boption=new JMenuItem("Options");
menubar.add(mfile);
mfile.add(borders);
mfile.add(boption);
mfile.add(bexit);
frame.setJMenuBar(menubar);
ltext="==========";
for(int i=0;i<6;i++)
ltext1=ltext+ltext1;
ltext=ltext1;
ltext2="----------";
for(int j=0;j<6;j++)
ltext3=ltext2+ltext3;
ltext2=ltext3;
bigfont=new Font("Monotype Corsiva",Font.BOLD,35);
bigfont1=new Font("Times New Roman",Font.PLAIN,20);
lheader=new JLabel("Deckle Suite (Board)");
lheader1=new JLabel("Khanna Paper Mill (Pvt.) Ltd.");
lheader2=new JLabel("Fatehgarh Road");
lheader3=new JLabel("Amritsar");
lline=new JLabel(ltext1);
lline1=new JLabel(ltext3);
lodate=new JLabel("Order Date");
lquality=new JLabel("Quality");
ltype=new JLabel("Sheet/Reel");
lparty=new JLabel("Party");
lindent=new JLabel("Indent No.");
lsize=new JLabel("Size");
lmul=new JLabel("x");
lgsm=new JLabel("GSM");
lquantity=new JLabel("Quantity");
ldest=new JLabel("Destination");
lorderno=new JLabel("Line No.");
todate=new JTextField(50);
tquality=new JTextField(50);
ttype=new JTextField(20);
cbotype=new JComboBox();
tparty=new JTextField(200);
tindent=new JTextField(50);
tlength=new JTextField(35);
twidth=new JTextField(35);
tgsm=new JTextField(20);
tquantity=new JTextField(35);
tdest=new JTextField(200);
torderno=new JTextField(200);
lheader.setBounds(350,50,500,50);
lheader1.setBounds(370,100,500,30);
lheader2.setBounds(430,130,200,30);
lheader3.setBounds(460,160,200,30);
lline.setBounds(0,200,3000,30);
lline1.setBounds(0,350,3000,30);
lorderno.setBounds(40,240,100,20);
lodate.setBounds(40,270,100,20);
lquality.setBounds(320,270,100,20);
ltype.setBounds(40,400,70,20);
lparty.setBounds(40,300,70,20);
lindent.setBounds(40,430,100,20);
lsize.setBounds(450,430,50,20);
lmul.setBounds(560,430,50,20);
lgsm.setBounds(40,460,50,20);
lquantity.setBounds(320,460,50,20);
ldest.setBounds(40,490,100,20);
torderno.setBounds(120,240,100,20);
todate.setBounds(120,270,100,20);
tquality.setBounds(380,270,200,20);
cbotype.setBounds(120,400,90,20);
tparty.setBounds(120,300,700,20);
tindent.setBounds(120,430,200,20);
tlength.setBounds(490,430,60,20);
twidth.setBounds(580,430,60,20);
tgsm.setBounds(120,460,80,20);
tquantity.setBounds(380,460,80,20);
tdest.setBounds(120,490,500,20);
cbotype.addItem("SHEET");
cbotype.addItem("REEL");
p1.add(lheader);
p1.add(lheader1);
p1.add(lheader2);
p1.add(lheader3);
p1.add(lline);
p1.add(lline1);
p1.add(lodate);
p1.add(todate);
p1.add(lquality);
p1.add(tquality);
p1.add(lparty);
p1.add(tparty);
p1.add(ltype);
p1.add(cbotype);
p1.add(lindent);
p1.add(tindent);
p1.add(lsize);
p1.add(tlength);
p1.add(lmul);
p1.add(twidth);
p1.add(lgsm);
p1.add(tgsm);
p1.add(lquantity);
p1.add(tquantity);
p1.add(ldest);
p1.add(tdest);
p1.add(lorderno);
p1.add(torderno);
lheader.setFont(bigfont);
lheader1.setFont(bigfont1);
lheader2.setFont(bigfont1);
lheader3.setFont(bigfont1);
lheader.setForeground(Color.blue);
lheader1.setForeground(Color.gray);
lheader2.setForeground(Color.gray);
lheader3.setForeground(Color.gray);
bcancel=new JButton("Refresh");
bquery=new JButton("Query");
bexecute=new JButton("Execute");
bupdate=new JButton("Update");
bnext=new JButton("Next");
bprev=new JButton("Previous");
bcancel.addActionListener(this);
bquery.addActionListener(this);
bexecute.addActionListener(this);
bupdate.addActionListener(this);
bnext.addActionListener(this);
bprev.addActionListener(this);
borders.addActionListener(this);
boption.addActionListener(this);;
bexit.addActionListener(this);
bcancel.setBounds(250,550,200,25);
p1.add(bcancel);
bquery.setBounds(450,550,200,25);
p1.add(bquery);
bexecute.setBounds(650,550,200,25);
p1.add(bexecute);
bupdate.setBounds(250,575,200,25);
p1.add(bupdate);
bprev.setBounds(450,575,200,25);
p1.add(bprev);
bnext.setBounds(650,575,200,25);
p1.add(bnext);
torderno.setEnabled(false);
todate.setEnabled(false);
bcancel.setEnabled(true);
bexecute.setEnabled(false);
bquery.setEnabled(false);
bprev.setEnabled(false);
bnext.setEnabled(false);
bupdate.setEnabled(false);
frame.show();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
public static void main(String args[])
MDILayout layout=new MDILayout();
public void actionPerformed(ActionEvent ae)
if (ae.getSource()==borders)
intframe.show();
intframe.repaint();
if (ae.getSource()==boption)
rangeframe.show();
rangeframe.repaint();
}Please provide me the solution so that P1 appears in IF1 and P2 appears in P2.
Thanks in advance,
Ankurall the controls are able to display on IF1 but after adding IF2 allthe controls are transferred from IF1 to IF2 and now IF1 displays as a blank screen
You can't have components at more than one place in the hierarchy. If you add a component to something it is removed from its existing parent if there is one.
I'm not sure how much that helps you - I took one look at your code and ran away screaming. -
Vertical JMenuBar width problem
When I flip my JMenuBar vertical instead of horizontal by doing
BoxLayout bl = new BoxLayout(this,BoxLayout.PAGE_AXIS);
setLayout(bl);
in a constructor for a class that extends JMenuBar. When I do that only 3 characters of each JMenu in the menubar are show. The button size is also ruffly half the width of the actual window. I am doing pack() on the JFrame that houses the JMenuBar. At the moment nothing else is in the JFrame. If I do not set the layout of my JMenuBar then I get a regular horizontal one and width is fine. It's only when I want the Menus vertical instead of horizontal. Been experimenting with all kinds of stuff and no go so far. Looking for suggestions?this produces a menubar, with the screen items vertical, but it takes up too much real estate
import java.awt.*;
import javax.swing.*;
class Testing extends JFrame
public Testing()
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocation(400,200);
JMenu file = new JMenu("File");
JMenuItem newItem = new JMenuItem("New");
JMenuItem open = new JMenuItem("Open");
JMenuItem preview = new JMenuItem("Preview");
JMenuItem print = new JMenuItem("Print");
JMenuItem exit = new JMenuItem("Exit");
file.add(newItem);
file.add(open);
file.add(new JSeparator());
file.add(preview);
file.add(print);
file.add(new JSeparator());
file.add(exit);
JMenu options = new JMenu("Options");
JMenuItem font = new JMenuItem("Font");
JMenuItem color = new JMenuItem("Color");
options.add(font);
options.add(color);
JMenuBar menuBar = new JMenuBar();
menuBar.setLayout(new GridLayout(0,1));
menuBar.add(file);
menuBar.add(options);
setJMenuBar(menuBar);
getContentPane().add(new JTextArea(5,20));
pack();
public static void main(String[] args){new Testing().setVisible(true);}
} -
Hello, I am creating a gui with various swing objects. I put a grouping of various objects within some panels as to allow for simpler layout. The problem however is spaning a jpanel over 2 rows.
basically i want one panel on the left that spans 2 rows, and two panels that span one row each but are placed horizontally to the first panel. followed by 3 panels places horizontally on a 3rd row. when i try to set gridheigh=2 i get weirdness
package javaiq3;
/** Iq3GUI.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Iq3GUI extends JFrame implements ActionListener{
/* main window essential objects */
protected JFrame frame; // main window
private JPanel panel; // content panel for main window
private GridBagLayout gridbag = new GridBagLayout(); // layout object for main window
* constructor
* @param title Main window title
public Iq3GUI(String title){
//initializes the main window, its layout and panels
frame = new JFrame(title); // initializes main window
frame.addWindowListener(new WindowAdapter() { // window listener
// exits program when window is closed
public void windowClosing(WindowEvent e) {System.exit(0);}
GridBagConstraints c = new GridBagConstraints(); // constraints
GridBagConstraints subc = new GridBagConstraints(); // constraints
panel = new JPanel();
panel.setLayout(gridbag);
setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
/**** menu bar ****/
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menu.getAccessibleContext().setAccessibleDescription("File menu");
menuBar.add(menu);
/**** end: menu bar ****/
/**** type radio buttons ****/
JRadioButton[] typeRButton = new JRadioButton[2];
typeRButton[0]=new JRadioButton("Life");
typeRButton[1]=new JRadioButton("Crit");
JPanel typeRButtonPanel = new JPanel(); // panel for radio buttons
typeRButtonPanel.setLayout(new BorderLayout());
typeRButtonPanel.setBorder(BorderFactory.createTitledBorder("Type:")); // sets border
ButtonGroup typeGroup = new ButtonGroup(); // radio button group
for(int x=0;x<typeRButton.length;x++){ // groups radio buttons together
typeGroup.add(typeRButton[x]);
typeRButtonPanel.add(typeRButton[0],BorderLayout.CENTER); // adds them to panel
typeRButtonPanel.add(typeRButton[1],BorderLayout.SOUTH);
c.insets = new Insets(15,15,0,0);
c.gridx=0; c.gridy=0; c.ipady=0; c.gridwidth=1; gridbag.setConstraints(typeRButtonPanel, c);
panel.add(typeRButtonPanel); // adds radio button panel to main panel
/**** end: type radio buttons ****/
/**** company combo box ****/
JComboBox companyComboBox = new JComboBox();
JPanel companyComboBoxPanel = new JPanel();
companyComboBox.setPreferredSize(new Dimension(300,18));
companyComboBoxPanel.setLayout(gridbag);
subc.insets = new Insets(-2,5,2,5); gridbag.setConstraints(companyComboBox, subc);
companyComboBoxPanel.setBorder(BorderFactory.createTitledBorder("Company:"));
companyComboBoxPanel.add(companyComboBox);
c.insets = new Insets(0,0,0,0);
c.gridx=1; c.gridy=0; c.ipadx=0; gridbag.setConstraints(companyComboBoxPanel, c);
panel.add(companyComboBoxPanel);
/**** end: company combo box ****/
/**** product combo box ****/
JComboBox productComboBox = new JComboBox();
JPanel productComboBoxPanel = new JPanel();
productComboBox.setPreferredSize(new Dimension(300,18));
productComboBoxPanel.setLayout(gridbag);
subc.insets = new Insets(-2,5,2,5); gridbag.setConstraints(productComboBox, subc);
productComboBoxPanel.setBorder(BorderFactory.createTitledBorder("Product:"));
productComboBoxPanel.add(productComboBox);
c.insets = new Insets(0,0,0,0);
c.gridx=1; c.gridy=2; c.ipady=0; gridbag.setConstraints(productComboBoxPanel, c);
panel.add(productComboBoxPanel);
/**** end: product combo box ****/
/**** type sex radio buttons ****/
JRadioButton[] sexRButton = new JRadioButton[2];
sexRButton[0]=new JRadioButton("Male");
sexRButton[1]=new JRadioButton("Female");
JPanel sexRButtonPanel = new JPanel(); // panel for radio buttons
sexRButtonPanel.setLayout(new BorderLayout());
sexRButtonPanel.setBorder(BorderFactory.createTitledBorder("Sex:")); // sets border
ButtonGroup sexGroup = new ButtonGroup(); // radio button group
for(int x=0;x<sexRButton.length;x++){ // groups radio buttons together
sexGroup.add(sexRButton[x]);
sexRButtonPanel.add(sexRButton[0],BorderLayout.CENTER); // adds them to panel
sexRButtonPanel.add(sexRButton[1],BorderLayout.SOUTH);
c.gridx=0; c.gridy=3; c.ipady=0; gridbag.setConstraints(sexRButtonPanel, c);
panel.add(sexRButtonPanel); // adds radio button panel to main panel
/**** end: sex radio buttons ****/
/**** smoker check box/combo box ****/
JCheckBox smokerRButton = new JCheckBox("No");
JComboBox smokerComboBox = new JComboBox();
smokerComboBox.setPreferredSize(new Dimension(100,18));
JPanel smokerPanel = new JPanel();
smokerPanel.setLayout(new BorderLayout());
smokerPanel.setBorder(BorderFactory.createTitledBorder("Smoker:"));
smokerPanel.add(smokerRButton,BorderLayout.CENTER);
smokerPanel.add(smokerComboBox,BorderLayout.SOUTH);
c.gridx=1; c.gridy=3; c.ipady=0; gridbag.setConstraints(smokerPanel, c);
panel.add(smokerPanel);
/**** end: smoker check box/combo box ****/
/**** waiver radio buttons ****/
JRadioButton[] waiverRButton = new JRadioButton[2];
waiverRButton[0]=new JRadioButton("Yes");
waiverRButton[1]=new JRadioButton("No");
JPanel waiverRButtonPanel = new JPanel(); // panel for radio buttons
waiverRButtonPanel.setLayout(new BorderLayout());
waiverRButtonPanel.setBorder(BorderFactory.createTitledBorder("Waiver:")); // sets border
ButtonGroup waiverGroup = new ButtonGroup(); // radio button group
for(int x=0;x<waiverRButton.length;x++){ // groups radio buttons together
waiverGroup.add(waiverRButton[x]);
waiverRButtonPanel.add(waiverRButton[0],BorderLayout.CENTER); // adds them to panel
waiverRButtonPanel.add(waiverRButton[1],BorderLayout.SOUTH);
c.gridx=2; c.gridy=3; c.ipady=0; gridbag.setConstraints(waiverRButtonPanel, c);
panel.add(waiverRButtonPanel); // adds radio button panel to main panel
/**** end: type radio buttons ****/
/**** main gui properties ****/
// Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); //screen dimensions
// Rectangle frameDim = frame.getBounds(); // frame boundries
// frame.setLocation((screenDim.width - frameDim.width) / 4,(screenDim.height - frameDim.height) / 4);//sets frame's location to center screen
// frame.setSize(600,100);
frame.setContentPane(panel); frame.pack();
frame.setVisible(true);
/**** end: main gui properties ****/
* setLookAndFeel
* Sets the look and feel of the application, if it cannot be set to the
* user defined one, sets the default java
* @param feel Stores the look and feel string
public void setLookAndFeel(String feel){
try { // sets the GUI style to the parameter type
UIManager.setLookAndFeel(feel);
} catch (Exception e) {
try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
catch (Exception e2){ // if default java one cannot be set, exits program
System.err.println(e2.getMessage());
System.exit(0);
* errorBox
* Displays a JDialog box with an ok button, programmer defined message
* and a warning icon
* @param message Programmer defined message
public void errorBox(String message){
JOptionPane.showMessageDialog(frame,message,"Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
* actionPerformed
* Performs action sent to by action listener
* @param e Action object
public void actionPerformed(ActionEvent e){
System.out.println("Click");
* Main
* Test method
* @param args Does nothing
public static void main(String[] args){
Iq3GUI heh = new Iq3GUI("IQ3");
}Wow. That's some ugly code. You might want to work on coding conventions a bit.
The reason books provide information in paragraphs is to give the eye a rest and the brain time to process the information (a brain is only 8 MHz -- no kidding). Your code should do the same. If 80% of effort goes into maintaining code, you'll help yourself (and potential coworkers) by coding neatly so that things are easy to understand at a glance without dealing with a lot of visual clutter.
1) Try to put comments on their own lines instead of whacking them onto the end of a line of code.
2) Include spaces between code segments that are related tasks -- think of them as "virtual blocks" (since they're not enclosed in braces). Think about the paragraph analogy again. A paragraph groups related sentences. Let your code do the same.
3) Never, ever jam multiple statements into a single line of code. It's a huge pain in the ass to read. While the compiler doesn't care about whitespace, human beings do.
4) When working with GridBagLayout, add all your components in the same part of your class file. By doing so, when you need to alter the layout, you don't have to dig through all of your code to find bits and pieces of the layout. Your project is small, but if you do this stuff for a living, you're eventually going to work on gigantic projects. My current project, for example, consists of 20,000 lines of code just for the GUI (and my project isn't even all at big).
5) Exiting a program without telling the user is laaaaame. I know you're just playing around, but now's the time to get good habits.
OK, so now that you've sat through the editorial, the quick and dirty answer is that you have to explicitly specify widths and heights in your constrains for each component, otherwise GridBagLayout's behavior becomes hard to predict.
In your code, you specify gridwidth once and never again. You know that a Constraint object is reusable, right? What you've just told GridBagLayout is "try to make everything the same width." Meanwhile, the layout is trying to respect your preferred sizes.
Please read the Java Tutorial on GridBagLayout, particularly the suggestion to sketch your layout on a piece of paper ahead of time so that you remember which constraint attributes to change. For safe measure, you might want to specify an entire set of constraints each time you lay out a component so that you won't leave out something important.
As for the background color, I just fixed it by setting a background for your main panel. Windows look and feel is lame, I guess. I always use the Java look and feel, so I haven't run into your problem before.
See my modified code below.
//package javaiq3;
/** Iq3GUI.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Iq3GUI extends JFrame implements ActionListener
protected JFrame frame;
private JPanel panel;
private GridBagLayout gridbag = new GridBagLayout();
public Iq3GUI(String title)
frame = new JFrame(title);
frame.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
GridBagConstraints c = new GridBagConstraints();
GridBagConstraints subc = new GridBagConstraints();
panel = new JPanel();
panel.setLayout(gridbag);
panel.setBackground(Color.lightGray);
setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menu.getAccessibleContext().setAccessibleDescription("File menu");
menuBar.add(menu);
JRadioButton[] typeRButton = new JRadioButton[2];
typeRButton[0]=new JRadioButton("Life");
typeRButton[1]=new JRadioButton("Crit");
JPanel typeRButtonPanel = new JPanel();
typeRButtonPanel.setLayout(new BorderLayout());
typeRButtonPanel.setBorder(BorderFactory.createTitledBorder("Type:"));
ButtonGroup typeGroup = new ButtonGroup();
for(int x=0;x<typeRButton.length;x++)
typeGroup.add(typeRButton[x]);
typeRButtonPanel.add(typeRButton[0],BorderLayout.CENTER);
typeRButtonPanel.add(typeRButton[1],BorderLayout.SOUTH);
c.insets = new Insets(15,15,0,0);
c.gridx=0;
c.gridy=0;
c.ipady=0;
c.gridwidth=1;
gridbag.setConstraints(typeRButtonPanel,c);
panel.add(typeRButtonPanel);
JComboBox companyComboBox = new JComboBox();
JPanel companyComboBoxPanel = new JPanel();
companyComboBox.setPreferredSize(new Dimension(300,18));
companyComboBoxPanel.setLayout(gridbag);
subc.insets = new Insets(-2,5,2,5);
gridbag.setConstraints(companyComboBox, subc);
companyComboBoxPanel.setBorder(BorderFactory.createTitledBorder("Company:"));
companyComboBoxPanel.add(companyComboBox);
c.insets = new Insets(0,0,0,0);
c.gridx=1;
c.gridy=0;
c.ipadx=0;
gridbag.setConstraints(companyComboBoxPanel, c);
panel.add(companyComboBoxPanel);
JComboBox productComboBox = new JComboBox();
JPanel productComboBoxPanel = new JPanel();
productComboBox.setPreferredSize(new Dimension(300,18));
productComboBoxPanel.setLayout(gridbag);
subc.insets = new Insets(-2,5,2,5);
gridbag.setConstraints(productComboBox, subc);
productComboBoxPanel.setBorder(BorderFactory.createTitledBorder("Product:"));
productComboBoxPanel.add(productComboBox);
c.insets = new Insets(0,0,0,0);
c.gridx=1; c.gridy=2; c.ipady=0;
gridbag.setConstraints(productComboBoxPanel, c);
panel.add(productComboBoxPanel);
JRadioButton[] sexRButton = new JRadioButton[2];
sexRButton[0]=new JRadioButton("Male");
sexRButton[1]=new JRadioButton("Female");
JPanel sexRButtonPanel = new JPanel();
sexRButtonPanel.setLayout(new BorderLayout());
sexRButtonPanel.setBorder(BorderFactory.createTitledBorder("Sex:"));
ButtonGroup sexGroup = new ButtonGroup();
for(int x=0;x<sexRButton.length;x++)
sexGroup.add(sexRButton[x]);
sexRButtonPanel.add(sexRButton[0],BorderLayout.CENTER);
sexRButtonPanel.add(sexRButton[1],BorderLayout.SOUTH);
c.gridx=0;
c.gridy=3;
c.ipady=0;
gridbag.setConstraints(sexRButtonPanel,c);
panel.add(sexRButtonPanel);
JCheckBox smokerRButton = new JCheckBox("No");
JComboBox smokerComboBox = new JComboBox();
smokerComboBox.setPreferredSize(new Dimension(100,18));
JPanel smokerPanel = new JPanel();
smokerPanel.setLayout(new BorderLayout());
smokerPanel.setBorder(BorderFactory.createTitledBorder("Smoker:"));
smokerPanel.add(smokerRButton,BorderLayout.CENTER);
smokerPanel.add(smokerComboBox,BorderLayout.SOUTH);
c.gridx=1;
c.gridy=3;
c.ipady=0;
gridbag.setConstraints(smokerPanel,c);
panel.add(smokerPanel);
JRadioButton[] waiverRButton = new JRadioButton[2];
waiverRButton[0]=new JRadioButton("Yes");
waiverRButton[1]=new JRadioButton("No");
JPanel waiverRButtonPanel = new JPanel();
waiverRButtonPanel.setLayout(new BorderLayout());
waiverRButtonPanel.setBorder(BorderFactory.createTitledBorder("Waiver:"));
ButtonGroup waiverGroup = new ButtonGroup();
for(int x=0;x<waiverRButton.length;x++)
waiverGroup.add(waiverRButton[x]);
waiverRButtonPanel.add(waiverRButton[0],BorderLayout.CENTER);
waiverRButtonPanel.add(waiverRButton[1],BorderLayout.SOUTH);
c.gridx=2;
c.gridy=3;
c.ipady=0;
gridbag.setConstraints(waiverRButtonPanel,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 2;
//c.weightx = 100;
//c.weighty = 100;
c.insets = new Insets(0,0,0,0);
panel.add(typeRButtonPanel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 1;
//c.weightx = 100;
//c.weighty = 100;
c.insets = new Insets(0,0,0,0);
panel.add(companyComboBoxPanel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 2;
c.gridheight = 1;
//c.weightx = 100;
//c.weighty = 100;
c.insets = new Insets(0,0,0,0);
panel.add(productComboBoxPanel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 2;
//c.weightx = 100;
//c.weighty = 100;
c.insets = new Insets(0,0,0,0);
panel.add(sexRButtonPanel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 2;
//c.weightx = 100;
//c.weighty = 100;
c.insets = new Insets(0,0,0,0);
panel.add(smokerPanel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 2;
//c.weightx = 100;
//c.weighty = 100;
c.insets = new Insets(0,0,0,0);
panel.add(waiverRButtonPanel, c);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
public void setLookAndFeel(String feel)
try
UIManager.setLookAndFeel(feel);
catch(Exception e)
try
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
catch(Exception e2)
System.err.println(e2.getMessage());
System.exit(0);
public void errorBox(String message)
JOptionPane.showMessageDialog(frame,message,"Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
public void actionPerformed(ActionEvent e)
System.out.println("Click");
public static void main(String[] args)
Iq3GUI heh = new Iq3GUI("IQ3");
} -
Hi,
I have a class that extends JFrame, this has a JMenuBar set to it (set with setJMenuBar method of JFrame) and is displayed fine until i try to add a java.awt.Canvas object to the center of the JFrame(using a BorderLayout) . When this canvas has been added then you can still click on the JMenu names in the JMenuBar but the JMenu itself is no hidden behind the canvas. Here is some of the code
Class that extends JFrame's constructor
//call the super constructor
super("My Image Viewer");
//get the content pane
c = getContentPane();
//set the layout of the frame
c.setLayout(new BorderLayout());
//create a new MenuHandler
menuHandler = new MenuHandler();
//create a new JFileChooser
fileChooser = new JFileChooser("C:/Documents and Settings/"
+ "Irene Stephanie/My Documents");
//create a new file filter
filter = new ImgFilter();
//assign the file filter
fileChooser.setFileFilter(filter);
//create a new window canvas
canvas = new WindowCanvas();
add("Center", canvas);
//set up the menus
initMenu();
//set the JMenuBar
setJMenuBar(menuBar);
//Set the window size
setSize(640, 480);
//make the window visible
setVisible(true);Class that extends Canvas
public class WindowCanvas extends Canvas{
public WindowCanvas(){
super();
public void paint(Graphics g){
}Please not that it works if you add the JMenuBar to the South position, and that you can draw in the canvas, but you cannot see the JMenu's.
Any help will be greatly apreciated
AndyA Canvas is a heavyweight component. By default, Swing menus are lightweight components. You need to call
JPopupMenu.setDefaultLightWeightPopupEnabled(false);before creating your menus. -
Newbie help: Layout Managers
Hi,
as a newbie in Swing I have difficulties with the Layout Managers... I have read the Swing tutorial but it's still a little bit complicated:
I have a JPanel, I would like to add a JMenuBar, a JToolbar and then 2 additional JPanels at the top and on the left representing rulers like in the "How a Scroll Pane Works" example at
http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html as well as a JTable on the right.
How can I do this... BorderLayout containing my main JPanel at CENTER and the two JPanels representing the rulers at PAGE_START and LINE_START and the JTable at LINE_END? Where can I place then my menu- and toolbar? Can I add a BoxLayout to PAGE_START for that?
In a posting here at the forum I read that the MenuBar should be added to the root Pane. How do I do this? When do I use Content Pane, Layered Pane and Glass Pane?
Do you know a simple example or good tutorials at the web?
Thanks a lot!Thank you for the link about the rulers.
The rulers goes inside your custom component. It will be like the example at http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html
Other stuffs layered like this.
package tmp;
import javax.swing.*;
import java.awt.*;
public class LayoutExample extends JFrame
public static void main( String[] args ) throws Exception
SwingUtilities.invokeAndWait( new Runnable()
public void run()
// All the interaction with GUI do inside the MessageLoop thread!
LayoutExample l = new LayoutExample();
l.pack();
l.setVisible( true );
protected JMenuBar mainMenu;
protected JToolBar mainToolBar;
protected RulesFeaturedScrolPane scrollPane;
public LayoutExample() throws HeadlessException
super();
setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
setTitle( "Layout Example" );
// -------------- CREATING NECESSARY CONTROLS ----------------
// Menu
mainMenu = new JMenuBar();
JMenu mnuFile = mainMenu.add( new JMenu( "File" ) );
mnuFile.add( new JMenuItem( "Open" ) );
// ToolBar
mainToolBar = new JToolBar();
mainToolBar.add( new JButton( "Open" ) );
// Customized JScrollPane (with rulers)
scrollPane = new RulesFeaturedScrolPane();
// -------------- END OF CREATING NECESSARY CONTROLS ----------------
// Settig up the components
setJMenuBar( mainMenu ); // Menu added to JFrame not to its ContentPane
getContentPane().setLayout( new BorderLayout() );
getContentPane().add( mainToolBar, BorderLayout.NORTH ); // ToolBar added to the ContentPane
getContentPane().add( scrollPane, BorderLayout.CENTER ); // Other components added to ContentPane
public static class RulesFeaturedScrolPane extends JPanel // <----------- this may extend JScrollPane
public RulesFeaturedScrolPane()
add( new JLabel( "TODO: this class should have rulers" ) );
}Most interesting things starts at getContentPane().setLayout( new BorderLayout() ); -
Hi,
I want to make a graphical user interface with xml.
Is that possible?
For example:
<?xml version="1.0" encoding="UTF-8" ?>
<JMenubar>
<JMenu name="Program">
<JMenuItem name="Connect" method="Connect()" />
</JMenu>
</JMenubar>
I automatically want to create these menu.
But this xml could be more extended, and then the layout must also made automatically.
The problem is, that you don't know how many JMenu's en JMenuItems there are.
Anyone has an idea how to work with this?One way to do this is just to use XMLEncode & XMLDecode, so a nice example for you, to run this, first
java Test -c test.xml
It will ask some questions, fill 'em in.
then
java Test -l test.xml
and it'll create a frame based on the XML file created by step one.
import java.beans.*;
import javax.swing.*;
import java.io.*;
class Test {
public static void main(String argv[] ) throws Throwable{
String file = "default.xml";
JFrame frame;
if( argv.length > 1 && argv[1] != null ) {
file = argv[1];
if( argv[0] != null && argv[0].equals( "-l" ) ) {
XMLDecoder d = new XMLDecoder
( new BufferedInputStream
( new FileInputStream( file ) ) );
frame = ( JFrame ) d.readObject();
frame.pack();
frame.show();
return;
if( argv[0] != null && argv[0].equals( "-c" ) ) {
System.out.println( "Frames Title:" );
BufferedReader in = new BufferedReader
( new InputStreamReader ( System.in ) );
String title = in.readLine();
frame = new JFrame( title );
frame.setDefaultCloseOperation( frame.EXIT_ON_CLOSE );
System.out.println( "utton or [L]abel" );
String bOrl = in.readLine();
System.out.println( "Objects Title: " );
title = in.readLine();
bOrl = bOrl.toUpperCase();
JComponent obj;
if( bOrl.startsWith( "B" ) ) {
obj = new JButton( title );
} else {
obj = new JLabel( title );
frame.getContentPane().add( obj );
System.out.println( "Number Of Menus" );
String noS = in.readLine();
int no = Integer.parseInt( noS );
JMenuBar bobTheMenu = new JMenuBar();
JMenu menu = new JMenu( "File" );
bobTheMenu.add( menu );
frame.setJMenuBar( bobTheMenu );
for(int counter = 0; counter < no; counter++ ) {
System.out.println( "MenuItem " + counter + " title: " );
title = in.readLine();
menu.add( new JMenuItem( title ) );
System.out.println( "Saving" );
XMLEncoder e = new XMLEncoder
( new BufferedOutputStream
( new FileOutputStream( file )));
e.writeObject( frame );
e.close(); -
BorderLayout.NORTH for a Buttonpanel and JMenubar?
Is there a way to make both north?
Thanks.
Here is the relevent code: I tried to make it so that it displays it north then the string read from a file is set to top. But it dosn't display the buttonpanel north.
gameMenu.add(hpset);
gameMenu.add(censor);
menuBar.add(fileMenu);
menuBar.add(modMenu);
menuBar.add(adminCP);
menuBar.add(tools);
adminCP.add(adminCommands);
menuBar.add(gameMenu);
modMenu.add(modCommands);
tools.add(linkTools);
/*Setting censor*/
ButtonGroup censr = new ButtonGroup();
onz = new JRadioButtonMenuItem("On");
onz.setSelected(true);
onz.addActionListener(this);
censr.add(onz);
censor.add(onz);
offz = new JRadioButtonMenuItem("Off");
censr.add(offz);
offz.addActionListener(this);
censor.add(offz);
/*End of setting hp*/
/*Setting hp*/
ButtonGroup hpsel = new ButtonGroup();
hpbar = new JRadioButtonMenuItem("Hitpoints bar");
hpbar.setSelected(true);
hpbar.addActionListener(this);
hpsel.add(hpbar);
hpset.add(hpbar);
numbers = new JRadioButtonMenuItem("Numbers");
hpsel.add(numbers);
numbers.addActionListener(this);
hpset.add(numbers);
/*End of setting hp*/
String place = C();
if(place.startsWith("disable")) {
buttonPanel.setEnabled(false);
System.out.println("Disabling button panel.");
if(place.startsWith("top")) {
frame.getContentPane().add(buttonPanel, BorderLayout.NORTH);
System.out.println("Setting button panel to top.");
} else if(place.startsWith("bottem")) {
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
System.out.println("Setting button panel to bottem.");
if(!place.startsWith("top") && !place.startsWith("bottem") && !place.startsWith("disable")) {
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
System.out.println("No config file found. Setting default bar.");
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
frame.getContentPane().add(gamePanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
init();C() is a method which uses bufferedwriter to read the line to see what setting the person wants.
ThanksI can't read that unformatted code, so I can't help you directly, but I get the feeling that you're trying to put both the Buttonpanel and the JMenubar in the same BorderLayout.NORTH position, and you're finding that only the last one entered will be seen. What you need to do instead is create another JPanel, say northPanel, give it a proper layout, say BoxLayout configured to add components along the y-axis (to add a component just below the previous component), add your Buttonpanel and JMenubar to this northPanel and then add the northPanel to the main panel (the frame's contentPane), BorderLayout.NORTH.
Edited by: Encephalopathic on Jun 18, 2008 2:32 PM -
Need help with GridBagLayout (or layouts in general)
I'm trying to make a layout like this:
|--------------------------------------------------------|-----------|
| | |
| display | |
| | |
| | control |
| | |
| | |
| | |
|--------------------------------------------------------| |
| info | |
|--------------------------------------------------------|-----------|and I can't get it to work.
This is as far as I have gotten (and no, Netbeans can't help me :(, or I don't know how to make it help me)
* MainFrame.java
* Created on February 2, 2008, 1:30 AM
package TowerDefense.Visual;
import TowerDefense.Maps.sampleMap;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
* @author jerome
public class MainFrame extends javax.swing.JFrame implements ActionListener {
private JPanel mainPanel = new JPanel();
private JPanel display = new JPanel();
private JPanel infoPane = new JPanel();
private JPanel controlPane = new JPanel();
private JMenuBar menuBar = new JMenuBar();
private JMenu file = new JMenu("File");
private JMenuItem mnuExit = new JMenuItem("Exit");
private JMenu edit = new JMenu("Edit");
private JMenu miMaps = new JMenu("Maps");
private JMenuItem sampleMap = new JMenuItem("Sample Map");
/** Creates new form MainFrame */
public MainFrame() {
this.setSize(800,600);
* Menu bars
this.setJMenuBar(menuBar);
menuBar.add(file);
file.add(mnuExit);
mnuExit.addActionListener(this);
menuBar.add(edit);
edit.add(miMaps);
miMaps.add(sampleMap);
sampleMap.addActionListener(this);
//construction of layout
this.setLayout(new BorderLayout());
this.add(mainPanel, BorderLayout.CENTER);
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints c =new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridy = 0;
c.weightx = 3;
c.weighty = 2;
mainPanel.add(display, c);
c =new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.fill = java.awt.GridBagConstraints.HORIZONTAL;
c.ipady = 1;
c.anchor = java.awt.GridBagConstraints.EAST;
mainPanel.add(controlPane, c);
c =new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
mainPanel.add(infoPane, c);
//testing display
infoPane.setBackground(Color.YELLOW);
controlPane.setBackground(Color.RED);
display.setBackground(Color.GREEN);
public void actionPerformed(ActionEvent arg0) {
Object o = arg0.getSource();
if(mnuExit.equals(o))
System.exit(1);
}a lot depends on how you want the areas resized when/if the frame is resized
here's one possible approach
import java.awt.*;
import javax.swing.*;
class MainFrame extends javax.swing.JFrame
private JPanel display = new JPanel();
private JPanel infoPane = new JPanel();
private JPanel controlPane = new JPanel();
public MainFrame()
infoPane.setBackground(Color.YELLOW);
controlPane.setBackground(Color.RED);
display.setBackground(Color.GREEN);
JSplitPane spt1= new JSplitPane(JSplitPane.VERTICAL_SPLIT,display,infoPane);
spt1.setResizeWeight(.8);
spt1.setEnabled(false);
spt1.setDividerSize(0);
JSplitPane spt2= new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,spt1,controlPane);
spt2.setResizeWeight(.7);
spt2.setEnabled(false);
spt2.setDividerSize(0);
getContentPane().add(spt2);
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new MainFrame();
} -
Hello,
I am having a problem that has eluded all my attempts to find the problem.
I have a feeling it is one of those simple problems and my weary eyes are
not seeing. Here is my problem.
I have an application that has a JMenuBar that I add like follows in my JFrame
class:
setJMenuBar(menuBar);
Next I have a JToolBar Pane that I create and add like this:
JPanel toolBarPane = new JPanel();
toolBarPane.setLayout(new BorderLayout());
JToolBar toolbar = new JToolBar();
// ADD SOME BUTTONS
toolBarPane.add(toolbar, BorderLayout.NORTH);
getContentPane().add(toolBarPane, BorderLayout.NORTH);
My application also has a status bar at the bottom where I display, for example,
text that changes as the mouse moves over a button or menu item. I also have a
JTabbedPane and JDeskTop in the JFrame as well. Kind of looks like your
typical IDE app.
Finally, here is my problem.
Randomly, when the app first starts up, the MenuBar does not show. I will however
display when I move the mouse over a button on the JToolBar. This happens more
often then not.
Does anyone know what might be happening here?
Much Thanks,
Doug MatulisI noticed in your program you create a toolbar pane with a border layout and add your toolbar to the North location of the toolbar pane. The toolbar pane is then added to the to the North location of your content pane. The toolbar could be added directly to the content pane. Should not be a problem, but it is an observation.
In this section from the Swing tutorial they suggest to create your own content pane from a JPanel
http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html
Using this approach this is how I have built my GUI. My center component is a JTabbedPane (I am not using a JDesktop so that could also be a difference).
setJMenuBar( createMenuBar() );
JPanel contentPane = new JPanel( new BorderLayout() );
setContentPane( contentPane );
contentPane.add( createToolBar(), BorderLayout.NORTH );
contentPane.add( createTabbedPanel(), BorderLayout.CENTER );
contentPane.add( createStatusBar(), BorderLayout.SOUTH );
I am using JDK1.3 on Windows 98 and have not experienced the problems you describe.
Maybe you are looking for
-
I need to know how to do a "one time reprieve"
I logged onto my friends account with them on my computer, and accidentally authorized it with my computer. I can't download anything from my account for 90 days. Help me!!! Please someone tell me how to do the "one time reprieve" THANKS!
-
How do I save a video permanently ?
Now that I know how to save a photo permanently : In the continuous series of saving things (save money, save energy, save water, save gasoline--neh...more important : How do I save a video (from YouTube for example ) and keeping full motion ? I down
-
Hello I have lost my serial number for adobe photoshop elements 13. Bought from John Lewis last month. I did have it installed but had to uninstall but cannot find the any of the packaging etc plus did not register. What is the best way of getting it
-
Standalone deployment & the Xalan transformer
Hi, I'm using JDev and deploying/running against to a standalone instance. Everything was fine until I upgraded my XSL transformer to the latest version of Xalan ( from the default Oracle Provided transformer). Now I am getting an error when I deploy
-
Can I Use Chrome Polish On The Back Of My 4g?
So I've had my ipod touch 4g for almost a year now, and it has been in a hard cover almost all the time. From me removing the case mainly I have gotten many noticeable scratches on the flat part of the back. Since its a stainless steel back, can I us