import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class File
{
private JFrame frame1;
private JPanel panel1;
private JPanel panel2;
private JLabel labelWeight;
private JLabel labelHeight;
File()
{
frame1 = new JFrame();
panel1 = new JPanel();
panel2 = new JPanel();
labelWeight = new JLabel("Weight :");
labelHeight = new JLabel("Height :");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
panel1.setLayout(new FlowLayout());
panel1.add(labelWeight);
panel2.setLayout(new FlowLayout());
panel2.add(labelHeight);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
frame1.setLayout(new BoxLayout(frame1,BoxLayout.X_AXIS));
panel1.setAlignmentY(0);
panel2.setAlignmentY(0);
frame1.add(panel1);
frame1.add(panel2);
frame1.setSize(400, 200);
frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
public static void main (String args[])
{
new File();
}
}
It gives BoxLayout Sharing error at runtime
Generally, LayoutManagers are set on a JPanel. I guess JFrame implements this method to forward it to the content pane of the frame. I would suggest you try:
Container contentPane = frame1.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.X_AXIS));
If you still have problems take a look at the Swing tutorial on How to Use Box Layout for working examples.
Swing components should be created in the Event Dispatch Thread. Try this in your main():
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new File();
}
});
But your problem may be the same as this question.
Related
Given a JFrame whose contentPane's layout is set to null, I would like to add two tabs one for Publisher, the other is for Subscriber such as :
public class PubSubGUI extends JFrame{
private JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
private JPanel pubPanel = new JPanel();
private JPanel subPanel = new JPanel();
public PubSubGUI(Controller controller) {
getContentPane().setLayout(null);
getContentPane().add(tabbedPane);
//add Publisher components to pubPanel
tabbedPane.addTab("Publlisher", pubPanel);
//add Subscriber components to pubPanel
tabbedPane.addTab("Subscriber", subPanel);
//Rest of the constructor's source code is omitted
}
//Rest of the class' source code is omitted
}
When running the application neither the components nor the tabs are displayed. All I am getting is an empty JFrame. I tried to set different LayoutManagers to each of pubPanel and subPanel, still the problem persists. Any hints or suggestions please.
Refer This:
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}
I've created two jframes main_frame and sub_frame where main_frame holds a jbutton. Now i want that button to open sub_frame in the same frame(main_frame) and set main_frame disable until sub_frame is opened.
Note that I dont want main_frame to setVisible(false).
I suggest you use a CardLayout
Instead of multiple JFrames, you have multiple JPanels and switch between them.
Here is an example:
package main.frames;
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame
{
static JPanel homeContainer;
static JPanel homePanel;
static JPanel otherPanel;
static CardLayout cl;
public MainFrame()
{
JButton showOtherPanelBtn = new JButton("Show Other Panel");
JButton backToHomeBtn = new JButton("Show Home Panel");
cl = new CardLayout(5, 5);
homeContainer = new JPanel(cl);
homeContainer.setBackground(Color.black);
homePanel = new JPanel();
homePanel.setBackground(Color.blue);
homePanel.add(showOtherPanelBtn);
homeContainer.add(homePanel, "Home");
otherPanel = new JPanel();
otherPanel.setBackground(Color.green);
otherPanel.add(backToHomeBtn);
homeContainer.add(otherPanel, "Other Panel");
showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel"));
backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home"));
add(homeContainer);
cl.show(homeContainer, "Home");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("CardLayout Example");
pack();
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
It is really easy, just call the constructor and set visibility:
SubFrameClass frame = new SubFrameClass();
frame.setVisible(true);
Components are not displayed in my JFrame using Swing.
Actually my aim is:
Add Frame
In the frame add panel
Panel cantains 3 buttons
But it didn't show.
Here is my code
public class Panels
{
JFrame frame;
JPanel panel;
private JButton addButton;
private JButton modifyButton;
private JButton deleteButton;
Panels()
{
initGUI();
launchFrame();
}
public void initGUI()
{
frame = new JFrame();
panel = new JPanel();
addButton = new JButton("Add");
modifyButton = new JButton("Modify");
deleteButton = new JButton("Delete");
}
public void launchFrame()
{
addButton.setBounds(130,50,225,25);
addButton.setBounds(150,50,225,25);
addButton.setBounds(170,50,225,25);
addButton.setBounds(190,50,225,25);
panel.add(addButton);
panel.add(modifyButton);
panel.add(deleteButton);
panel.setLayout(null);
panel.setBackground(Color.RED);
frame.add(panel);
frame.setTitle("My Frame with Panel");
frame.setSize(600,400);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Here is main for calling Panels class
When run on main function Frame is shown without controllers (ie 3 buttons not shown)
public class Main
{
public static void main(String[] args)
{
Panels obj_panel=new Panels();
}
}
This is the main problem
frame.setLayout(null);
When you set the layout to null, that means that all of its components must have boundaries set. You try to add the panel, without any boundaries. You only set the boundaries for the buttons in the panel. If you remove the above line, it works.
Other Issues I'd really take a look at:
Don't use null layouts at all. Instead make use of layout managers, and let them handle the sizing and positioning for you. This results in a a much more manageable and flexible UI. Please take some time to learn the different layout managers. Start at Laying out Components Within a Container
All Swing apps should run on a special thread known as the Event Dispatch Thread (EDT). Please take some time to read Initial Threads to learn how you can accomplish this.
Here is a refactor (fixing the "Other issues") with no null layout, just using layout managers, margins, and borders, and the code in the main shows how to run the program on the Event Dispatch Thread
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
Panels obj_panel = new Panels();
}
});
}
}
class Panels {
private JFrame frame;
private JPanel panel;
private JButton addButton;
private JButton modifyButton;
private JButton deleteButton;
Panels() {
initGUI();
launchFrame();
}
private void initGUI() {
frame = new JFrame(); // default layout manager is BorderLayout
panel = new JPanel(); // default layout manager is FlowLayout
addButton = new JButton("Add");
modifyButton = new JButton("Modify");
deleteButton = new JButton("Delete");
}
private void launchFrame() {
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 10, 10));
buttonPanel.setBackground(Color.RED);
buttonPanel.add(addButton);
buttonPanel.add(modifyButton);
// add margin to left and right of delete button
// other buttons will follow suit because of GridLayout
deleteButton.setMargin(new Insets(0, 50, 0, 50));
buttonPanel.add(deleteButton);
// create some space at the top for the buttonPanel
buttonPanel.setBorder(new EmptyBorder(20, 0, 0, 0));
panel.add(buttonPanel);
panel.setBackground(Color.RED);
frame.add(panel);
frame.setTitle("My Frame with Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Hi all, I was in a development of my college mini project. It was a Library Management system , which i should do in Java swing using Net-beans IDE. First I was doing manual coding. It takes time.
In manual coding I create single JFrame with Menu bar and and items, on all action performed I wrote codes for all Jpanels. It made the file and code huge. and confusing too.
Now I need your help.
I have created a Main JFrame with Menu
A JPanel - ADD Book
another Jpanel - On add book success (demo! , for Actions happening in ADD Book )
I had made action listener
addBook addbk = new addBook();
this.getContentPane().add(addbk);
wrote this code.
I doesn't make sense.
Friends, As a new to java, What i need to study is
1.) How cal and Show an external Jpanel an action performed
2.) How to show another JPanel to same root JFrame if any event has occurred in external JPanel.
In sort, something like Iframe in HTML
Thank you all.
http://compilr.com/abelkbil/openlib/OpenLibMainGUI.java
http://compilr.com/abelkbil/openlib/addBook.java
http://compilr.com/abelkbil/openlib/bookAdded.java
CardLayout, is exactly what you need for this situation. And do learn Java Naming Conventions and stick to them, as you are a beginner, so to be on the right track from the start is always GOOD.
Here is one example, that you can look at :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel panel2;
private MyPanel panel3;
private JComboBox choiceBox;
private String[] choices = {
"Panel 1",
"Panel 2",
"Panel 3"
};
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
choiceBox = new JComboBox(choices);
panel1 = new MyPanel(contentPane
, Color.RED.darker().darker(), this);
panel2 = new MyPanel(contentPane
, Color.GREEN.darker().darker(), this);
panel3 = new MyPanel(contentPane
, Color.DARK_GRAY, this);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
contentPane.add(panel3, "Panel 3");
frame.getContentPane().add(choiceBox, BorderLayout.PAGE_START);
frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JComboBox getChoiceBox()
{
return choiceBox;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
private Color backgroundColour;
private JComboBox choiceBox;
public MyPanel(JPanel panel, Color c, CardLayoutExample cle)
{
contentPane = panel;
backgroundColour = c;
choiceBox = cle.getChoiceBox();
setOpaque(true);
setBackground(backgroundColour);
//construct components
jcomp1 = new JButton ("Show New Panel");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String changeToPanel = (String) choiceBox.getSelectedItem();
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, changeToPanel);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
Else you can have a look at this example also.
I have this app, but, when I resize the window, the element JTextArea inside, it doesn't resize with the window. Why?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ExampleGUI {
private JTextArea text_area;
private JScrollPane scroll_bar;
private JFrame frame;
private JPanel panel;
public ExampleGUI(){
frame = new JFrame("Example GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text_area = new JTextArea();
scroll_bar = new JScrollPane(text_area);
panel = new JPanel();
panel.add(scroll_bar);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){public void run(){new ExampleGUI();}});
}
}
You need to set your GridBagConstraint x and y weights (weightx and weighty -- the 5th and 6th parameters in the GridBagConstraint constructor) to a positive value other than 0.0. You should read tutorials on GridBagLayout if you're going to use it as it is fairly complex. Some have had great success nesting simpler layouts or using 3rd party layouts such as MigLayout.
Your frame layout is a FlowLayout. This does not resize children. From the docs:
A flow layout lets each component assume its natural (preferred) size.
You will be better off using a BorderLayout and putting the pane in the CENTER.
Replace this:
frame.setLayout(new FlowLayout());
frame.add(pane);
with this:
frame.setLayout(new BorderLayout());
frame.add(pane, BorderLayout.CENTER);
Also, as Hovercraft points out, if you need the individual components to resize when the pane resizes, then you need to have non-zero weights in the GridBagConstraints.
This takes into account the advice of Hovercraft Full Of Eels & Ted Hopp with a few other tweaks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Collection;
public class AziendaGUI implements ActionListener {
private JButton view_list;
private JButton save_list;
private JTextArea text_area;
private JScrollPane scrollpane;
private JPanel pane;
private JFrame frame;
private GridBagLayout grid;
public AziendaGUI() {
frame = new JFrame("Immobiliari s.p.a");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
view_list = new JButton("View Property");
view_list.setActionCommand("view_list");
view_list.addActionListener(this);
save_list = new JButton("Save List");
save_list.setActionCommand("save_list");
save_list.addActionListener(this);
text_area = new JTextArea(10,22);
text_area.setEditable(false);
scrollpane = new JScrollPane(text_area);
grid = new GridBagLayout();
pane = new JPanel();
pane.setLayout(grid);
/* Set Constraints view_list button */
grid.setConstraints(view_list, new GridBagConstraints(0,0,1,1,0.0,0.0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,5,5,5),0,0));
pane.add(view_list);
/* Set Constraints save_list button */
grid.setConstraints(save_list,new GridBagConstraints(1,0,1,1,0.1,0.1,GridBagConstraints.EAST,GridBagConstraints.NONE,new Insets(5,5,5,5),0,0));
pane.add(save_list);
frame.add(scrollpane);
frame.add(pane, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
private void store(){
String file_name = JOptionPane.showInputDialog("Inserisci il nome del file");
}
#Override
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
if(s.equals("view_list")){
}
if(s.equals("save_list")){
store();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){#Override
public void run(){new AziendaGUI();}});
}
}