Can anyone suggest me how can I divide my JTabbedPane in two equal horizontal sections? My Pane has three tabs in it. I want to divide the second tab pane (tab 2) into two equal halves?
Code for Tabbed Pane
import javax.swing.*;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
public class Monitor{
public static void main(String[] args){
JFrame frame = new JFrame("WELCOME");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tab = new JTabbedPane();
frame.add(tab, BorderLayout.CENTER);
JButton button = new JButton("1");
tab.add("tab1", button);
button = new JButton("2");
tab.add("tab2", button);
button = new JButton("3");
tab.add("tab3", button);
frame.setSize(400,400);
frame.setVisible(true);
}
}
Use a single row GridLayout for the JPanel that is placed in that tab. With two components in it, they will each have half the space. E.G.
import javax.swing.*;
import java.awt.*;
public class Monitor {
public static void main(String[] args){
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("WELCOME");
// A better close operation..
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane tab = new JTabbedPane();
frame.add(tab, BorderLayout.CENTER);
JButton button = new JButton("1");
tab.add("tab1", button);
// this GridLayout will create a single row of components,
// with equal space for each component
JPanel tab2Panel = new JPanel(new GridLayout(1,0));
button = new JButton("2");
tab2Panel.add(button);
tab2Panel.add(new JButton("long name to stretch frame"));
// add the panel containing two buttons to the tab
tab.add("tab2", tab2Panel);
button = new JButton("3");
tab.add("tab3", button);
// a better sizing method..
//frame.setSize(400,400);
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Related
I'm having a problem with a layout I'm trying to do in java. I have 2 panels in a 800x600 frame. The first panel "gamePanel" is (600x600) and the second "menuPanel" is (200x600).
In the menuPanel there are 4 buttons that I tried to organize as a single column of 4 rows using gridLayout(which partially worked). The buttons appear to be in place but when hovering on them they expand occupying the other panel (gamePanel). I tried placing them using setBounds but they directly disappear.
This is how it works before hovering the buttons.
After hovering 2 buttons, but all 4 are displayed the same way
Here is the code:
public class Layout {
Point point = new Point();
public Layout() {
JFrame window = new JFrame();
ImageIcon icon = new ImageIcon("images/icon.jpg");
//JFRAME
window.setSize(800,600);
window.setLocationRelativeTo(null);
window.setTitle("Arkanoid");
window.setUndecorated(true);
window.setIconImage(icon.getImage());
//PANELS
JPanel gamePanel = new JPanel();
gamePanel.setBackground(Color.RED);
gamePanel.setBounds(0, 0, 600, 600);
JPanel menuPanel = new JPanel(new GridLayout(4,1));
menuPanel.setBackground(Color.BLACK);
menuPanel.setBounds(600,0,200,600);
menuPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
window.add(gamePanel);
window.add(menuPanel);
//Buttons
JButton closeButton = new JButton("Close Me");
closeButton.addActionListener(e -> System.exit(0));
menuPanel.add(closeButton);
JButton playButton = new JButton("Play");
menuPanel.add(playButton);
JButton Button1 = new JButton("Test1");
menuPanel.add(Button1);
JButton Button2 = new JButton("Test2");
menuPanel.add(Button2);
//Labels
//SHOW
window.setVisible(true);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
A JFrame has a default BorderLayout, which I used to place the two JPanels.
I added a main method so I could run the GUI. I commented out the icon code, which doesn't make any sense for an undecorated JFrame. I moved the setLocationRelativeTo method to after the pack method, so the JFrame is actually centered.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ExampleLayout {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ExampleLayout();
}
});
}
Point point = new Point();
public ExampleLayout() {
JFrame window = new JFrame();
// ImageIcon icon = new ImageIcon("images/icon.jpg");
// JFRAME
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setTitle("Arkanoid");
window.setUndecorated(true);
// window.setIconImage(icon.getImage());
// PANELS
JPanel gamePanel = new JPanel();
gamePanel.setBackground(Color.RED);
gamePanel.setPreferredSize(new Dimension(600, 600));
JPanel menuPanel = new JPanel(new GridLayout(0, 1));
menuPanel.setBackground(Color.BLACK);
menuPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
menuPanel.setPreferredSize(new Dimension(200, 600));
window.add(gamePanel, BorderLayout.CENTER);
window.add(menuPanel, BorderLayout.EAST);
// Buttons
JButton closeButton = new JButton("Close Me");
closeButton.addActionListener(e -> System.exit(0));
menuPanel.add(closeButton);
JButton playButton = new JButton("Play");
menuPanel.add(playButton);
JButton Button1 = new JButton("Test1");
menuPanel.add(Button1);
JButton Button2 = new JButton("Test2");
menuPanel.add(Button2);
// Labels
// SHOW
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
I am trying to build a GUI that looks something like this:
Main idea is to have buttons on the side and a table displaying results.
Here is the code I have so far:
public class GUI {
private JButton usdJpyButton = new JButton("USD/JPY");
private JButton usdGbpButton = new JButton("USD/GBP");
public void mainScreen(){
JFrame frame = new JFrame("Window");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setSize(900,600);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
GridLayout layout = new GridLayout(0,4);
frame.setLayout(layout);
JPanel sidePanel = new JPanel(new GridBagLayout());
sidePanel.setBackground(Color.black);
GridBagConstraints cons = new GridBagConstraints();
cons.insets = new Insets(50,0,0,0);
cons.gridy = 1;
cons.anchor = GridBagConstraints.NORTH;
sidePanel.add(usdJpyButton);
cons.gridy = 2;
sidePanel.add(usdGbpButton);
frame.add(sidePanel);
frame.setVisible(true);
}
The buttons are not aligned and I am not sure which layout manager I should use for the best results. Also each button will have an action listener to a different table so do I need to create seperate JPanels for each table??
I am not sure which layout manager I should use for the best results.
Rarely do you ever use a single layout manager. Generally you will nest panels each using a different layout manager to achieve your desired effect.
Read the section from the Swing tutorial on Layout Managers for working examples of each layout manager.
In this case you would probably need two panels, one for the buttons and one for the panels to display when you click on the button.
So for the buttons you might create a panel using BorderLayout. Then you create a second panel using a GridLayout. You add your buttons to the panel with the GridLayout. Then you add this panel to the PAGE_START of the BorderLayout. Then you add this panel to the LINE_START of the BorderLayout used by the content pane of the frame.
Then for the panel to display each table you would use a CardLayout. Then you create a separate panel for each currency table and add it to the CardLayout. You would add this panel to the CENTER of the BorderLayout of the content pane.
Then in the ActionListener of your buttons you swap the panel in the CardLayout based on the button that was clicked.
Again, the tutorial link I provided has working examples of the BorderLayout, GridLayout and CardLayout.
I would recommend MigLayout manager.
It is not particularly difficult to do it with this manager.
package com.zetcode;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import net.miginfocom.swing.MigLayout;
public class InstaMetrixEx extends JFrame implements ActionListener {
public InstaMetrixEx() {
initUI();
}
private void initUI() {
JButton btn1 = new JButton("Client Overview");
JButton btn2 = new JButton("Seo Reports");
JButton btn3 = new JButton("Social media reports");
JButton btn4 = new JButton("Campaigns");
JButton btn5 = new JButton("Webmaster tools");
JButton btn6 = new JButton("Dashboard");
JButton btn7 = new JButton("Tasks");
JComboBox combo1 = new JComboBox();
combo1.addItem("Bulk actions");
JButton btn8 = new JButton("Submit");
JTable table = new JTable(20, 7);
JScrollPane spane = new JScrollPane(table);
createLayout(btn1, combo1, btn8, btn2, btn3, btn4,
btn5, btn6, btn7, spane );
setTitle("InstaMetrixEx");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout());
add(arg[0], "sgx");
add(arg[1], "gapx 10lp, split 2");
add(arg[2], "wrap");
add(arg[3], "split 6, aligny top, flowy, sgx");
add(arg[4], "sgx");
add(arg[5], "sgx");
add(arg[6], "sgx");
add(arg[7], "sgx");
add(arg[8], "sgx");
add(arg[9], "gapx 10lp, spanx, wrap, push, grow");
pack();
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, "Button clicked",
"Information", JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
InstaMetrixEx ex = new InstaMetrixEx();
ex.setVisible(true);
});
}
}
Screenshot:
I want to position a JLabel within a JPanel, so that it appears at the top of the window. I then want to position two drop-down menu below that so that the user can choose from two sets of options.
How would I go about positioning these elements?
Here's a JLabel title with two JComboBoxes. I have no idea what else you mean by a "drop-down menu".
I created a JPanel with a BorderLayout to hold the GUI.
The title is a JLabel inside of a JPanel using the default FlowLayout.
The JComboBoxes are inside of a JPanel using the default FlowLayout.
Here's the code:
package com.ggl.testing;
import java.awt.BorderLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DropDownLayout implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new DropDownLayout());
}
#Override
public void run() {
JFrame frame = new JFrame("Drop Down Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(createTitlePanel(), BorderLayout.NORTH);
panel.add(createDropDownPanel(), BorderLayout.CENTER);
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel();
JLabel titleLabel = new JLabel("Title");
panel.add(titleLabel);
return panel;
}
private JPanel createDropDownPanel() {
JPanel panel = new JPanel();
DefaultComboBoxModel<String> model1 = new DefaultComboBoxModel<String>();
model1.addElement("Selection 1");
model1.addElement("Selection 2");
model1.addElement("Selection 3");
model1.addElement("Selection 4");
JComboBox<String> comboBox1 = new JComboBox<String>(model1);
panel.add(comboBox1);
DefaultComboBoxModel<String> model2 = new DefaultComboBoxModel<String>();
model2.addElement("Choice 1");
model2.addElement("Choice 2");
model2.addElement("Choice 3");
model2.addElement("Choice 4");
JComboBox<String> comboBox2 = new JComboBox<String>(model2);
panel.add(comboBox2);
return panel;
}
}
I have written a small program for creating a simple gui with tabbed panes.Currently it has two tabs.
In one of the tabs i have created a button and in another tabs i have created two buttons(based upon a string in a third class).What i am not able to do is inside the second tab i want to created two tabs ("one" and "two" refered in te code) and the two button that are currently in the tab should be present in each of the sub tabs.Can anybody tell me how can i acheive this?
main class:
abc.java
public class abc {
JFrame frame;
JTabbedPane tabPane;
abc_export exp;
bsm_import2 imp;
public static void main(String[] args) {
abc jtab = new abc();
jtab.start();
}
public void start(){
exp=new abc_export();
imp=new bsm_import2();
tabPane.addTab("bsm_export", exp.tab);
tabPane.addTab("bsm_import2", imp.tab);
}
public abc() {
// Create a frame
frame = new JFrame();
// Create the tabbed pane.
tabPane = new JTabbedPane();
//Adding into frame
frame.add(tabPane, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Class two:abc_export.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class abc_export {
JPanel tab;
public abc_export() {
//Adding into frame
tab = new JPanel();
JButton btn=new JButton("run");
tab.add(btn);
tab.setOpaque(false);
}
};
class three: bsm_import2.java(this is where i need the changes to be done to create sub tabs)
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.*;
import java.util.StringTokenizer;
import java.util.*;
import java.awt.event.*;
public class bsm_import2 {
public static JPanel tab;
public bsm_import2()
{
createAndShowGUI();
}
private static void createAndShowGUI() {
tab=new JPanel();
tab.setLayout(new GridLayout(3,2));
String line="tab1#one tab2#two";
String strAry[] = line.split(" ");
JButton Button[]=new JButton[100];
final Map<String, String> map = new HashMap<String, String>();
for(int i =0; i < strAry.length ; i++){
String[] parts = strAry[i].split("#");
map.put(parts[0],parts[1]);
Button[i] = new JButton(parts[0]);
tab.add(Button[i]);
tab.setOpaque(false);
}
for ( String key : map.keySet() ) {
System.out.println( key );
}
}
}
Based on what I understand form your question what you can do is, in the panel of second tab add a new JTabbedPane with 2 tabs having a button in each and you will get what you want. A small demo code will be:
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane mainTabsPane = new JTabbedPane(); // main tabs pane
//first tab
JButton button = new JButton("Button in first tab");
JPanel jPanel = new JPanel();
jPanel.add(button);
mainTabsPane.addTab("First tab", jPanel);
//second tab
jPanel = new JPanel();
JTabbedPane secondaryTabsPane = new JTabbedPane(); // secondary tabs pane
button = new JButton("Button in second tab ---> first sub tab");
JPanel jPanel2 = new JPanel();
jPanel2.add(button);
secondaryTabsPane.addTab("First tab", jPanel2);
JPanel jPanel3 = new JPanel();
button = new JButton("Button in second tab ---> second sub tab");
jPanel3.add(button);
secondaryTabsPane.addTab("Second tab", jPanel3);
// add secondary tabs pane to new panel of second tab
jPanel.add(secondaryTabsPane);
// add new panel to main tabs pane
mainTabsPane.addTab("Second tab", jPanel);
frame.getContentPane().add(mainTabsPane);
frame.setVisible(true);
Other than this you are directly refering to a variable of a class in another class here tabPane.addTab("bsm_export", exp.tab);. You should not do this, instead you should make it private and provide getter/setter to access it. Also why are you having such complicated structure of code for such a small thing, displaying buttons in tabs!!!?? Also always follow Java Coding Convention, class name should not start with small character.
Hi I am trying to create an interface consisting of a JComboBox and a JTextField. I have sorted out the code to add a label to the JComboBox but I am having trouble adding a label to the text field. Any help would be appreciated.
import javax.swing. *;
import java.awt.event. *;
import java.awt.FlowLayout;
import java.lang.Math;
public class AreaFrame3 extends JFrame
{
public static void main(``String[]args)
{
//Create array containing shapes
String[] shapes ={"(no shape selected)","Circle","Equilateral Triangle","Square"};
//Use combobox to create drop down menu
JComboBox comboBox=new JComboBox(shapes);
JPanel panel1 = new JPanel(new FlowLayout()); //set frame layout
JLabel label1 = new JLabel("Select shape:");
panel1.add(label1);
panel1.add(comboBox);
JTextField text = new JTextField(10); //create text field
JFrame frame=new JFrame("Area Calculator Window");//create a JFrame to put combobox
frame.setLayout(new FlowLayout()); //set layout
frame.add(panel1);
frame.add(text);
JButton button = new JButton("GO"); //create GO button
frame.add(button);
//set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set JFrame ssize
frame.setSize(400,250);
//make JFrame visible. So we can see it
frame.setVisible(true);
}
}
Here is one way to do it. Simply put all the widgets in your panel1 in appropriate order.
In the long run this is probably not very much maintainable and you would want to have a better LayoutManager than FlowLayout, but if you just want to learn Swing, this may be a good start. If you feel that FlowLayout is not good enough, take a look at the LayoutManager tutorial. My personal favourites are: BorderLayout and GridBagLayout. MigLayout may also be a good one, but I have never used it and it is not part of the JVM.
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class AreaFrame3 {
protected void initUI() {
// Create array containing shapes
String[] shapes = { "(no shape selected)", "Circle", "Equilateral Triangle", "Square" };
// Use combobox to create drop down menu
JComboBox comboBox = new JComboBox(shapes);
JLabel label1 = new JLabel("Select shape:");
JPanel panel1 = new JPanel(new FlowLayout()); // set frame layout
JLabel label2 = new JLabel("Text label:");
JTextField text = new JTextField(10); // create text field
panel1.add(label1);
panel1.add(comboBox);
panel1.add(label2);
panel1.add(text);
JFrame frame = new JFrame("Area Calculator Window");// create a JFrame to put combobox
frame.setLayout(new FlowLayout()); // set layout
frame.add(panel1);
JButton button = new JButton("GO"); // create GO button
frame.add(button);
// set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
// make JFrame visible. So we can see it
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new AreaFrame3().initUI();
}
});
}
}