Swing & AWT: ContentPane items not showing in JFrame - java

I'm creating a basic Java Swing app but I am having problems with my content pane as it is not showing my objects.
This is my main class this will be calling up other classes in future and is just calling up the Frame.java:
public class Main
{
public static void main(String[] args)
{
System.out.println("HI");
Frame frameObject = new Frame();
frameObject.main();
}
}
This is the frame class where i create my frame:
import javax.swing.*;
import java.awt.*;
public class Frame
{
public static void main()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new MainFrame("Warlock of Firetop Mountain");
//Implementing Toolkit to allow computer to get dimensions of screen and assign them to two int values
Toolkit tk = Toolkit.getDefaultToolkit();
int xsize = (int) tk.getScreenSize().getWidth();
int ysize = (int) tk.getScreenSize().getHeight();
frame = new JFrame("Warlock of Firetop Mountain");
frame.setTitle("Warlock of Firetop Mountain");
frame.setSize(new Dimension(xsize, ysize));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
This is my mainFrame.java where i store my components:
public class MainFrame extends JFrame
{
public MainFrame(String title)
{
super(title);
setLayout(new BorderLayout());
//Components - Buttons
JButton saveButton =new JButton("Save");
JButton loadButton =new JButton("Load");
JButton optionsButton = new JButton("Options");
JButton inventoryButton =new JButton("Inventory");
Container buttonsContainer = getContentPane();
buttonsContainer.add(saveButton, BorderLayout.LINE_START);
buttonsContainer.add(loadButton, BorderLayout.CENTER);
buttonsContainer.add(optionsButton,BorderLayout.CENTER);
buttonsContainer.add(inventoryButton,BorderLayout.AFTER_LINE_ENDS);
//Components - Enter Button
JButton enterButton = new JButton("Enter");
// /Components - ComboBox
JComboBox pageTurner = new JComboBox();
//Components = JTextArea
JTextArea currentText = new JTextArea();
}
}

frame = new JFrame("Warlock of Firetop Mountain");
Why are you resetting frame with a new instance of JFrame? Didn't you already set it with MainFrame?

What you are doing is assigning frame to a new MainWindow that contains all your components. But then, you re-assign frame to a new JFrame, and a JFrame by default has no components.

Related

How to group two windows into one?

I need to insert the window with the tabbed called "First panel, Second panel, Third panel, Fourth panel" into the window named "Animation".
What should I do so that at the end it looks like: a window that has an animation box with four tabs, a Text box and a User input box?
First class called "Main" :
import java.awt.*;
import javax.swing.*;
public class Main {
JFrame frame = new JFrame("Demo");
JPanel panel = new JPanel();
JLabel square1 = new JLabel("Animation");
JLabel square2 = new JLabel("Text");
JTextField square3 = new JTextField("User Input");
public Main() {
panel.setLayout(new GridLayout(2,2,3,3));
panel.add(square1);
panel.add(square2);
panel.add(square3);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(600,400);
frame.setVisible(true);
}
public static void main(String[] args) {
Tabbed tp = new Tabbed();
tp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
tp.setSize(600,400);
tp.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main();
}
});
}
}
'Second class called "Tabbed" :'
import javax.swing.*;
public class Tabbed extends JFrame{
private static final long serialVersionUID = 1L;
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
JPanel thirdPanel = new JPanel();
JPanel fourPanel = new JPanel();
JLabel firstLabel = new JLabel("First!");
JLabel secondLabel = new JLabel("Second!");
JLabel thirdLabel = new JLabel("Third!");
JLabel fourLabel = new JLabel("Fourth!");
JTabbedPane tabbedPane = new JTabbedPane();
public Tabbed(){
firstPanel.add(firstLabel);
secondPanel.add(secondLabel);
thirdPanel.add(thirdLabel);
fourPanel.add(fourLabel);
tabbedPane.add("First panel",firstPanel);
tabbedPane.add("Second panel",secondPanel);
tabbedPane.add("Third panel",thirdPanel);
tabbedPane.add("Fourth panel",fourPanel);
add(tabbedPane);
}
}
Here's how I want to combine the two windows :

Java syntax for separating action listeners

Please help me out to separate these ActionListeners in a periodic table that I am attempting to complete. When I execute the program and click on 'H', it opens all the other elements and when the others are clicked, it does not work. So I need a way to separate these using any method...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PeriodicTable
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Elements");
frame.setVisible(true);
frame.setSize(1000,1500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("H");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("He");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Li");
panel.add(button3);
button3.addActionListener (new Action2());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("H");
frame2.setVisible(true);
frame2.setSize(1000,1500);
JLabel label = new JLabel("Hydrogen");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("He");
frame3.setVisible(true);
frame3.setSize(1000,1500);
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Li");
frame4.setVisible(true);
frame4.setSize(1000,1500);
JLabel label = new JLabel("Lithium");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
}
Thanks in advance.
(note: only the first 3 elements are coded for...)
When I execute the program and click on 'H', it opens all other elements
Only one frame opens for me.
and when the others are clicked, it does not work.
Each button opens a single frame for me.
However, button 3 opens the wrong frame because you add the wrong listener to the button:
//button3.addActionListener (new Action2());
button3.addActionListener (new Action3());
Other issues:
You should add the components to the frame BEFORE making the frame visible.
Don't hardcode screen sizes, you never know what size screen other users will be using
So the order of your code might be something like:
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame("He");
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
And of course you really don't want to create dozens of separate ActionListeners. You want to make the listener more generic so it can be shared.
Something like:
static class Action implements ActionListener
{
public Action(String element, String description)
{
this.element = element;
this.description = description;
}
public void actionPerformed (ActionEvent e)
{
JLabel label = new JLabel(description);
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame(element);
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
}
}
Then when you create the listener you use:
button3.addActionListener (new Action("HE", "Helium"));

Placing of JPanels on the JFrames is not correct

I wrote a program to compose a GUI using swing/awt framework for my assignment. So far, I am able to get the pieces working together, but when I put them all into a JFrame, they are not coming out as expected.
I have recently started working on Java GUI framework, and not sure what is missing in my code. How can I get this working properly?
I am also attaching the screen shots (see at the bottom) of the output I am getting.
public class MainFrame extends JFrame {
public MainFrame() {
addComponentsToPane(this.getContentPane());
}
private void addComponentsToPane(Container pane) {
// Set layout
GridBagConstraints gbc = new GridBagConstraints();
this.setTitle("Test tool");
this.setSize(600, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(2, 1));
// Add video JComponent
mMainPanel = new MainPanel();
pane.add(mMainPanel, 0);
// Add conference screen panel
mFeedPanel = new FeedPanel();
pane.add(mFeedPanel, 1);
// Add a button panel
mButtonPanel = new ButtonPanel();
pane.add(mButtonPanel, 2);
this.setResizable(true);
this.setVisible(true);
this.pack();
}
}
// In actual output, there is 1 screen in this panel.
// mScreen1 is derived from JComponent object.
public class MainPanel() extends JPanel {
public MainPanel() {
addMainPanelComponents();
}
private void addMainPanelComponents() {
this.setSize(352, 240);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 2));
add(mScreen);
setVisible(true);
}
}
// In actual output, there are 3 screens in this panel. I have shown code for 1 screen only
// mScreen1 is derived from JComponent object.
public class FeedPanel extends JPanel {
public FeedPanel() {
addFeedPanelComponents();
}
private void addFeedPanelComponents() {
String img1 = "images/screen1.png";
setSize(352, 150);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 3));
Image image1 = ImageIO.read(new File(img1));
mScreen1.setImage(image1);
add(mScreen1);
setVisible(true);
}
}
public class ButtonPanel extends JPanel {
public ButtonPanel() {
addButtonPanelComponents();
}
private void addButtonPanelComponents() {
this.setSize(352, 150);
this.setBackground(Color.yellow);
this.setLayout(new GridLayout(1,
5));
// Add Button to panel
mStartButton = new JButton("Start");
this.add(mStartButton);
mStartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StartButtonActionListener(ae);
}
});
mStopButton = new JButton("Stop");
this.add(mStopButton);
mStopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StopButtonActionListener(ae);
}
});
setVisible(true);
}
}
This comes by default on running the code.
This comes after manually resizing the frame.
The combination of BorderLayout , GirdLayout and BoxLayout can do this for you(Actually it's not the only choice).
Here is the code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridLayoutTest {
public void createUI(){
JFrame frame = new JFrame();
JPanel topPanel = new TopPanel();
JPanel buttomPanel = new ButtomPanel();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel,BorderLayout.CENTER);
mainPanel.add(buttomPanel,BorderLayout.SOUTH);
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
GridLayoutTest test = new GridLayoutTest();
test.createUI();
}
#SuppressWarnings("serial")
class TopPanel extends JPanel{
public TopPanel(){
setLayout(new GridLayout(2, 3));
ImageIcon icon = new ImageIcon("capture.png");
JLabel label1 = new JLabel(icon);
label1.setVisible(false);
JLabel label2 = new JLabel(icon);
JLabel label3 = new JLabel(icon);
label3.setVisible(false);
JLabel label4 = new JLabel(icon);
JLabel label5 = new JLabel(icon);
JLabel label6 = new JLabel(icon);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);
add(label6);
}
}
#SuppressWarnings("serial")
class ButtomPanel extends JPanel{
public ButtomPanel(){
JButton startButton = new JButton("start");
JButton stopButton = new JButton("stop");
JButton recordButton = new JButton("record");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
}
}
}
BoxLayout is so good too provide white space and help you to center the component.
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
Add Glue before the first component and after the last component will help you too center the component and add strut can help you to provide white space you want. you can refer to https://stackoverflow.com/a/22525005/3378204 for more details.
Here is the effect:
The BoxLayout won't affect your component's size. Hope it can help you.
Try this :
public class Main{
private JFrame f;
private JLabel l1, l2, l3,l4;
private JPanel p1, p2, p3;
private JButton b1, b2, b3;
public Main(){
this.f = new JFrame();
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.f.setLayout(new GridLayout(3,1));
this.p1 = new JPanel();
this.p1.setLayout(null)
this.p1.setSize(yoursize);
this.l1 = new JLabel();
this.l1.setBounds(x,y,xspan,yspan);
this.p1.add(l1);
this.p2 = new JPanel();
this.p2.setLayout(new GridLayout(1,3));
this.l2 = new JLabel();
this.l3 = new JLabel();
this.l4 = new JLabel();
this.p2.add(l2);
this.p2.add(l3);
this.p2.add(l4);
this.p3 = new JPanel();
this.p3.setLayout(new GridLayout(1,3));
this.b1 = new JButton();
this.b2 = new JButton();
this.b3 = new JButton();
this.p3.add(b1);
this.p3.add(b2);
this.p3.add(b3);
this.f.add(p1);
this.f.add(p2);
this.f.add(p3);
this.f.pack();
this.f.setResizeable(false)
}}
Add your video components instead of labels and you can change the color of the components as you wish.
Also if you want more control over the size and position of the components, use null layout and place them individually using setBounds() function as once shown in the program above. It is surely time consuming but makes the layout perfect.

Working with JFrames

hi I'm basically give up. Ok so this is what I am trying to do. So far I have written code to create a JFrame which contains a text field and combo box. The code is supposed to calculate the area of an input in the text field depending on what shape is selected from the combo box and output the result on the JFrame!
Here's is what the output should look like
And here is my code so far. it's a bit messed up but any help would be much appreciated. Thanks in advance
import javax.swing. *;
import java.awt.event. *;
import java.awt.FlowLayout;
import java.lang.Math;
public class AreaFrame3 extends JFrame
{
double Area;
double input;
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);
JLabel label1 = new JLabel("Select shape:");
JPanel panel1 = new JPanel(new FlowLayout()); //set frame layout
JLabel label2 = new JLabel("(select shape first)");
JTextField text = new JTextField(10); //create text field
text.setEnabled(false);
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);
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);
frame.pack();
//set JFrame ssize
frame.setSize(400,250);
//make JFrame visible. So we can see it
frame.setVisible(true);
// public void actionPerformed(ActionEvent e)
//{
}
public void AreaCalc()
{
JButton button = new JButton("GO"); //create GO button
frame.add(button);
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
int input = double.parseDouble(text.getText());
if(e.getSource() == button)
{
String shape = (String).comboBox.getSelectedItem();
if(shape == "(no shape selected)")
{
text.setEnabled(false);
}
else{
text.setEnabled(true);
}
if(input > 1 && shape == "Circle")
{
// label2.getText() = "Enter the radius of the circle: ";
Area = (Math.PI * (input * input));
}
}
else{}
}
}
);
}
}
I try to understand what you did here:
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);
frame.add(text); // <---
Especially frame.add(text); and panel1.add(text);. Don't add text to JFrame. Use JPanel.
Further,
public class AreaFrame3 extends Frame
Use public class AreaFrame3 extends JFrame so you don't need create additional JFrame:
JFrame frame=new JFrame("Area Calculator Window");
Something like:
super.setLayout(new FlowLayout()); //set layout
super.add(panel1);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.pack();
//set JFrame ssize
super.setSize(400,250);
//make JFrame visible. So we can see it
super.setVisible(true);
At last Ill give you some tamplate to start with (that will help you):
public class FrameExmpl extends JFrame{
private static final long serialVersionUID = 1L;
private JTabbedPane tabbedPane;
private JPanel topPanel;
private JTextField txtf_loadDS_;
public static int valueInt = 0; // responsible for Task status updating
public static Boolean isFinish = false;
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
FrameExmpl UI_L = new FrameExmpl();
UI_L.buildGUI();
UI_L.setVisible(true);
}
public void buildGUI(){
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
setSize(435, 225);
setLocation(285, 105);
setResizable(false);
topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
txtf_loadDS_ = new JTextField();
txtf_loadDS_.setBounds(22, 22, 382, 25);
topPanel.add(txtf_loadDS_);
finishBuildGUI();
}
public void finishBuildGUI(){
tabbedPane = new JTabbedPane();
topPanel.add(tabbedPane, BorderLayout.CENTER);
}
}
There are multiple issues with this application such as extending from Frame rather than JFrame & attempting to assign an int from Double.parseDouble. I would recommend that you start again building a small but working application and incrementally add functionality, this way errors are easier to fix.

Swing Methods on submission of button

How to close current frame (Frame1) and open a new frame (Frame2) already created and pass the data to frame2 from frame1 on the clicking of button?
Use a CardLayout1. Either that or one JFrame and one or more JDialog2 instances.
How to Use CardLayout
How to Make Dialogs
The very best way to accomplish this, is very much told to you by #Andrew Thompson.
And the other way to accomplish, the motive of the question as described in the code. Here as you make object of your new JFrame, you have to pass the things you need in the other class as an argument to the other class, or you can simply pass the object(with this you be passing everything in one go to the other class)
A sample code for a bit of help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFramesExample
{
public JFrame frame;
private JPanel panel;
private JButton button;
private JTextField tfield;
private SecondFrame secondFrame;
public TwoFramesExample()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
tfield = new JTextField(10);
tfield.setBackground(Color.BLACK);
tfield.setForeground(Color.WHITE);
button = new JButton("NEXT");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// Here we are passing the contents of the JTextField to another class
// so that it can be shown on the label of the other JFrame.
secondFrame = new SecondFrame(tfield.getText());
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(tfield, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFramesExample();
}
});
}
}
class SecondFrame
{
private JFrame frame;
private JPanel panel;
private JLabel label;
private JButton button;
private TwoFramesExample firstFrame;
public SecondFrame(String text)
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
label = new JLabel(text);
button = new JButton("BACK");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
firstFrame = new TwoFramesExample();
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(label, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
}
Hope this be of some help.
Regards

Categories

Resources