If I have 1 main class and 2 subclasses
subclass 1: public class JPanel1 extends JPanel {....properly initialized}
subclass 2: public class JTextArea1 extends JTextArea {... properly initialized}
Why can I do jframe1.add(new JPanel1()) but not jframe1.add(new JTextArea1())? for a properly initialized JFrame jframe1 = new JFrame();?
My goal is to output data into both the jpanel and the jtextarea
Here on my side, the issue you raising, is working fine. Do let me know, if you think, this is not what you mean :-)
import java.awt.*;
import javax.swing.*;
public class SwingExample
{
private CustomPanel customPanel;
private CustomTextArea customTextArea;
private void displayGUI()
{
JFrame frame = new JFrame("Swing Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createLineBorder(
Color.DARK_GRAY, 5));
customPanel = new CustomPanel();
customTextArea = new CustomTextArea();
contentPane.add(customPanel, BorderLayout.CENTER);
contentPane.add(customTextArea, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new SwingExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
private static final int GAP = 5;
public CustomPanel()
{
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(
Color.BLUE, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(300, 300));
}
}
class CustomTextArea extends JTextArea
{
private static final int GAP = 5;
public CustomTextArea()
{
setBorder(BorderFactory.createLineBorder(
Color.RED, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(100, 30));
}
}
OUTPUT :
Related
class ballbouncepanel extends JPanel
{
public void start()
{
Timer timer;
final int FREQ = 45;
timer = new Timer(FREQ, new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
repaint();
}
});
timer.start();
}
Rect rect = new Rect();
public Dimension getPreferredSize()
{
return new Dimension(250,200);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
rect.draw(g);
rect.move(g);
rect.erase(g);
}
}
class Rect
{
public int xLocation = 0;
public int yLocation = 0;
public int xVelocity = 10;
public int yVelocity = 10;
public void draw(Graphics g)
{
g.setColor(Color.cyan);
g.fillRect(xLocation, yLocation, 20, 20);
}
public void move(Graphics g)
{
xLocation += xVelocity;
yLocation += yVelocity;
}
public void erase(Graphics g)
{
g.setColor(Color.white);
g.fillRect(xLocation, yLocation, 20, 20);
}
}
The new error is that now my repaint method isn't working.
Above is my code for the frame that I got that I want to paint on, I understand paint using a applet or JApplet, but I am trying to do what I did in a applet on Swing, and now im running into problems, I have looked up many tutorials on how to implement graphics in, but most of them is just running a main graphics, I need mine to be in this specific frame(BB). If anyone could help me understand or point me to a beginners tutorial for it, it would be appreciated.
I think you are just forgetting to call the start() method of your ballbouncepanel. Also a note: you're move() method does no painting, so take out the Graphics argument and just call it in the timer
Also not sure what the erase method is supposed to do, but I'm thinking you want to change color every tick of the timer. In that case, just keep a color variable, and just change that variable. You can see the example below
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class bounceballpanel extends JPanel {
public void start() {
Timer timer;
final int FREQ = 45;
timer = new Timer(FREQ, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
rect.move();
rect.changeColor();
repaint();
}
});
timer.start();
}
Rect rect = new Rect();
public Dimension getPreferredSize() {
return new Dimension(250, 200);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
rect.draw(g);
//rect.erase(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
bounceballpanel panel = new bounceballpanel();
panel.start();
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
class Rect {
public int xLocation = 0;
public int yLocation = 0;
public int xVelocity = 10;
public int yVelocity = 10;
Color color = Color.cyan;
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(xLocation, yLocation, 20, 20);
}
public void move() {
xLocation += xVelocity;
yLocation += yVelocity;
}
public void changeColor() {
if (color == Color.cyan) {
color = Color.white;
} else {
color = Color.cyan;
}
}
/*
public void erase(Graphics g) {
g.setColor(Color.white);
g.fillRect(xLocation, yLocation, 20, 20);
}*/
}
I am trying to make a program with 2 panels, and when the first panel is clicked it displays another color, and in the second panel the word changes to the color that is currently displayed
The problem is repaint() doesn't call paintComponent() again
class Fun extends JPanel{
public int i = 0;
A a = new A();
B b = new B();
public Fun(){
setLayout(new GridLayout(2, 2, 10, 10));
add(a);
add(b);
}
public void paintComponent(Graphics g){
setBackground(Color.WHITE);
super.paintComponent(g);
}
class A extends JPanel implements MouseListener{
public Color c = Color.BLUE;
CardLayout cl = new CardLayout();
JPanel c1 = new JPanel();
JPanel c2 = new JPanel();
JPanel c3 = new JPanel();
Color[] colors = {Color.BLUE, Color.GREEN, Color.RED};
public A(){
addMouseListener(this);
setLayout(cl);
c1.setBackground(Color.BLUE);
c2.setBackground(Color.GREEN);
c3.setBackground(Color.RED);
add(c1);
add(c2);
add(c3);
}
public void mouseClicked(MouseEvent e){
cl.next(this);
if (i==2){
i = 0;
}
else{
i++;
}
c = colors[i];
new B().go();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}
class B extends JPanel{
JLabel l = new JLabel("Play Baby!");
public B(){
add(l);
}
public void paintComponent(Graphics g){
System.out.println("repainted");
A apple = new A();
g.setColor(apple.colors[i]);
super.paintComponent(g);
}
public void go(){
repaint();
}
}
}
In your mouseClicked, you are calling go() on a new B. But the new B is never added to another component. You probably want to say, b.repaint(), using the B that was defined as a member variable.
I know this sounds like an easy question, but I am making a simple text adventure with buttons and such, and I cant figure out how to add my Jpanel into my JFrame. My JPanel has a bunch of buttons and graphics and stuff if that makes a difference. I have provided the code below. frame panel=new frame(); is the other class which extends JPanel. I know its confusing that its called "frame", its because I used to have it extend JFrame. Anyways my code doesnt produce the buttons, graphics etc, from the other class like it should. Thanks,
package sonomaroller;
import javax.swing.*;
import java.awt.*;
import static javax.swing.JFrame.*;
public class SonomaRoller extends JFrame {
public static Dimension size = new Dimension(550,550); //Dimension of Frame
public static String title = "Sonoma Roller v0.00" ;
public SonomaRoller(){
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null); // null centers window on screen
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("hello?");
//setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
SonomaRoller object1=new SonomaRoller();
frame panel=new frame();
}
}
Try
SonomaRoller object1=new SonomaRoller();
frame panel=new frame();
object1.getContentPane().add(panel);
or just simply
object1.add(panel);
From: JFrame#getContentPane()
and Container#add(Component)
Here's some code that works if it helps:
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame {
public MyFrame() {
add(new MyPanel());
setSize(640, 480);
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
#Override public void run() {
new MyFrame().setVisible(true);
}
});
}
}
class MyPanel extends JPanel {
#Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(20, 20, 80, 80);
}
}
maybe like this...?
package sonomaroller;
import javax.swing.*;
import java.awt.*;
import javax.swing.JFrame.*;
public class SonomaRoller extends JFrame {
public static Dimension size = new Dimension(550,550); //Dimension of Frame
public static String title = "Sonoma Roller v0.00" ;
public SonomaRoller(){
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null); // null centers window on screen
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("hello?");
//setLayout(null);
setVisible(true);
frame panel=new frame();
setContentPane(panel);
}
public static void main(String[] args) {
SonomaRoller object1=new SonomaRoller();
}
}
This is how I normally do it:
public class SonomaRoller extends JFrame {
public SonomaRoller(){
setLayout(new BorderLayout(0, 0));
JPanel newPanel = new JPanel();
getContentPane().add(newPanel);
}
}
this is the problem :
frame panel=new frame();
put this line instead of above code :
Frame frame = new Frame();
Panel panel = new Panel();
frame.add(panel);
Below is SSCCE to describe my problem.
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class APanel extends JPanel{
public APanel() {
this.setVisible(true);
this.setBackground(Color.red);
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()==2)
{
}
System.out.println("Child panel clicked!");
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) {}
});
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PPanel extends JPanel{
private APanel panel1;
private APanel panel2;
private APanel panel3;
public PPanel() {
this.setLayout(new GridLayout(0,1));
panel1 = new APanel();
panel2 = new APanel();
panel2.setBackground(Color.yellow);
panel3 = new APanel();
panel3.setBackground(Color.green);
this.add(panel1);
this.add(panel2);
this.add(panel3);
this.setBackground(Color.blue);
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.println("Parent panel clicked!");
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) {}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame();
PPanel panel = new PPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(350, 300));
frame.setTitle("Demo");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
How can I do the following:
If e.getClickCount()==1 then the parent MouseListener will active and it will print "parent panel clicked!".
If e.getClickCount()==2 then the children MouseListner will active and print out "child panel clicked!".
Edit1: Closer to the proposed solution.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
public class APanel extends JPanel {
private static final long serialVersionUID = 1L;
private Point pt;
public APanel() {
timer.setRepeats(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double from child");
pt = null;
timer.stop();
} else {
pt = e.getPoint();
Component component = (Component)e.getSource();
component.getParent().dispatchEvent(e);
timer.restart();
}
}
});
setBackground(Color.red);
setVisible(true);
}
private Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//System.out.println("single from child");
}
});
}
In case, a mouseEvent needs to pass through multiplevel of containers, this link might be of interest.
If you elect to interpret double clicks, consider using the user's preferred interval, as suggested here.
Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
I think (as I know) that not is possible redirect Mouse event from child to its parent, just get parent from Component that is under the MouseCursor, or get parent from Component that's received Events from MouseClick
sure maybe someone can help you with that :-), but here is code which you needed for success with that
parent:
import java.awt.*;
import javax.swing.*;
public class PPanel extends JPanel {
private static final long serialVersionUID = 1L;
private APanel panel1;
private APanel panel2;
private APanel panel3;
public PPanel() {
setLayout(new GridLayout(0, 1));
panel1 = new APanel();
panel2 = new APanel();
panel2.setBackground(Color.yellow);
panel3 = new APanel();
panel3.setBackground(Color.green);
add(panel1);
add(panel2);
add(panel3);
setBackground(Color.blue);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
PPanel panel = new PPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(350, 300));
frame.setTitle("Demo");
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
}
Child:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
public class APanel extends JPanel {
private static final long serialVersionUID = 1L;
private Point pt;
public APanel() {
timer.setRepeats(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double from child");
pt = null;
timer.stop();
} else {
pt = e.getPoint();
timer.restart();
}
}
});
setBackground(Color.red);
setVisible(true);
}
private Timer timer = new Timer(400, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("single from child");
}
});
}
The menu is displayed on game startup and works fine, but once in game you can hit escape to bring up the menu again and this will cause the program to minimize. After I unminimize the game I can hit escape again and the menu screen will appear as intended. The return button also works as intended. What is going on here?
EDIT
Here is my SSCCE:
You will just need to add the imports and unimplemented methods for BullsEyePanel. I hope this helps!
public class Board {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int B_WIDTH = (int) dim.getWidth();
int B_HEIGHT = (int) dim.getHeight();
JFrame f = new JFrame("Children of The Ape");
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.pack();
f.setBackground(Color.BLACK);
f.setVisible(true);
f.setResizable(false);
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
// Change to full screen
gd.setFullScreenWindow(f);
if (gd.isDisplayChangeSupported()) {
gd.setDisplayMode(new DisplayMode(B_WIDTH, B_HEIGHT, 32, DisplayMode.REFRESH_RATE_UNKNOWN));
}
MenuPanel menu = new MenuPanel(f);
f.getContentPane().add(menu);
f.validate();
}
}
class BullsEyePanel extends JPanel implements MouseInputListener, ActionListener {
JFrame frame;
public BullsEyePanel(JFrame f) {
frame = f;
addKeyListener(new TAdapter());
setFocusable(true);
setVisible(true);
repaint();
}
private void openMenu() {
frame.getContentPane().add(new MenuPanel(this));
setVisible(false);
}
private class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == 27) {
openMenu();
}
}
}
}
class MenuPanel extends JPanel {
JButton btnExit;
JButton btnNewGame;
JFrame f;
BullsEyePanel panel;
MenuPanel(JFrame frame) { //this menu constructor is only called on program startup
f = frame;
setBackground(Color.black);
setFocusable(true);
btnNewGame = new JButton("New Game");
btnExit = new JButton("Exit");
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
add(btnNewGame);
add(btnExit);
setVisible(true);
}
MenuPanel(BullsEyePanel bullsEyePanel) { //this menu constructor is called when ESC is typed
f = bullsEyePanel.frame;
setBackground(Color.black);
setFocusable(true);
btnNewGame = new JButton("New Game");
btnExit = new JButton("Exit");
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
add(btnNewGame);
add(btnExit);
setVisible(true);
}
public class exitListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
}
public class newGameListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
f.getContentPane().add(new BullsEyePanel(f), BorderLayout.CENTER);
}
}
}
Instead of variant constructors, let the menu panel undertake its removal and restoration, as suggested below. See also this related example.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Board {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Board().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
JFrame f = new JFrame("Children of The Board");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.BLACK);
MenuPanel menu = new MenuPanel(f);
f.add(menu, BorderLayout.NORTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class MenuPanel extends JPanel {
private JButton btnExit = new JButton("Exit");
private JButton btnNewGame = new JButton("New Game");
private BullsEyePanel gamePanel;
private JFrame parent;
MenuPanel(JFrame parent) {
this.gamePanel = new BullsEyePanel(this);
this.parent = parent;
this.setBackground(Color.black);
this.setFocusable(true);
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
this.add(btnNewGame);
this.add(btnExit);
this.setVisible(true);
}
public void restore() {
parent.remove(gamePanel);
parent.add(this, BorderLayout.NORTH);
parent.pack();
parent.setLocationRelativeTo(null);
}
private class exitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
}
private class newGameListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
parent.remove(MenuPanel.this);
parent.add(gamePanel, BorderLayout.CENTER);
parent.pack();
parent.setLocationRelativeTo(null);
gamePanel.requestFocus();
}
}
}
class BullsEyePanel extends JPanel {
private MenuPanel menuPanel;
public BullsEyePanel(MenuPanel menu) {
this.menuPanel = menu;
this.setFocusable(true);
this.addKeyListener(new TAdapter());
this.setPreferredSize(new Dimension(320, 240)); // placeholder
this.setVisible(true);
}
private class TAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent code) {
if (code.getKeyCode() == KeyEvent.VK_ESCAPE) {
menuPanel.restore();
}
}
}
}