public class MainMenu extends JFrame {
private JPanel panel,file_list_panel;
private JPanel contentPane;
private JMenuBar menuBar;
private JMenu mnNewMenu1,mnNewMenu2,mnNewMenu3;
private JMenuItem mt1,mt2,mt3;
private JPanel right,left ,bottom;
private JSplitPane spver ,sphor;
private JTabbedPane tabbedPane;
private JLabel label;
private JList<String> list_1;
private JScrollPane jscroll_list;
private DefaultListModel listmodel_1 = new DefaultListModel();
public MainMenu() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
int intValue = Integer.parseInt( "EEEEEE",16);
Color aColor = new Color( intValue );
UIManager.put("TabbedPane.background", new Color(230, 216, 174));
UIManager.put("TabbedPane.selected", Color.WHITE);
UIManager.put("TabbedPane.contentAreaColor",aColor );
UIManager.put("TabbedPane.focus", Color.WHITE);
setTitle("Main Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setBounds(100, 100, 848, 680);
//setLocation(10, 10);
setLocationRelativeTo(null); // set jFrame alignment to center
//parent(first) panel
contentPane = new JPanel();
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(2, 2, 2, 2));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
//Main Menu BAR
menuBar = new JMenuBar();
menuBar.setFont(new Font("Tekton Pro Ext", Font.PLAIN, 11));
setJMenuBar(menuBar);
//Menu 1
mnNewMenu1 = new JMenu("New menu");
menuBar.add(mnNewMenu1);
//Menu 1 MenuItem 1
mt1 = new JMenuItem("Browse New Project");
mt1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
BrowseScreen frame = new BrowseScreen();
frame.setVisible(true);
}
});
mnNewMenu1.add(mt1);
//second panel
panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
spver =new JSplitPane(JSplitPane.VERTICAL_SPLIT);
spver.setDividerLocation(500);
spver.setEnabled(false);
bottom=new JPanel();
sphor =new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
sphor.setEnabled(false);
spver.setTopComponent(sphor);
spver.setBottomComponent(bottom);
bottom.setLayout(null);
panel.add(spver);
sphor.setDividerLocation(180);
left =new JPanel();
right =new JPanel();
sphor.setRightComponent(right);
right.setLayout(new GridLayout(0, 1, 0, 0));
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
JPanel tab1 = new JPanel();
tabbedPane.addTab("fffa", tab1);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JPanel tab2 = new JPanel();
tabbedPane.addTab("TAB1", tab2);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
right.add(tabbedPane);
sphor.setLeftComponent(left);
left.setLayout(new BorderLayout(0, 0));
file_list_panel= new JPanel();
file_list_panel.setBackground(Color.BLACK);
file_list_panel.setForeground(Color.WHITE);
label = new JLabel("Java Files of Project");
label.setBackground(Color.BLACK);
label.setForeground(Color.WHITE);
label.setFont(new Font("Garamond", Font.BOLD, 14));
file_list_panel.add(label);
left.add(file_list_panel, BorderLayout.NORTH);
list_1 = new JList<String>(listmodel_1);
jscroll_list = new JScrollPane(list_1);
left.add(jscroll_list, BorderLayout.CENTER);
}
public void setList(Vector<String> files){
listmodel_1.removeAllElements();
list_1.removeAll();
for(int i=0;i<files.size();i++)
listmodel_1. addElement(files.elementAt(i));
list_1.setModel(listmodel_1);
this.invalidate();
this.validate();
this.repaint();
}
}
setList is called from the browse window before it calls setVisible(false);
ie . this methods gets called when the browse window disappears .. it does all the things in method but does not update it in the MainMenu
public void setFileList(){
MainMenu mm= new MainMenu();
mm.setList(java_files);
}
list_1 -JList listmodel_1=DefaultListModel
i've tried to refreshing the frame but does not refresh after adding the new list to the Main Window ...
before JList is updated im browsing the the files in another window then it is set to setVisible(false) then MainMenu gets focused and calls the setList method but its not changing
You're creating a new JList<String> and copying the reference to your instance variable - but you're neither removing the old JList from the frame, nor adding the new one. Just changing the variable won't do that.
Rather than creating a new JList<String>, why don't you just replace the model of the existing one? Remove this line:
list_1=new JList<String>(listmodel_1);
and you may find it just works. (You're already setting the model in the subsequent line...)
Basically, you are creating a new JList and associating your model with it, but this has no effect on the JList that is on the screen
public void setList(Vector<String> files){
// Good...
listmodel_1.removeAllElements();
// Not required, has nothing to do with the items in the list
//list_1.removeAll();
// Good
for(int i=0;i<files.size();i++)
listmodel_1. addElement(files.elementAt(i));
// This here is your problem
//list_1=new JList<String>(listmodel_1);
// Because I have no idea what model list_1 is actually using...
list_1.setModel(listmodel_1);
//list_1.setSelectedIndex(0);
//this.invalidate();
//this.validate();
//this.repaint();
}
Related
I am using JCombobox and just below that there is a panel which contains JTextFields. Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself. I don't know what to do. I am unable to post a pic of the problem here because i am a new user and my reputation is below 10.
public class MainClass {
public static void main(String args[]){
Form form = new Form();
int width = 400;
int height = 400;
form.setSize(width, height);
form.setVisible(true);
form.setTitle("Create Network");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
form.setLocation((screenSize.width-width)/2, (screenSize.height-height)/2);
}
}
This is the form class
public class Form extends JFrame {
private JLabel ipAddress, networkTopo, numNodes;
private JTextField nodes;
private JButton addIp;
private JButton removeIp;
private JButton next, back;
private JPanel jPanel, jPanel1, jPanel2, commonPanel;
private JComboBox<String> dropDown;
private String[] topologies = { "Grid", "Diagnol Grid", "Bus", "Ring",
"Star" };
public Form() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
setResizable(false);
this.getContentPane().setBackground(Color.WHITE);
// add(Box.createRigidArea(new Dimension(0,10)));
GridLayout commonPanelLayout = new GridLayout(0, 2);
commonPanelLayout.setVgap(10);
commonPanel = new JPanel(commonPanelLayout);
commonPanel.setVisible(true);
commonPanel.setAlignmentX(commonPanel.LEFT_ALIGNMENT);
commonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
commonPanel.setBackground(Color.white);
numNodes = new JLabel("Number of Nodes");
commonPanel.add(numNodes);
nodes = new JTextField(20);
commonPanel.add(nodes);
networkTopo = new JLabel("Network Topology");
commonPanel.add(networkTopo);
dropDown = new JComboBox<String>(topologies);
dropDown.setBackground(Color.WHITE);
commonPanel.add(dropDown);
add(commonPanel);
add(Box.createRigidArea(new Dimension(0, 10)));
ipAddress = new JLabel("IP Addresses");
ipAddress.setAlignmentX(ipAddress.LEFT_ALIGNMENT);
ipAddress.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
add(ipAddress);
add(Box.createRigidArea(new Dimension(0, 10)));
jPanel = new JPanel(new FlowLayout());
jPanel.setVisible(true);
jPanel.setAlignmentX(jPanel.LEFT_ALIGNMENT);
jPanel.setBackground(Color.WHITE);
// jPanel1.setAutoscrolls(true);
add(jPanel);
GridLayout layout = new GridLayout(0, 1);
jPanel1 = new JPanel();
layout.setVgap(10);
// jPanel1.setBackground(Color.WHITE);
jPanel1.setVisible(true);
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(jPanel1);
scroll.setAutoscrolls(true);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setPreferredSize(new Dimension(300, 150));
jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width,
Integer.MAX_VALUE));
jPanel.add(scroll);
jPanel2 = new JPanel(new GridLayout(0, 1, 10, 10));
jPanel2.setBackground(Color.WHITE);
jPanel2.setVisible(true);
jPanel.add(jPanel2);
addIp = new JButton("Add");
jPanel2.add(addIp);
removeIp = new JButton("Remove");
jPanel2.add(removeIp);
JPanel savePanel = new JPanel(new FlowLayout());
savePanel.setVisible(true);
savePanel.setAlignmentX(savePanel.LEFT_ALIGNMENT);
savePanel.setBackground(Color.white);
back = new JButton("Back");
back.setAlignmentX(next.LEFT_ALIGNMENT);
back.setEnabled(false);
savePanel.add(back);
next = new JButton("Next");
next.setAlignmentX(next.LEFT_ALIGNMENT);
savePanel.add(next);
add(savePanel);
AddIPEvent addIPEvent = new AddIPEvent();
addIp.addActionListener(addIPEvent);
RemoveIPEvent removeIPEvent = new RemoveIPEvent();
removeIp.addActionListener(removeIPEvent);
}
public class AddIPEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel subPanel = new JPanel(new FlowLayout());
// subPanel.setBackground(Color.WHITE);
subPanel.setVisible(true);
JCheckBox jCheckBox = new JCheckBox();
// jCheckBox.setBackground(Color.WHITE);
subPanel.add(jCheckBox);
JTextField ip = new JTextField(12);
subPanel.add(ip);
JTextField nodesInIp = new JTextField(6);
nodesInIp.setVisible(false);
subPanel.add(nodesInIp);
jPanel1.add(subPanel);
jPanel1.repaint();
jPanel1.revalidate();
}
}
public class RemoveIPEvent implements ActionListener {
public void removeIP(Container container) {
for (Component c : container.getComponents()) {
if (c instanceof JCheckBox) {
if (((JCheckBox) c).isSelected()) {
jPanel1.remove(container);
jPanel.revalidate();
jPanel1.repaint();
}
} else if (c instanceof Container) {
removeIP((Container) c);
}
}
}
public void actionPerformed(ActionEvent e) {
removeIP(jPanel1);
}
}
}
After Clicking on the Add button and then clicking on the JComboBox will make portion of JTextField dissapear. Could someone pls point out the mistake?
Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself.
//jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width, Integer.MAX_VALUE));
Don't set the preferred size of components. The layout manager will determine the preferred size as components are added/removed. Then scrollbars will appear as required.
jPanel1.repaint();
jPanel1.revalidate();
The order should be:
jPanel1.revalidate();
jPanel1.repaint();
The revalidate() first invokes the layout manager before it is repainted.
//form.setSize(width, height);
form.pack();
Again, don't try to set the size. Let the layout managers do their jobs. The pack() will size the frame based on the sizes of the components added to the frame.
I currently have a JFrame to start fullscreen, inside this jframe i have a jpanel, this jpanel includes a vertical scrollpane. Now if i resize my jframe vertically it just kinda removes the bottom part of the jpanel. Is there any way to just shrink the jscrollpane.
im currently using flowlayout for the jframe,
Scrollbar appear automatically when the preferred size of the components added to the scroll pane area greater than the size of the scroll pane.
The FlowLayout will wrap components to a new row, but it always gives the preferred size as the size required to fit the components on a single row, so the preferred height will never change.
To solve this problem you can use the Wrap Layout which simple extend FlowLayout to recalculate the preferred size when wrapping occurs.
The JPanel consists of 3 other panels, a top panel, a scrollpane in the middle and a botpanel. The top and bot panel are just button and checkboxes and stuff
private void initPane() {
createFolderCompPanel();
createBotPanel();
createTopPanel();
createScrollPane();
createTotalPanel();
add(totalPanel);
}
private void createFolderCompPanel() {
//Create folderCompPanel
folderCompPanel = new JPanel();
folderCompPanel.setLayout(new BoxLayout(folderCompPanel, BoxLayout.Y_AXIS));
folderCompPanel.add(Box.createVerticalGlue());
}
private void createTotalPanel() {
//Create TotalPanel
totalPanel = new JPanel();
totalPanel.setLayout(new BoxLayout(totalPanel, BoxLayout.Y_AXIS));
totalPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
totalPanel.add(topPanel);
totalPanel.add(scrollPane);
totalPanel.add(botPanel);
}
private void createScrollPane() {
//Create ScrollPane
scrollPane = new JScrollPane();
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setViewportBorder(BorderFactory.createEtchedBorder());
scrollPane.getVerticalScrollBar().setUnitIncrement(6);
}
private void createBotPanel() {
//Create BotPanel
botPanel = new JPanel();
botPanel.setLayout(new BoxLayout(botPanel, BoxLayout.X_AXIS));
//AddButton
addButton = new JButton("Add");
addButton.setEnabled(false);
addButton.addActionListener(this);
//SaveButton
saveButton = new JButton("Save");
saveButton.setEnabled(false);
saveButton.addActionListener(this);
//CancelButton
cancelButton = new JButton("Cancel");
cancelButton.setEnabled(false);
cancelButton.addActionListener(this);
lblTotalLength = new JLabel("Total Length: " + totalLength);
botPanel.add(Box.createRigidArea(new Dimension(10, 0)));
botPanel.add(addButton);
botPanel.add(Box.createRigidArea(new Dimension(10, 0)));
botPanel.add(lblTotalLength);
botPanel.add(Box.createHorizontalGlue());
botPanel.add(saveButton);
botPanel.add(Box.createRigidArea(new Dimension(10, 0)));
botPanel.add(cancelButton);
botPanel.add(Box.createRigidArea(new Dimension(10, 0)));
}
private void createTopPanel() {
//Create TopPanel
topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
//create deletedisplay button
deleteDisplayButton = new JButton("Delete Display");
deleteDisplayButton.addActionListener(this);
deleteDisplayButton.setEnabled(false);
//create displaybox
displayBox = new JComboBox();
displayBox.addActionListener(this);
displayBox.addItem("<None>");
for (String s : connect.getAllDisplays()) {
displayBox.addItem(s);
}
displayBox.setMaximumSize(displayBox.getPreferredSize());
//create newdisplay button
newDisplayButton = new JButton("New Display");
newDisplayButton.addActionListener(this);
topPanel.add(Box.createRigidArea(new Dimension(10, 0)));
topPanel.add(displayBox);
topPanel.add(Box.createHorizontalGlue());
topPanel.add(newDisplayButton);
topPanel.add(Box.createRigidArea(new Dimension(5, 0)));
topPanel.add(deleteDisplayButton);
topPanel.add(Box.createRigidArea(new Dimension(10, 0)));
}
this is the panel i add to the jframe
public GuiConstructor(){
super(APPLICATION_NAME);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setMinimumSize(new Dimension(630, 600));
setLayout(new FlowLayout(FlowLayout.LEFT));
LoopControlWindow folderSearch = new LoopControlWindow(connect, this);
add(folderSearch);
pack();
setLocationRelativeTo(null);
setResizable(true);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
I have an Interface class that extends JFrame. I am creating 3 JPanels and adding them to a Container (Border Layout) in different areas of the layout.
When I run the application, nothing shows but a blank window and a title. If I resize the application it will then show all the content and work as intended.
I'm not sure what I did differently this time, I've used this method before and it works in previous programs.
Any help is appreciated.
Here is my Interface Class Constructor code: http://pastebin.com/4UyEXsBr
Code:
public class Interface extends JFrame implements ActionListener {
private Container contentPane;
private JPanel buttonPanel, userPanel;
private JButton loginButton, createUserButton, logoutButton, withdrawButton, depositButton, switchToRegisterButton, switchToLoginButton;
private JLabel headerLabel, inputTopJTFLabel, inputPW1JPFLabel, toastLabel, inputPW2JPFLabel;
public JTextField inputTopJTF;
public JPasswordField inputPW1JPF, inputPW2JPF;
JRootPane rootPane;
public Interface(int width, int height, String title) {
//Setting up Interface
setTitle(title);
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100,100);
setVisible(true);
Font header = new Font("TimesRoman", Font.PLAIN, 50);
///////////////////////BUTTON PANEL///////////////////////
//Button Panel
buttonPanel = new JPanel();
//Buttons
//loginButton
loginButton = new JButton("Login");
loginButton.addActionListener(this);
loginButton.setAlignmentX(Component.CENTER_ALIGNMENT);
//switchToRegisterButton
switchToRegisterButton = new JButton("New User?");
switchToRegisterButton.addActionListener(this);
switchToRegisterButton.setAlignmentX(Component.CENTER_ALIGNMENT);
//switchToLoginButton
switchToLoginButton = new JButton("Switch to Login");
switchToLoginButton.addActionListener(this);
switchToLoginButton.setAlignmentX(Component.CENTER_ALIGNMENT);
switchToLoginButton.setVisible(false);
//createUserButton
createUserButton = new JButton("Register");
createUserButton.addActionListener(this);
createUserButton.setAlignmentX(Component.CENTER_ALIGNMENT);
createUserButton.setVisible(false);
//logoutButton
logoutButton = new JButton("Logout");
logoutButton.addActionListener(this);
logoutButton.setAlignmentX(Component.CENTER_ALIGNMENT);
logoutButton.setVisible(false);
//withdrawButton
withdrawButton = new JButton("Withdraw");
withdrawButton.addActionListener(this);
withdrawButton.setAlignmentX(Component.CENTER_ALIGNMENT);
withdrawButton.setVisible(false);
//depositButton
depositButton = new JButton("Deposit");
depositButton.addActionListener(this);
depositButton.setAlignmentX(Component.CENTER_ALIGNMENT);
depositButton.setVisible(false);
//Adding items to buttonPanel
buttonPanel.add(loginButton);
buttonPanel.add(switchToRegisterButton);
buttonPanel.add(switchToLoginButton);
buttonPanel.add(createUserButton);
buttonPanel.add(logoutButton);
buttonPanel.add(withdrawButton);
buttonPanel.add(depositButton);
///////////////BODY PANEL//////////////////////
//Body Panel
userPanel = new JPanel();
userPanel.setLayout(new BoxLayout(userPanel, BoxLayout.PAGE_AXIS));
//JTextFields
//inputTopJTF
Dimension inputTopJTFDimension = new Dimension(100, 20);
inputTopJTF = new JTextField();
inputTopJTF.setMaximumSize(inputTopJTFDimension);
//inputPW1JPF
Dimension inputPW1JPFDimension = new Dimension(100, 20);
inputPW1JPF = new JPasswordField();
inputPW1JPF.setMaximumSize(inputPW1JPFDimension);
//inputPW2JPF
Dimension inputPW2JPFDimension = new Dimension(100, 20);
inputPW2JPF = new JPasswordField();
inputPW2JPF.setMaximumSize(inputPW2JPFDimension);
inputPW2JPF.setVisible(false);
//JLabels
//toastLabel
toastLabel = new JLabel("Please sign in or create new account.");
toastLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//inputTopJTFLabel
inputTopJTFLabel = new JLabel("Username:");
inputTopJTFLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//inputPW1JPFLabel
inputPW1JPFLabel = new JLabel("Password:");
inputPW1JPFLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//inputPW2JPFLabel
inputPW2JPFLabel = new JLabel("Confirm Password:");
inputPW2JPFLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
inputPW2JPFLabel.setVisible(false);
//Adding items to userPanel
userPanel.add(toastLabel);
userPanel.add(inputTopJTFLabel);
userPanel.add(inputTopJTF);
userPanel.add(inputPW1JPFLabel);
userPanel.add(inputPW1JPF);
userPanel.add(inputPW2JPFLabel);
userPanel.add(inputPW2JPF);
///////////////CONTENT PANE/////////////////////
//Content Pane
contentPane = getContentPane();
//JLabels
//headerLabel
headerLabel = new JLabel("Bank", SwingConstants.CENTER);
headerLabel.setFont(header);
//PAGE_START
contentPane.add(headerLabel, BorderLayout.PAGE_START);
//LINE_START
//CENTER
contentPane.add(userPanel, BorderLayout.CENTER);
//LINE_END
//PAGE_END
contentPane.add(buttonPanel, BorderLayout.PAGE_END);
userPanel.setFocusable(true);
userPanel.requestFocus();
//Default Button
rootPane = getRootPane();
rootPane.setDefaultButton(loginButton);
}
call
setVisible(true);
in last line .because component added after line setvisible will not be shown until you call repaint(),revalidate().when you resize ,repaint() method get called and frame will visible correctly .so call setvisible after add all component
after line rootPane.setDefaultButton(loginButton); call setvisible
rootPane.setDefaultButton(loginButton);
setVisible(true);//after add all component to frame call setvisible method
this is full working code
I'm having problem with adding another JPanel to my frame when I'm using combobox.
I want to change the center panel according to the selection in combobox.
I made differehnt panel to all selections but it didn't add to my main panel.
I added the code.
thanks :)
import AllClasses.FlightCompany;
{
public class WorkerDialog extends JFrame {
private JPanel Worker;
private String[] LabelNames = { "Worker Type:", " Worker Name:" };
String [] str = { "Office", "Host",
"Pilot" };
JComboBox<String> ChooseBox = new JComboBox<>(str);
public JPanel MainPanel;
private JPanel [] p= new JPanel[3];
public WorkerDialog(FlightCompany f) {
super("Worker Dialog");
p[0] = new Office_Gui();
p[1] = new Host_Gui();
p[2] = new Pilot_Gui();
Worker = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel LabelName = new JLabel(LabelNames[0]);
JLabel LabelName2 = new JLabel(LabelNames[1]);
JTextField fieldBox = new JTextField();
LabelName.setSize(40, 25);
ChooseBox.setPreferredSize(new Dimension(180, 22));
Worker.add(LabelName);
Worker.add(ChooseBox);
Worker.add(LabelName2);
fieldBox.setPreferredSize(new Dimension(180, 22));
Worker.add(fieldBox);
JPanel AddPanel = new JPanel(new GridLayout(2, 1, 1, 1));
AddPanel.add(new JButton("Add"));
AddPanel.add(new JButton("TakeOff"));
MainPanel = new JPanel(new BorderLayout(3, 3));
AddPanel.setPreferredSize(new Dimension(0, 110));
ChooseBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
//String str = e.getActionCommand();
String jb = (String) ChooseBox.getSelectedItem();
if (jb.equals("Office")){
MainPanel.add(p[0],BorderLayout.CENTER);
System.out.println("Office");}
}
});
MainPanel.add(Worker, BorderLayout.NORTH);
MainPanel.add(AddPanel, BorderLayout.SOUTH);
add(MainPanel);
//pack();
setSize(560, 300);
setAlwaysOnTop(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
What you want to do is use a CardLayout for your mainPanel, that will allow you to easily switch between panels. Then add all your panels to the mainPanel, specifying a name for the panel. That name will go in the combo box. When you want to show a certain panel, just call cardLayout.show(mainPanel, "nameOfPanel")
To learn more about Cardlayout see How to Use CardLayout. You can also see a simple example here
An aside: Use Java naming convention. Variables begin with lower case letters, using camel casing. ie:
ChooseBox → chooseBox
MainPanel → mainPanel
etc.
I am trying to make an GUI in java ,this is my first venture with GUI in java and I am trying to learn
Above is what I trying to create.But I simple can't get to design it in that way ,here is my code:
//Frame:
JFrame frame;
//Menu :
JMenuBar menuBar;
JMenu menu1,menu2;
JMenuItem menuItem;
//Panels:
JPanel topPanel;
JPanel centerPanel;
JPanel bpttomPanel;
String[] vTypeStrings = { "Select vehicle","Car", "Boat", "Truck", };
//Labels:
JLabel typeLabel;
//ComboBoxes:
JComboBox vList;;
//Frame creation
frame= new JFrame("frame1");
frame.setSize(450,250);
frame.setLocation(200,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3,1));
//Create the menu bar.
menuBar = new JMenuBar();
//Create menu bar items
menu1 = new JMenu("File");
menu1.setMnemonic('F');
menuBar.add(menu1);
menu2 = new JMenu("Help");
menu2.setMnemonic('H');
menuBar.add(menu2);
//Adding items to each menu
menuItem = new JMenuItem("Load", 'L');
menu1.add(menuItem);
menuItem = new JMenuItem("Exit", 'X');
menu1.add(menuItem);
//Second menu
menuItem = new JMenuItem("About",'A');
menu2.add(menuItem);
//Adding menu to frame
frame.setJMenuBar(menuBar);
//Top Panel
topPanel = new JPanel(new FlowLayout());
frame.add(topPanel,BorderLayout.NORTH);
JLabel headLabel=new JLabel("Snedden's Ordering system");//Heading label
topPanel.add(headLabel);
headLabel.setFont(new Font("Serif", Font.PLAIN, 24));
headLabel.setForeground(new Color(0xff0000));
//Center Panel
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(2,2,2,2));
vList = new JComboBox(vTypeStrings);
vList.setSelectedIndex(0);
typeLabel=new JLabel("Vehicle Type");
typeLabel.setLabelFor(vList);
centerPanel.add(typeLabel);
centerPanel.add(vList);
frame.add(centerPanel,BorderLayout.CENTER);
frame.setVisible(true);
Here is what I get
THing is I get the label and the field on the same line, don't understand why,please help thanks.
frame.setLayout(new GridLayout(3,1));
This is your first mistake. The cells of a GridLayout are all the same size, while you want the central part to be higher.
frame.add(topPanel,BorderLayout.NORTH);
....
frame.add(centerPanel,BorderLayout.CENTER);
This is the second one, you set frame to have a GridLayout, so you shouldn't use BorderLayout constraints.
The correct thing to do, in my opinion, is to remove the first line, and leave the frame with the default border layout.
As for your issue with the grid, it's due to the fact that you're not filling the grid.
If you insert 4 controls in the grid, or initialize the grid with (1,2), you will get the expected outcome.
This is with centerPanel.setLayout(new GridLayout(1,2));:
And this is with `
centerPanel.add(typeLabel);
centerPanel.add(vList);
centerPanel.add(new JLabel());
centerPanel.add(new JLabel());
What about this:
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
public Gui()
{
super("Gui");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
setVisible(true);
add(new Form(), BorderLayout.EAST);
add(new ButtonRow(), BorderLayout.SOUTH);
}
private class ButtonRow extends JPanel {
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
public ButtonRow()
{
setLayout(new FlowLayout());
button1 = new JButton("button 1");
button2 = new JButton("button 2");
button3 = new JButton("button 3");
button4 = new JButton("button 4");
add(button1);
add(button2);
add(button3);
add(button4);
}
}
public static void main(String args[])
{
new Gui();
}
private class Form extends JPanel {
String[] vTypeStrings = { "Select vehicle","Car", "Boat", "Truck", };
public Form()
{
setLayout(new VerticalLayout());
JComboBox vList = new JComboBox(vTypeStrings);
add(new Control("choose", vList));
add(new Control("label 1"));
add(new Control("label 2"));
add(new Control("label 3"));
add(new Control("label 4"));
}
}
private class Control extends JPanel {
private JLabel label;
private JTextField text;
public Control(String lbl)
{
label = new JLabel(lbl);
text = new JTextField(15);
setLayout(new FlowLayout());
add(label);
add(text);
}
public Control(String lbl, JComboBox list)
{
label = new JLabel(lbl);
setLayout(new FlowLayout());
add(label);
add(list);
}
}
}
I think you get the idea.
NOTE: I've used this VerticalLayout class.
Not good answers I see from others, now this one is good. Just type:
JPanel panel = new JPanel();
panel.setLayout(null);
And set the LOCATIONS and SIZES to the objects on the JPANEL and you can place them anywhere.