Add JPanel from other Class to JPanel - java

I would like to add a JPanel from another class to a JPanel:
class FirstPanel extends JPanel
{
private JButton button;
FirstPanel()
{
setLayout(null);
setVisible(true);
button = new JButton();
button.setBounds(x, y, width, height);
button.setFocusPainted(false);
button.setIcon(new ImageIcon(SecondPanel.class.getResource(filePath)));
button.setBackground(bgColor);
button.setForeground(Color.white);
button.setVisible(true);
Border emptyBorder = BorderFactory.createEmptyBorder();
button.setBorder(emptyBorder);
add(button);
ButtonActionHandler buttonActionHandler = new ButtonActionHandler();
}
public class ButtonActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
setVisible(true);
add(new SecondJPanel());
new SecondJPanel().setVisible(true);
}
} }
And this is my Second JPanel:
class SecondPanel extends JPanel
{
private JButton button;
private JLabel titleLabel;
SecondPanel()
{
setLayout(null);
setVisible(true);
button = new JButton();
button.setBounds(100, 200, 100, 200);
button.setFocusPainted(false);
button.setIcon(new ImageIcon(SecondPanel.class.getResource(filePath)));
button.setBackground(bgColor);
button.setForeground(Color.white);
button.setVisible(true);
Border emptyBorder = BorderFactory.createEmptyBorder();
button.setBorder(emptyBorder);
add(button);
}
}
The Launching of the First Panel through a JFrame (from another class) works, however the adding of the second JPanel to the first one doesn't.
Any help is really appreciated

I'm sorry, but you don't seem to be understanding what I am telling you.
Composition is your friend.
I would do it like this:
public class JPanel1 extends JPanel {
private JButton button;
public JPanel1(ActionListener buttonListener) {
this.button = new Button("Push me");
this.button.addActionListener(buttonListener);
// do what's needed to add the button to the display.
}
}
public class JPanel2 extends JPanel {
private JButton button;
public JPanel2(ActionListener buttonListener) {
this.button = new Button("Push me");
this.button.addActionListener(buttonListener);
// do what's needed to add the button to the display.
}
}
public class TwoPanelFrame extends JFrame {
public TwoPanelFrame(JPanel p1, JPanel p2) {
// add the two panels to your frame and display.
}
}

Related

I want to insert a panel to jframe at a click of button

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Button extends JButton{
Button(){}
Button(String text,ImageIcon icon,Dimension dm,Point point){
this.setText(text);
this.setIcon(icon);
this.setSize(dm);
this.setBorder(BorderFactory.createLineBorder(Color.WHITE));
this.setHorizontalTextPosition(SwingConstants.RIGHT);
this.setIconTextGap(50);
this.setFont(new Font(null, Font.PLAIN, 14));
this.setFocusable(false);
this.setLocation(point);
this.setBackground(null);
}
}
class MenuPanel extends JPanel implements ActionListener{
public MenuPanel(int width,int height,Color color){
bDimension = new Dimension(196,40);
addIcon =new ImageIcon(getClass().getResource("addUser.png"));
editIcon =new ImageIcon(getClass().getResource("editUser.png"));
this.setLayout(null);
this.setPreferredSize(new Dimension(width,height));
this.setBackground(color);
//THE LOGO
this.add(new LogoPanel(new Dimension(196, 150), this.getBackground(),new Point(2, 2)));
//THE ADD BUTTON
btnAdd =new Button("Add User",addIcon,bDimension,new Point(2,this.getComponent(0).getHeight()+4));
btnAdd.addActionListener`enter code here`(this);
this.add(btnAdd);
//THE EDIT BUTTON
btnEdit =new Button("Edit User",editIcon,bDimension,new Point(2,this.getComponent(0).getHeight()+this.getComponent(1).getHeight()+8));
btnEdit.addActionListener(this);
this.add(btnEdit);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnAdd) {
JPanel addUser =new JPanel();
addUser.setBackground(Color.BLUE);
addUser.setPreferredSize(new Dimension(400,100));
addUser.add(new JButton("Button"));
//NOT SURE WHAT I'M DOING HERE. DOESN'T WORK
this.getParent().add(addUser,BorderLayout.CENTER);
}else if(e.getSource()==btnEdit) {
JPanel editUser =new JPanel();
editUser.setBackground(Color.RED);
editUser.setPreferredSize(new Dimension(400,100));
editUser.add(new JButton("Button"));
//NOT SURE WHAT I'M DOING HERE. DOESN'T WORK
this.getParent().add(editUser,BorderLayout.CENTER);
}
}
private Button btnAdd;
private Button btnEdit;
private ImageIcon addIcon;
private ImageIcon editIcon;
private Dimension bDimension;
}
class LogoPanel extends JPanel{
public LogoPanel(Dimension dimension,Color color,Point point){
btnLogo =new JLabel();
btnLogo.setText("Your Name");
btnLogo.setIcon(new ImageIcon(getClass().getResource("user.png")));
btnLogo.setOpaque(true);
btnLogo.setIconTextGap(10);
btnLogo.setHorizontalTextPosition(0);
btnLogo.setVerticalTextPosition(3);
btnLogo.setHorizontalAlignment(0);
btnLogo.setVerticalAlignment(0);
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createLineBorder(Color.WHITE));
this.setSize(dimension);
this.setBackground(color);
this.add(btnLogo,BorderLayout.CENTER);
this.getComponent(0).setFont(new Font(null, Font.PLAIN, 14));
this.getComponent(0).setFocusable(false);
this.setLocation(point);
}
JLabel btnLogo;
}
public class Window extends JFrame {
public Window(){
this.setTitle(null);
this.setIconImage(null);
this.setLayout(new BorderLayout(0,2));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(new Dimension(960,500)));
this.setMinimumSize(new Dimension(960,500));
this.getContentPane().setBackground(new Color(250, 250, 250));
//ADD PANELS
this.add(new MenuPanel(200, 0, new Color(238, 238, 238)),BorderLayout.WEST);
this.setLocationRelativeTo(null);
}
}
The code above creates a jframe with a borderlayout and a menu panel aligned west. The menu panel has
two jbuttons.
What i want to achive is, click either of the buttons and thereby inserting a panel to the other side of the jframe.
Could you somebody please help/teach me how to achieve this. I am very new to programming and particularly in java.

How to make button in one class affect text area in another?

Please help me to understand how this works. I'm having difficulties to understand how, for example, JButton in one class can alter text in JTextArea that is in another class of a same package. I've made a simple app just to ask a question here, I need this for a bigger school project where I need to implement this to work with multiple classes.
When I put everything in the same class it works but I need it in separate classes.
Here is the simple code.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Button extends JPanel {
private JButton button;
private Panel panel;
public Button() {
button = new JButton("BUTTON");
panel = new Panel();
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
String input = clicked.getText();
panel.setTextArea(input);
//System.out.println(input);
}
});
}
}
class Panel extends JPanel {
private JTextArea textArea;
public Panel() {
setLayout(new BorderLayout());
textArea = new JTextArea();
add(textArea, BorderLayout.CENTER);
}
public JTextArea getTextArea() {
return textArea;
}
void setTextArea(String text) {
this.textArea.setText(text);
}
}
public class Java extends JFrame {
private Button dugme;
private JFrame frame;
private Panel panel;
public Java() {
frame = new JFrame();
dugme = new Button();
panel = new Panel();
//super("test");
frame.setLayout(new BorderLayout());
frame.setTitle("test");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(dugme, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
Java app = new Java();
}
}
I want action listener to alter the text in the panel, sys-out works so the listener listens the button but I can't make it to alter the text in text area.
As already mentioned by #XtremeBaumer you have two different instances of Panel class. You need to remove the secode one.
public class Button extends JPanel {
private JButton button;
private Panel panel;
public Button(Panel panel) { // we need already created instance of panel here.
this.panel = panel;
button = new JButton("BUTTON");
// panel = new Panel(); <-- this line must be deleted.
// ...
}
}
public class Java extends JFrame {
private Button dugme;
private JFrame frame;
private Panel panel;
public Java(){
frame = new JFrame();
panel = new Panel();
dugme = new Button(panel);
// ...
}
}
Please also replace the line
add(textArea, BorderLayout.CENTER);
by
add(new JScrollPane(textArea), BorderLayout.CENTER);
This allows you to get the scrool bars when text goes larger than the text ara size.
Here is your reworked example
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Button extends JPanel {
private JButton button;
private Panel panel;
public Button(Panel panel) {
this.panel = panel;
button = new JButton("BUTTON");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
String input = clicked.getText();
panel.setTextArea(input);
//System.out.println(input);
}
});
}
}
class Panel extends JPanel {
private JTextArea textArea;
public Panel() {
setLayout(new BorderLayout());
textArea = new JTextArea();
add(new JScrollPane(textArea), BorderLayout.CENTER);
}
public JTextArea getTextArea() {
return textArea;
}
void setTextArea(String text) {
this.textArea.setText(text);
}
}
public class Java extends JFrame {
private Button dugme;
private JFrame frame;
private Panel panel;
public Java() {
frame = new JFrame();
panel = new Panel();
dugme = new Button(panel);
//super("test");
frame.setLayout(new BorderLayout());
frame.setTitle("test");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(dugme, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
Java app = new Java();
}
}

Java : Can't display JPanel above a JLabel with image

here's my problem : I display an ArrayList of JLabel with image and a JPanel with buttons inside a JPanel and I want to display my JPanel above my JLabel when I press a button. But when I press the button, my JPanel is under the JLabels.
Please don't tell me to use a JLayerPane cause if I can do without it it would be best.
Thanks for your solutions.
Here's an exemple of my code :
To run this put the image 100x100 found here :
http://www.html5gamedevs.com/topic/32190-image-very-large-when-using-the-dragging-example/
in a file named image
Main :
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("test");
frame.setSize(900,700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
JPanelControler ctrl = new JPanelControler();
frame.add(ctrl.getMyJpanel());
frame.setVisible(true);
}
}
MyJPanelControler :
public class JPanelControler {
private MyJPanel myJpanel;
public JPanelControler() {
myJpanel = new MyJPanel();
myJpanel.createJLabel();
myJpanel.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myJpanel.displayJPanel();
}
});
}
public MyJPanel getMyJpanel() {
return myJpanel;
}
}
MyJPanel :
public class MyJPanel extends JPanel {
private JButton button;
private ArrayList<JLabel> labels;
//a JPanel that contains buttons,... I won't put this class here
private JPanel panel;
public MyJPanel() {
setLayout(null);
button = new JButton("X");
button.setBounds(600,600,50,50);
add(button);
}
public void createJLabel() {
labels = new ArrayList<>();
JLabel label;
try {
BufferedImage image = ImageIO.read(new File("images/image.jpg"));
for(int i=0; i<2; i++) {
label = new JLabel(new ImageIcon(image));
label.setBounds(i*100,50,image.getWidth(), image.getHeight());
labels.add(label);
add(label);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void displayJPanel() {
panel = new JPanel();
panel.setLayout(null);
JButton b = new JButton("Ok");
b.setBounds(0,0,100, 50);
JButton b2 = new JButton("Cancel");
b2.setBounds(0,50,100, 50);
panel.setBounds(150,50, 100, 100);
panel.add(b);
panel.add(b2);
add(panel);
refresh();
}
public void refresh() {
invalidate();
revalidate();
repaint();
}
public JButton getButton() {return this.button; }
}
If you want the buttons to appear over plain images, then you have one of two options:
Draw the images in a paintComponent override in the main JPanel and not as ImageIcons within a JLabel. This will allow you to add components to this same JPanel, including buttons and such, and the images will remain in the background. If you go this route, be sure to call the super.paintComponent(g); method first thing in your override.
Or you could use a JLayeredPane (regardless of your not wanting to do this). You would simply put the background JPanel into the JLayeredPane.DEFAULT_LAYER, the bottom layer (constant is Integer 0), and place the newly displayed JButton Panel in the JLayeredPane.PALETTE_LAYER, which us just above the default. If you go this route, be sure that the added JPanel is not opaque, else it will cover over all images completely.
For an example of the 2nd suggestion, please see below:
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
public class JPanelControler {
private MyJPanel myJpanel;
public JPanelControler() {
myJpanel = new MyJPanel();
myJpanel.createJLabel();
myJpanel.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myJpanel.displayJPanel();
}
});
}
public MyJPanel getMyJpanel() {
return myJpanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("test");
frame.setSize(900, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
JPanelControler ctrl = new JPanelControler();
frame.add(ctrl.getMyJpanel());
frame.setVisible(true);
}
}
class MyJPanel extends JLayeredPane {
private static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia"
+ "/commons/thumb/f/fc/Gros_Perr%C3%A9.jpg/100px-Gros_Perr%C3%A9.jpg";
private JButton button;
private ArrayList<JLabel> labels;
// a JPanel that contains buttons,... I won't put this class here
private JPanel panel;
public MyJPanel() {
setLayout(null);
button = new JButton("X");
button.setBounds(600, 600, 50, 50);
add(button, JLayeredPane.DEFAULT_LAYER); // add to the bottom
}
public void createJLabel() {
labels = new ArrayList<>();
JLabel label;
try {
URL imgUrl = new URL(IMG_PATH); // ** added to make program work for all
BufferedImage image = ImageIO.read(imgUrl);
for (int i = 0; i < 2; i++) {
label = new JLabel(new ImageIcon(image));
label.setBounds(i * 100, 50, image.getWidth(), image.getHeight());
labels.add(label);
add(label);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void displayJPanel() {
panel = new JPanel();
panel.setLayout(null);
panel.setOpaque(false); // ** make sure can see through
JButton b = new JButton("Ok");
b.setBounds(0, 0, 100, 50);
JButton b2 = new JButton("Cancel");
b2.setBounds(0, 50, 100, 50);
panel.setBounds(150, 50, 100, 100);
panel.add(b);
panel.add(b2);
add(panel, JLayeredPane.PALETTE_LAYER); // add it above the default layer
refresh();
}
public void refresh() {
// invalidate(); // not needed
revalidate();
repaint();
}
public JButton getButton() {
return this.button;
}
}

paint method causing other components not to show up

I have a simple GUI program I'm trying to get to work. When the user presses the bottom button I'm trying to get some shapes to paint. When I get rid of the if(buttonClicked) in paint() everything shows up fine but paint() seems to be auto-executed and the shapes appear without any button click. When I add surround the paint() body with if(buttonClicked), regardless of how the ButtonHandler class handles it, the rest of my components do not even show up in the frame. I have no idea why this is happening. Test the code with and without the if logic in paint() and you will see what's going on.
public class GUI extends JFrame {
//declare components
Container container;
JPanel centerPanel, northPanel, southPanel, eastPanel, westPanel, mouseClickPanel;
JLabel topLabel;
JTextArea textArea;
JButton buttonA, buttonB, drawButton;
boolean buttonClicked;
public GUI(String title) {
super(title); // invoke JFrame Constructor
container = getContentPane();
container.setLayout(new BorderLayout());
centerPanel = new JPanel();
centerPanel.setBackground(Color.CYAN);
northPanel = new JPanel();
northPanel.setBackground(Color.GREEN);
southPanel = new JPanel();
southPanel.setBackground(Color.MAGENTA);
eastPanel = new JPanel();
eastPanel.setBackground(Color.ORANGE);
westPanel = new JPanel();
westPanel.setBackground(Color.YELLOW);
mouseClickPanel = new JPanel();
mouseClickPanel.setBackground(Color.GRAY);
mouseClickPanel.setPreferredSize(new Dimension(400, 400));
topLabel = new JLabel("Press either button to make something happen");
topLabel.setFont(new Font("Calibri", Font.PLAIN, 16));
topLabel.setHorizontalAlignment(JLabel.CENTER);
textArea = new JTextArea(3, 20);
textArea.setEditable(false);
buttonA = new JButton("Press Here");
buttonB = new JButton("Press Here");
drawButton = new JButton("Press here");
container.add(centerPanel, BorderLayout.CENTER);
container.add(northPanel, BorderLayout.NORTH);
container.add(southPanel, BorderLayout.SOUTH);
container.add(eastPanel, BorderLayout.EAST);
container.add(westPanel, BorderLayout.WEST);
northPanel.add(topLabel, BorderLayout.NORTH);
centerPanel.add(buttonA);
centerPanel.add(textArea);
centerPanel.add(buttonB);
centerPanel.add(mouseClickPanel);
centerPanel.add(drawButton);
buttonClicked = false;
ButtonHandler buttonHandler = new ButtonHandler(buttonA, drawButton, textArea, buttonClicked);
buttonA.addActionListener(buttonHandler); // add actionListeners to buttonA and B
buttonB.addActionListener(buttonHandler);
drawButton.addActionListener(buttonHandler);
setSize(525, 600);
setVisible(true);
}
public void paint(Graphics g) {
if (buttonClicked) {
super.paint(g);
g.setColor(Color.RED);
g.fillOval(150, 150, 50, 50);
g.draw3DRect(200, 200, 50, 50, true);
}
}
}
Handler class:
public class ButtonHandler extends JFrame implements ActionListener {
private JButton buttonA, drawButton;
private JTextArea textArea;
boolean buttonClicked;
public ButtonHandler(JButton buttonA, JButton drawButton, JTextArea textArea, boolean buttonClicked) {
this.buttonA = buttonA;
this.textArea = textArea;
this.drawButton = drawButton;
this.buttonClicked = buttonClicked;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonA) {
textArea.setText(" <- You pressed left button");
}
else if (e.getSource() == drawButton) {
textArea.setText("You pressed button to draw rectangle");
buttonClicked = true;
repaint();
}
else {
textArea.setText("You pressed right button ->");
}
}
}
Take super.paint(g); out of the if statement. Have it as the first line. Otherwise, no painting at all (including the JPanel internals such as background) will happen unless the button is clicked.

Override the action listener on the X button

I have an internal frame which has my customer JPanel. In my customer JPanel, I added two panels which is from the outside source.
One of these has button to close the panel. However when I clicked it, it is no effect. How can I make the action listener on the button?
public class MyInternalFrame extends JInternalFrame{
private PDFJPanel panel=null;
public MyInternalFrame(File file) {
super("Test" + file.getName(), true, true, true, true);
panel=new PDFJPanel(file);
this.add(panel, BorderLayout.CENTER);
}
}
There is my customer JPanel
public class PDFJPanel extends JPanel {
private JPanel jpAnnotation=null;
private JScrollPane scrollPane = new JScrollPane();
private File thisFile=null;
private PDFNotesBean bean=null;
private CommentPanel commentPane=null;
public PDFJPanel(File file) {
thisFile=file;
getJPanel();
}
public void getJPanel() {
this.setLayout(new BorderLayout());
this.add(getPDFNotesBean(), BorderLayout.CENTER);
commentPane= bean.getCommentPanel();
bean.getCommentPanelNotes().getjcbHideComments().setVisible(false);
//this code can get the button
bean.getCommentPanelNotes().getToolbar().getCloseButton();
//Right size of the Panel
JPanel rightPanel=new JPanel();
rightPanel.setLayout(new BorderLayout());
rightPanel.setBackground(Color.GREEN);
jpAnnotation=new JPanel();
JButton btnUnderline =new JButton(new ImageIcon ("../UnderlineIcon.gif"));
btnUnderline.setSize(50, 260);
btnUnderline.setAlignmentX(JButton.LEFT_ALIGNMENT);
jpAnnotation.add(btnUnderline);
rightPanel.add(jpAnnotation, BorderLayout.NORTH );
rightPanel.add((Component) commentPane, BorderLayout.CENTER );
this.add(rightPanel, BorderLayout.EAST );
}
}
I'll take a shot in the dark.
jpAnnotation.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JFrame myInternalFrame= (JFrame)SwingUtilities.getWindowAncestor(this);
myInternalFrame.remove(PDFJPanel.this);
myInternalFrame.invalidate();
myInternalFrame.validate();
myInternalFrame.repaint();
}
});

Categories