How do I add a class in to a JPanel? - java

This is the JPanel
public class DisplayBoard {
public static void main (String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//The main panel
JPanel main = new JPanel();
main.setPreferredSize(new Dimension(600,800) );
main.setLayout(new BorderLayout());
//The title panel
JPanel title = new JPanel();
title.setPreferredSize(new Dimension(400, 120));
title.setBackground(Color.YELLOW);
JLabel test1 = new JLabel("Title goes here");
title.add(test1);
//The side bar panel
JPanel sidebar = new JPanel();
sidebar.setPreferredSize(new Dimension(200, 800));
sidebar.add(AddSubtract);
sidebar.setBackground(Color.GREEN);
JLabel test2 = new JLabel("Sidebar goes here");
sidebar.add(test2);
//The panel that displays all the cards
JPanel cardBoard = new JPanel();
cardBoard.setPreferredSize(new Dimension(400,640) );
//adding panels to the main panel
main.add(cardBoard, BorderLayout.CENTER);
main.add(title, BorderLayout.NORTH);
main.add(sidebar, BorderLayout.WEST);
frame.setContentPane(main);
frame.pack();
frame.setVisible(true);
}
}
and I want to add this class into the sidebar panel
public class AddSubtract {
int Number = 0;
private JFrame Frame = new JFrame("Math");
private JPanel ContentPane = new JPanel();
private JButton Button1 = new JButton("Add");
private JButton Button2 = new JButton("Subtract");
private JLabel Num = new JLabel ("Number: " + Integer.toString (Number));
public AddSubtract() {
Frame.setContentPane(ContentPane);
ContentPane.add(Button1);
ContentPane.add(Button2);
ContentPane.add(Num);
Button1.addActionListener(new Adding());
Button2.addActionListener(new Subtracting());
}
public class Adding implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number++;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public class Subtracting implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number--;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public void launchFrame(){
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.pack();
Frame.setVisible(true);
}
public static void main(String args[]){
AddSubtract Test = new AddSubtract();
Test.launchFrame();
}
}
Can someone explain to me how I can do this ?
I have a feeling that this is not going to work, but I really want to learn the way to do it.

This definately is not going to work. For starters, you have two main() methods. Second, if you want to add a class to your Frame, it should extend from JComponent. Basically, your code should look like this:
public class MainFrame extends JFrame {
public MainFrame() {
this.add(new MainPanel())
//insert all settings here.
}
}
public class MainPanel extends JPanel {
public MainPanel() {
this.add(new AddSubtract());
this.add(/*more panels*/)
}
}
public class AddSubtract extends JPanel {
public AddSubtract() {
//add buttons and stuff here
}
}
and variables do NOT start with capitals.
Edit: And when you have some JFrame, it's usually best to have a main() method with just one line:
public static void main(String[] args) {
new MainFrame();
}
just set the settings and configuration of the JFrame in the constructor.

Related

java communication between 2 JFrames

I'm getting an AWT-EventQueue-0 Null Pointer Exception in the below code and I can't get to fix it.
I want to have a main frame, from which by pressing a button
I open a second frame, where I have the option to create new players,
which would show up in the main frame.
I passed the references to the constructors, but I still keep getting the error.
I would be very happy for some help, thanks!
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new App();
}
});
}
}
public class App extends JFrame {
private MainPanel mainPanel;
private SecondPanel secondPanel;
public App() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
secondPanel = new SecondPanel(mainPanel);
mainPanel = new MainPanel(secondPanel);
add(mainPanel);
}
}
public class MainPanel extends JPanel {
private JTextArea textArea;
private JScrollPane scrollPane;
private JButton options;
public MainPanel(SecondPanel secondPanel) {
textArea = new JTextArea();
textArea.setColumns(20);
textArea.setRows(5);
textArea.setSize(300, 300);
textArea.setVisible(true);
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
scrollPane.setSize(new Dimension(400, 400));
options = new JButton("Options");
options.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
secondPanel.setVisible(true);
}
});
add(scrollPane);
add(options);
}
public JTextArea getTextArea() {
return textArea;
}
public void setTextArea(JTextArea textArea) {
this.textArea = textArea;
}
}
public class SecondPanel extends JFrame {
private JButton create, remove;
private JPanel panel;
public SecondPanel(MainPanel mainPanel) {
setVisible(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
panel = new JPanel();
panel.setLayout(new BorderLayout());
create = new JButton("create");
create.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mainPanel.getTextArea().append("New Player Created");
}
});
remove = new JButton("remove");
remove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mp.getTextArea().setText("Player removed");
}
});
add(panel);
panel.add(create, BorderLayout.EAST);
panel.add(remove, BorderLayout.WEST);
}
}
Well, it has to be "null", because you don't initialise your MainPanel before you hand it over to the secondPanel.
Instead, make an own method for setting the MainPanel on the secondPanel and to set the secondPanel on the MainPanel.
I see that you need the secondPanel for instance in your constructor to set an ActionListener. Do that in your "setSecondPanel(SecondPanel sPanel)"-Method which, as I mentioned before, you should create.

Bar Chart from different class in to GUI class

I have Gui class with a JPanel and JButton. When the button is clicked i would like to display the graph in my JPanel. The Graph is in different class. Can someone help me do this please?
GUI CLASS:
public class Gui extends JFrame implements ActionListener{
JButton showGraph;
public Gui() {
super("GUI");
setSize(1200,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
showGraph = new JButton("SHOW GRAPH");
JPanel mainPanel = new JPanel();
add(mainPanel);
mainPanel.setLayout(new GridLayout(2,0,10,10));
mainPanel.setBorder(new EmptyBorder(10,10,10,10));
mainPanel.add(showGraph);
JPanel graphPanel = new JPanel();
graphPanel.setBackground(Color.yellow);
mainPanel.add(graphPanel);
showGraph.addActionListener(this);
}
public static void main (String[] args){
new Gui().setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showGraph) {
SimpleBarChart b = new SimpleBarChart();
b.getGraph();
}
}
}
Change your getGraph() method to take a JFrame and pass in this.
public void getgraph(JFrame f) {
//JFrame f = new JFrame();
f.setSize(400, 300);
... as before ...
}
Then call in actionPerformed
if (e.getSource() == showGraph) {
SimpleBarChart b = new SimpleBarChart();
b.getGraph(this);
}
You can't have a frame inside a frame. Another option would be to make getGraph() return a JPanel and then you could put the panel in your existing frame instead of updating the whole frame.

Combinations of Classes

Hey everyone, I want to combine my classes and get it in
only one frame. Now I have 2 classes and I don't know how to group them.
The JSlider.
public class JSliderExample extends JFrame {
JSlider jsHorizontal;
JTextField jtf1;
public JSliderExample() {
jsHorizontal = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
jtf1 = new JTextField(15);
jtf1.setEditable(false);
jtf1.setText("Horizontal value is " + jsHorizontal.getValue());
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.add(jsHorizontal);
panel.setBackground(Color.WHITE);
panel.add(jtf1);
panel.setBackground(Color.WHITE);
getContentPane().add(panel, BorderLayout.CENTER);
getContentPane().add(panel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(300, 400, 400, 300);
setVisible(true);
setBackground(Color.WHITE);
}
class JSliderHandler implements ChangeListener {
public void stateChanged(ChangeEvent ce) {
jtf1.setText("value is " + jsHorizontal.getValue());
}
}
And there are my buttons
.
public void createGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JButton button2 = new JButton("PLAY");
button2.setActionCommand("Button PLAY was pressed!");
panel.add(button2);
textField = new JTextField();
textField.setColumns(23);
panel.add(textField);
ActionListener actionListener = new TestActionListener();
button1.addActionListener(actionListener);
button2.addActionListener(actionListener);
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(e.getActionCommand());
}
});
getContentPane().add(panel);
setPreferredSize(new Dimension(320, 100));
}
public class TestActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
textField.setText(e.getActionCommand());
}
}
In the end of programm I see 2 frames that consist of 2 classes.
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestFrame frame = new TestFrame();
frame.pack();
JSliderExample frame1 = new JSliderExample();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
If you don't want to see 2 JFrames, then don't create 2 JFrames. Why not make JPanels with all your classes above and not JFrames, and then in your main method, add your JPanels to the JFrame created within main. Simple.
So for example, instead of having JSliderExample extend JFrame, change it's name to SliderPanel and have it extend JPanel, and likewise with your JButton program. Then your main method could look something like:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// your JSlider example class **that extends JPanel**
SliderPanel sliderPanel = new SliderPanel();
// your JButton example class **that extends JPanel**
ButtonPanel buttonPanel = new ButtonPanel():
JFrame frame = new JFrame("My GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(sliderPanel, BorderLayout.PAGE_START);
frame.add(buttonPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null); // center GUI if you want
frame.setVisible(true);
}
});
}

Why is the public class name wrong?(Card Layout)

The program doesn't work still after I fixed the selling error. It says in the console. "Error: Main method not found in class help.MyCardLayout, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application" I don't know what that means.
package help;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyCardLayout implements ItemListener {
JPanel cards;
final static String BUTTONPANEL1 = "Card1";
final static String BUTTONPANEL2 = "Card2";
public void addComponentToPane(Container pane){
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = { BUTTONPANEL1, BUTTONPANEL2 };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
JPanel card2 = new JPanel();
card2.add(new JButton("Button 2"));
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL1);
cards.add(card2, BUTTONPANEL2);
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent evt){
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String) evt.getItem());
}
private static void createAndShowGUI(){
JFrame frame = new JFrame("CardLayoutDemo");
frame.setSize(300,200);
frame.setTitle("CardLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You wrote:
public void itemStateChange(ItemEvent evt) {
^ d is missing
The name is itemStateChanged and not itemStateChange
You've misspelt itemStateChanged() as itemStateChange() (there's a d missing at the end):
public void itemStateChange(ItemEvent evt){
↑ here

pass JFrame.getText() from one class member to other?

In this code , I have used 3 classes all of them which extend the JPanel class , whose instances are added to a JFrame in the JForm3 class's constructor.
I am wondering if there's a way to display the text present in the text field(instance of JTextField declared in TextPanel class) in the printTextOnConsole() method in the ButtonPanel class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JForm3
{
JFrame frame;
ButtonPanel bP;
TextPanel tP;
LabelPanel lP;
public JForm3()
{
frame = new JFrame("Java Window.");
bP = new ButtonPanel();
tP = new TextPanel();
lP = new LabelPanel();
frame.setSize(500,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER,tP);
frame.getContentPane().add(BorderLayout.EAST,bP);
frame.getContentPane().add(BorderLayout.WEST,lP);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
new JForm3();
}
}
class ButtonPanel extends JPanel implements ActionListener
{
JButton quitButton;
JButton printButton;
public ButtonPanel()
{
quitButton = new JButton("Quit");
printButton = new JButton("Print");
quitButton.addActionListener(this);
printButton.addActionListener(this);
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
this.add(quitButton);
this.add(printButton);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == quitButton)
System.exit(0);
else
printTextOnConsole();
}
public void printTextOnConsole()
{
}
}
class LabelPanel extends JPanel
{
JLabel label;
public LabelPanel()
{
this.setLayout(new BorderLayout());
label = new JLabel("Enter Some Text :");
this.add(BorderLayout.CENTER,label);
this.setVisible(true);
}
}
class TextPanel extends JPanel
{
JTextField textField;
public TextPanel()
{
this.setLayout(new BorderLayout());
textField = new JTextField("Enter text here");
this.add(BorderLayout.CENTER,textField);
this.requestFocus();
textField.select(0,textField.getText().length());
this.setVisible(true);
}
}
Use an interface to loose couple the text functionality between JPanels.
interface TextRetriever {
String getText();
}
Then pass the instance of the TextRetriever (TextPanel) to ButtonPanel
class ButtonPanel extends JPanel implements ActionListener {
private TextRetriever textRetriever;
public ButtonPanel(TextRetriever textRetriever) {
this.textRetriever = textRetriever
...
}
public void printTextOnConsole() {
String text = textRetriever.getText();
}
}

Categories

Resources