A JtabbedPane within a JtabbedPane - java

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.

Related

Adding JPanel from another class in JFrame When Button Clicked

Hi i'm new to Java and kinda lost in the codes i tried to write. It compiles with no error but everything i added on panel don't show up on the frame
Here's my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class Mainframe extends JFrame {
private AddingWindow addingWindow = new AddingWindow(); //Passing AddingWindow Class to the Main Class as statement
private JFrame addingWindowFrame = new JFrame(); //This is the frame i wanted to add the JPanel with its labels and buttons
public Mainframe() {
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1 ,1));
JButton addingBtn = new JButton("Add");
controlPanel.add(addingBtn);
//Add controlPanel to the mainframe
setLayout(new BorderLayout());
add(controlPanel, BorderLayout.WEST);
//Set showAddingPanel button event
addingBtn.addActionListener (new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
addingWindowFrame.setVisible(true);
}
});
addingWindowFrame.pack();
addingWindowFrame.setTitle("Title);
addingWindowFrame.setSize(600, 400);
addingWindowFrame.setResizable(false);
addingWindowFrame.setLocationRelativeTo(null);
addingWindowFrame.getContentPane().add(addingWindow); //Here i'm adding JPanel Class to the Frame
}
//Main method
public static void main(String[] args) {
JFrame mainFrame = new Mainframe();
mainFrame.setTitle("\"Mainframe\"");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
mainFrame.setMinimumSize(new Dimension(800, 600));
}
}
This is the other panel Class file i wanted to show up on the AddingWindowFrame
import java.awt.*;
import javax.swing.*;
public class AddingWindow extends JPanel {
AddingWindow() {
JPanel addingPanel = new JPanel();
addingPanel.setLayout(new GridLayout(2, 2));
JLabel fullNameLbl = new JLabel("Name");
JTextField fullNameTextField = new JTextField(25);
JButton addBtn = new JButton("add");
JButton cancelBtn = new JButton("cancel");
//Adding buttons, label and textfield to addingPanel
addingPanel.add(fullNameLbl);
addingPanel.add(fullNameTextField);
addingPanel.add(addBtn);
addingPanel.add(cancelBtn);
}
}
I think you want to display
What you did is you added all the things to your addingPanel but you forgot to add the addingPanel itself.
import java.awt.*;
import javax.swing.*;
public class AddingWindow extends JPanel {
AddingWindow() {
JPanel addingPanel = new JPanel();
addingPanel.setLayout(new GridLayout(2, 2));
JLabel fullNameLbl = new JLabel("Name");
JTextField fullNameTextField = new JTextField(25);
JButton addBtn = new JButton("add");
JButton cancelBtn = new JButton("cancel");
//Adding buttons, label and textfield to addingPanel
addingPanel.add(fullNameLbl);
addingPanel.add(fullNameTextField);
addingPanel.add(addBtn);
addingPanel.add(cancelBtn);
add(addingPanel);
}
}
You have two frames
MainFrame
AddingWindowFrame -> contains AddingPanel
And when you click on the button you are just displaying the AddingWindowFrame(I guess it should displayed somewhere in the background). Instead you need to add the AddingPanel directly to the currentFrame.
Mainframe.this.getContentPane().add(addingWindow);
But you should check how to use LayoutManagers

Split pane into two halves using Swing

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);
}
}

Java gui Jbutton

I have a program but I can't combine the textfield and the button in the same frame like in top textfield and below that the button:
Here is my source code:
import java.awt.*;
import javax.swing.*;
public class FirstGui extends JFrame
{
JTextField texts;
JButton button;
public FirstGui()
{
texts = new JTextField(15);
add(texts);
button = new JButton("Ok");
add(button);
}
public static void main(String args [])
{
FirstGui gui = new FirstGui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(200,125);
gui.setVisible(true);
}
}
Add a layout like FlowLayout:
public FirstGui()
{
setLayout(new FlowLayout());
texts = new JTextField(15);
add(texts);
button = new JButton("Ok");
add(button);
}
at the very beginning of your constructor, before anything else.
The default layout is BorderLayout for JFrame. When you add components to a BorderLayout, if you don't specify their BorderLayout position, like BorderLayout.SOUTH, the component will automatically be add to BorderLayout.CENTER. Bthe thing is though, each position can only have one component. So when you add texts it gets added to the CENTER. Then when you add button, it gets added to the CENTER but texts gets kicked out. So to fix, you can do
add(texts, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
See Laying out Components Within a Container to learn more about layout managers.
UPDATE
import java.awt.*;
import javax.swing.*;
public class FirstGui extends JFrame {
JTextField texts;
JButton button;
public FirstGui() {
texts = new JTextField(15);
add(texts, BorderLayout.CENTER);
button = new JButton("Ok");
add(button, BorderLayout.SOUTH);
}
public static void main(String args[]) {
FirstGui gui = new FirstGui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setVisible(true);
}
}

how to repaint a jpanel with button click and also switch between 2 panels

I am trying to repaint a panel with a button click, but its not happening. i tried using many methods like setEnabled(true), setVisible(true), repaint(), but none of these are working. And also i want to switch between two panels, like, if i click the "Total Vote" button, one panel should display, when i click on "Departmentwise Vote", another panel should display in the same place.
please help. Thanks in advance.
here i m providing the code :
public class RSummary extends JFrame implements ActionListener
{
JFrame rframe = new JFrame();
JPanel panel1, panel2, panel3, panel4, panel5;
JTable table;
JScrollPane scroll;
JSplitPane splitPane;
JButton butx;
public RSummary()
{
rframe.setSize(550,300);
rframe.setLocationRelativeTo(null);
setSize(550,300);
rframe.setTitle("Summary Report");
/* Total Vote & Department wise vote buttons */
panel1= new JPanel();
JButton but1 = new JButton("TOTAL VOTE");
JButton but2 = new JButton("DEPTARTMENT WISE VOTE");
but1.addActionListener(this);
panel1.add(but1);
panel1.add(but2);
/* Report contents according to button */
panel2 = new JPanel();
String[] columnNames = {"Name", "Department","Phno","LUID","Select"};
DefaultTableModel model1 = new DefaultTableModel();
model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll = new JScrollPane(table);
panel2.add(scroll);
panel2.setVisible(false);
/* close button */
panel3 = new JPanel();
JButton but4= new JButton("CLOSE");
but4.addActionListener(this);
panel3.add(but4);
/* Page heading */
panel4 = new JPanel();
JLabel lab =new JLabel("VOTE SUMMARY REPORT");
panel4.add(lab);
/* dummy panel */
panel5 = new JPanel();
JButton butx = new JButton("Hello butx");
panel5.add(butx);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1, panel2);
rframe.add(splitPane);
rframe.add(panel3,BorderLayout.SOUTH);
rframe.add(panel4,BorderLayout.NORTH);
rframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rframe.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String action=ae.getActionCommand();
if(action == "CLOSE")
{
rframe.setVisible(false);
}
if(action == "TOTAL VOTE")
{
panel2.setVisible(true); //this code is not working, i want the solution here.
}
}
public static void main(String args[]) throws ClassNotFoundException, SQLException
{
new RSummary();
}
}
The first problem is you're comparing the object references of your String values and not there contents...
if(action == "TOTAL VOTE")
Because of the way Strings are managed by Java, it is very unlikely that these will ever be equal.
String comparison in Java is done using String#equals
if ("TOTAL VOTE".equals(action))
Your second problem may be related to the fact the setVisible may not be invalidating the container hierarchy, which would tell the layout framework that the containers need to be updated.
You have two solutions, the first would be to call revalidate on the parent container, the second, and better, would be to use a CardLayout, which is designed to just what you are trying to do...
Take a look at How to use Card Layout for more details
Update after running the Code
You have a series of compounding issues...
You never set the action command of any of the buttons, so when the actionPerformed event is raised, the action is actually null
RSummary extends from JFrame, yet you create a second JFrame called rframe. This is very confusing and could potentially lead to more problems if you're not dealing with the correct frame.
Start by setting the actionCommand property of your buttons...
JButton but1 = new JButton("TOTAL VOTE");
but1.setActionCommand("TOTAL VOTE");
Then remove extends JFrame from RSummary, as it is doing nothing but adding to the confusion and adds no benefit
Setting a frame invisible will not "close" it. Instead use JFrame#dispose
Finally, making a component visible while it's part of split pane won't resize the split divider. Once you've made the corrections, you will need to manually move the divider.
You may consider placing a empty panel into the split pane and using a CardLayout, add the other components to it, switching them in and out using the CardLayout
Updated with modified code
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class RSummary extends JFrame implements ActionListener {
JFrame rframe = new JFrame();
JPanel panel1, panel2, panel3, panel4, panel5;
JTable table;
JScrollPane scroll;
JSplitPane splitPane;
JButton butx;
public RSummary() {
rframe.setSize(550, 300);
rframe.setLocationRelativeTo(null);
setSize(550, 300);
rframe.setTitle("Summary Report");
/* Total Vote & Department wise vote buttons */
panel1 = new JPanel();
JButton but1 = new JButton("TOTAL VOTE");
but1.setActionCommand("TOTAL VOTE");
JButton but2 = new JButton("DEPTARTMENT WISE VOTE");
but1.addActionListener(this);
panel1.add(but1);
panel1.add(but2);
/* Report contents according to button */
panel2 = new JPanel();
String[] columnNames = {"Name", "Department", "Phno", "LUID", "Select"};
DefaultTableModel model1 = new DefaultTableModel();
model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll = new JScrollPane(table);
panel2.add(scroll);
panel2.setVisible(false);
/* close button */
panel3 = new JPanel();
JButton but4 = new JButton("CLOSE");
but4.addActionListener(this);
panel3.add(but4);
/* Page heading */
panel4 = new JPanel();
JLabel lab = new JLabel("VOTE SUMMARY REPORT");
panel4.add(lab);
/* dummy panel */
panel5 = new JPanel();
JButton butx = new JButton("Hello butx");
panel5.add(butx);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1, panel2);
rframe.add(splitPane);
rframe.add(panel3, BorderLayout.SOUTH);
rframe.add(panel4, BorderLayout.NORTH);
rframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rframe.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
if ("CLOSE".equals(action)) {
rframe.dispose();
}
if ("TOTAL VOTE".equals(action)) {
panel2.setVisible(true); //this code is not working, i want the solution here.
panel2.getParent().revalidate();
}
}
public static void main(String args[]) throws ClassNotFoundException, SQLException {
new RSummary();
}
}
To switch panels you can do:
rframe.remove (panelToRemove);
rframe.add(panelToShow);
Is this the answer to your question or why do you want to repaint?
Geosearchef
UPDATE:
To summarize:
MadProgrammer is right, you have to replace if(action == "TOTAL VOTE") by if(action.equals("TOTAL VOTE")) (same for CLOSE)
and you have to add an actionCommand:
JButton but1 = new JButton("TOTAL VOTE");
but1.addActionListener(this);
but1.setActionCommand("TOTAL VOTE");
To change panels:
if (action.equals("TOTAL VOTE")) {
try{rframe.remove(panel1;)}catch(Exception e){}//clear window, maybe there is a method
try{rframe.remove(panel2;)}catch(Exception e){}
try{rframe.remove(panel3;)}catch(Exception e){}
rframe.add(panel2);//the panel you want to show
}
Of course, you have to get references to the panels to actionPerformed(ActionEvent ae).

adding a label to a text field

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();
}
});
}
}

Categories