I'm trying to do a simple piece of homework, where I display a line of text displaying whether a door object is open or not. Underneath that, I visually represent it (using the drawRect) method. And at the bottom I have two buttons, which can open or close the door, thus changing the text and rectangle.
Edit: List of code that can be compiled given now:
import java.awt.BorderLayout;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test {
public static void main(String[] args) {
// Creates new JFrame called frame, with title "Door"
// (displayed at top of screen).
JFrame frame = new JFrame ("Door");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TempDoorPanel panel = new TempDoorPanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
class Door {
private String state;
private String message;
Door (String state) {
this.state = state;
message = "The door is currently closed.";
}
public boolean isOpen() {
return state.equals ("open");
}
public boolean isClosed() {
return state.equals ("closed");
}
public void setState(String state) {
this.state = state;
}
public String getMessage() {
return message;
}
public void open() {
if (state.equals("open")) {
message = "The door is already open.";
}
else {
state = "open";
message = "The door has been opened.";
}
}
public void drawOpenDoor (Graphics page) {
page.drawRect(100, 100, 100, 100);
}
}
class TempDoorPanel extends JPanel {
private Door door;
private JTextField currentStateOfDoor;
private JButton openDoor;
public TempDoorPanel() {
super.setLayout(new BorderLayout());
door = new Door("closed");
super.setBackground(Color.blue);
super.setPreferredSize(new Dimension (360, 400));
currentStateOfDoor = new JTextField(14);
currentStateOfDoor.setText(door.getMessage());
super.add(currentStateOfDoor, BorderLayout.NORTH);
openDoor = new JButton("Open Door");
class openDoorListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
door.open();
repaintText();
}
}
openDoorListener openlistener = new openDoorListener();
openDoor.addActionListener(openlistener);
JPanel holder = new JPanel();
holder.add(openDoor);
super.add(holder, BorderLayout.SOUTH);
}
private void repaintText() {
currentStateOfDoor.setText(door.getMessage());
// These methods are from Door class.
}
public void paintComponent (Graphics page) {
super.paintComponent(page);
if (door.isOpen())
door.drawOpenDoor(page);
// isOpen is a boolean method from Door class.
}
}
What works:
Buttons appear at right place on screen, at BorderLayout.SOUTH, one after the other.
The JTextField appears at right place, at BorderLayout.NORTH
Finally, the blue area appears in the right place in the centre of the screen.
What I'm trying to fix:
I have no idea how to display the rectangle properly in the middle of that blue area. I've tried changing the coordinates and size of the rectangle, which doesn't change the size of it at all. I can make it drawRect(100, 100, 100, 100) and it changes nothing.
I'm also aware that the rectangle is currently hidden behind the top left corner of the JTextField, but I can't figure out how to move it into the BorderLayout.
Questions:
How do you place a rectangle in a BorderLayout?
How do you adjust the size of a rectangle, drawn via drawrect(), in such a layout?
Because you add components to the JPanel you draw on the JTextField is covering your drawing.
Solution:
1) Either compensate for this by checking the JTextField height in your drawRect(..) method
or better
2) Dont add components to the same JPanel which you are drawing on unless it cant be helped.
So basically I made your TempDoorPanel add a new JPanel to BorderLayout.CENTER which is the drawing panel we can now use drawRect(0,0,10,10) and it will show in the top left hand corner of JPanel drawingPanel.
Also dont call setPreferredSize on JPanel rather override getPreferredSize() and return Dimensions which fit your drawings.
To invoke paintComponent outside of the class simply call repaint() its instance
See this example which uses point no.2:
import java.awt.BorderLayout;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Door");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
TempDoorPanel panel = new TempDoorPanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
}
}
class Door {
private String state;
private String message;
public Door(String state) {
this.state = state;
message = "The door is currently closed.";
}
public void drawOpenDoor(Graphics page) {
page.setColor(Color.GREEN);
page.drawRect(0, 0, 10, 10);
}
}
class TempDoorPanel extends JPanel {
private Door door;
private JTextField currentStateOfDoor;
private JButton openDoor;
public TempDoorPanel() {
super.setLayout(new BorderLayout());
door = new Door("closed");
currentStateOfDoor = new JTextField(14);
//AcurrentStateOfDoor.setText(door.getMessage());
super.add(currentStateOfDoor, BorderLayout.NORTH);
openDoor = new JButton("Open Door");
final JPanel drawingPanel = new JPanel() {
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
// if (door.isOpen()) {
door.drawOpenDoor(grphcs);
// }
// isOpen is a boolean method from Door class.
}
};
drawingPanel.setBackground(Color.blue);
add(drawingPanel);
class openDoorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
//door.open();
repaintText();
drawingPanel.repaint();//so paint component of drawing panel is called
}
}
openDoorListener openlistener = new openDoorListener();
openDoor.addActionListener(openlistener);
JPanel holder = new JPanel();
holder.add(openDoor);
super.add(holder, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
private void repaintText() {
// currentStateOfDoor.setText(door.getMessage());
// These methods are from Door class.
}
}
When you handler the door opening event with your listener;
class openDoorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
door.open();
repaintText();
}
}
you don't actually include a call to repaint the panel; hence the panel's paintComponent() method isn't called and door.drawOpenDoor() isn't called. You can test this by clicking the button and then resizing the frame. When you resize, the panel is automatically repainted and bingo, your door appears.
You can fix this by adding a call to repaint() in your ActionListener;
class openDoorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
door.open();
repaintText();
repaint(); // requests that the panel be repainted
}
}
Related
I have a JFrame, comprised of three JPanel containers, each panel has a filled-in circle (for example, red, white blue).
What I'd like to be able to do is update the color of the filled-in circle of that panel (make it darker with Color.RED.darker, for example) when that particular panel is clicked
I can't use an ActionListener, since panels aren't components but containers. I started out using MouseListener, but have now updated this to MouseAdapter. I am able to determine which JPanel was clicked - for testing purposes I'm printing out which panel was clicked to the console (for simplicity purposes I added a name to each panel).
EDIT: I got this mostly working - I can now repaint() the Jpanel that was clicked, making that cricle color darker, using the suggestion below of creating a setCircleColor (color) method, which calls repaint().This redraws the circle in that panel, using a darker color.
However, what I really also need to do is make the other two (non-clicked) cirlces on the other panels to repaint() with lighter colors.
But I can't see an easy way to handle this - how can I manipulate the other Jpanels that I didn't click on?
Here's my code:
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class TrafficLight {
// sets up the frame, calls the circle panels and adds them to the frame
public static void setUpGui() {
JFrame frame = new JFrame("Traffic Lights");
frame.setSize(300, 900);
frame.setLayout(new GridLayout(3, 0));
DrawCirclePanel redCircle = new DrawCirclePanel(Color.RED);
DrawCirclePanel yellowCircle = new DrawCirclePanel(Color.YELLOW);
DrawCirclePanel greenCircle = new DrawCirclePanel(Color.GREEN);
redCircle.setName("redCircle");
yellowCircle.setName("yellowCircle");
greenCircle.setName("greenCircle");
CircleListener cl = new CircleListener();
redCircle.addMouseListener(cl);
yellowCircle.addMouseListener(cl);
greenCircle.addMouseListener(cl);
frame.add(redCircle);
frame.add(yellowCircle);
frame.add(greenCircle);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String[] args) {
setUpGui();
}
}
// the DrawCirclePanel class creates a panel and
// draws a filled-in circle on the panel
class DrawCirclePanel extends JPanel {
Color c;
Border blackline = BorderFactory.createLineBorder(Color.black);
// constructor for panel, takes Color as argument
// so we know what color circle to make
public DrawCirclePanel(Color color) {
this.c = color;
this.setLayout(new GridLayout(1, 0));
this.setBorder(blackline);
}
// draws the circle in the panel
public void paintComponent(Graphics g) {
super.paintComponent(g);
int xWidth = this.getParent().getWidth();
g.setColor(c);
g.fillOval(1, 1, xWidth-1, xWidth-1);
}
public void setCircleColor(Color color) {
this.c = color;
this.getGraphics().setColor(c);
this.repaint();
}
}
class CircleListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
DrawCirclePanel cPanel = (DrawCirclePanel) e.getSource();
System.out.println(cPanel);
String name = cPanel.getName();
if (name == "redCircle") {
cPanel.setCircleColor(Color.red.darker());
}
else if (name == "yellowCircle") {
cPanel.setCircleColor(Color.yellow.darker());
}
else {
cPanel.setCircleColor(Color.green.darker());
}
}
}
So the answer turned out to be fairly simple.
Declare the panels with the circles as static variables so that the MouseListener class can access all three of the panels.
As Andrew Thompson noted, set up a setCircleColor method in DrawCirclePanel that repaints the circle with a different color as needed.
In the MouseListener class, determine with panel was called, then repaint all three of the circles, passing in the correct color - darker() or brighter() - as needed.
Here's the final code
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import java.awt.event.MouseEvent;
public class TrafficLight {
static DrawCirclePanel redCircle;
static DrawCirclePanel yellowCircle;
static DrawCirclePanel greenCircle;
// sets up the frame, calls the circle panels and adds them to the frame
public static void setUpGui() {
JFrame frame = new JFrame("Traffic Lights");
frame.setSize(300, 900);
frame.setLayout(new GridLayout(3, 0));
redCircle = new DrawCirclePanel(Color.RED.brighter().brighter());
yellowCircle = new DrawCirclePanel(Color.YELLOW.darker().darker());
greenCircle = new DrawCirclePanel(Color.GREEN.darker().darker());
redCircle.setName("redCircle");
yellowCircle.setName("yellowCircle");
greenCircle.setName("greenCircle");
CircleListener cl = new CircleListener();
redCircle.addMouseListener(cl);
yellowCircle.addMouseListener(cl);
greenCircle.addMouseListener(cl);
frame.add(redCircle);
frame.add(yellowCircle);
frame.add(greenCircle);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String[] args) {
setUpGui();
}
}
// the DrawCirclePanel class creates a panel and
// draws a filled-in circle on the panel
class DrawCirclePanel extends JPanel {
Color c;
Border blackLine = BorderFactory.createLineBorder(Color.BLACK);
// constructor for panel, takes Color as argument
// so we know what color circle to make
public DrawCirclePanel(Color color) {
this.c = color;
this.setLayout(new GridLayout(1, 0));
this.setBorder(blackLine);
}
// draws the circle in the panel
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int xWidth = this.getParent().getWidth();
g.setColor(c);
g.fillOval(0, 0, xWidth, xWidth);
}
// changes the color and calls repaint after a mouseClicked event
public void setCircleColor(Color color) {
this.c = color;
this.getGraphics().setColor(c);
this.repaint();
}
}
//abstract adapter class for receiving mouse events
class CircleListener extends MouseAdapter {
// determine which panel was clicked; redraws as brighter circle
// redraws other circles with dimmer (darker) color
public void mouseClicked(MouseEvent e) {
DrawCirclePanel cPanel = (DrawCirclePanel) e.getSource();
String name = cPanel.getName();
if (name.equals("redCircle")) {
TrafficLight.redCircle.setCircleColor(Color.RED.brighter().brighter());
TrafficLight.yellowCircle.setCircleColor(Color.YELLOW.darker().darker());
TrafficLight.greenCircle.setCircleColor(Color.GREEN.darker().darker());
} else if (name.equals("yellowCircle")) {
TrafficLight.redCircle.setCircleColor(Color.RED.darker().darker());
TrafficLight.yellowCircle.setCircleColor(Color.YELLOW.brighter().brighter());
TrafficLight.greenCircle.setCircleColor(Color.GREEN.darker().darker());
} else {
TrafficLight.redCircle.setCircleColor(Color.RED.darker().darker());
TrafficLight.yellowCircle.setCircleColor(Color.YELLOW.darker().darker());
TrafficLight.greenCircle.setCircleColor(Color.GREEN.brighter().brighter());
}
}
}
Im trying to change the color of a JPanel using the JColorChooser when the "apply" button is pressed, but i'm not sure how to actually make the color change. How would I do that?
private class SetColorAction implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
setColor(DrawnView.colorChooser.getColor());
//Color color;
}
}
^ is one in class while the stuff below is in a different one
public void setColor(Color color){
this.setBackground(color);
}
public ViewUserActions() {
this.applyColorBtn.setVisible(false);
this.discardChangesBtn.setVisible(false);
this.editBtn.addActionListener((ActionEvent ae) -> {
if (this.editBtn.isSelected()) {
this.applyColorBtn.setVisible(true);
this.discardChangesBtn.setVisible(true);
} else {
this.applyColorBtn.setVisible(false);
this.discardChangesBtn.setVisible(false);
}
});
this.applyColorBtn.addActionListener(new SetColorAction());
this.discardChangesBtn.addActionListener(new SetColorAction());
this.applyColorBtn.addActionListener(new GetInfoAction());
this.discardChangesBtn.addActionListener(new GetInfoAction());
}
Here is a short demo of changing the background color of a JPanel by a button click.
This cam also give you an idea of mcve , doing just that and nothing more:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Frame extends JFrame {
JPanel panel;
Color[] colors = new Color[] {Color.YELLOW, Color.CYAN, Color.LIGHT_GRAY, Color.WHITE};
int counter =0;
Frame() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JButton button = new JButton("Change color");
button.addActionListener( ae -> setColor());
add(button, BorderLayout.NORTH);
panel = new JPanel();
panel.add(new JLabel ("Test panel"));
add(panel, BorderLayout.CENTER);
pack();
setVisible(true);
}
private void setColor() {
panel.setBackground(colors[counter++]);
counter = (counter >= colors.length) ? 0 : counter;
}
public static void main(String[] args) {
new Frame();
}
}
Try this simple source code:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ColorChooserExample {
private static JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
runColorChangerApp();
}
});
}
private static void runColorChangerApp() {
frame = new JFrame();
frame.setTitle("JPanel Color Changer");
frame.getContentPane().setLayout(new GridLayout(1, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(400, 250, 400, 300);
frame.getContentPane().add(getHomePanel());
frame.setVisible(true);
}
private static JPanel getHomePanel() {
final JPanel panel = new JPanel();
panel.setOpaque(true);
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
//Fire on Mouse Right Click
if(evt.getButton() == MouseEvent.BUTTON3) {
frame.setTitle("Listened Right Click");
Color initColor = panel.getBackground();
Color choosedColor = JColorChooser.showDialog(panel,
"Choose JPanel Background Color", initColor);
frame.setTitle("JPanel Color Changer");
panel.setBackground(choosedColor);
}
}
});
return panel;
}
}
I am going to assume by the "apply" button, you mean the "ok" button of the JColorChooser dialog.
In that case, here is an optimal solution:
Color r = JColorChooser.showDialog(null, "Select Color for JPanel", Color.CYAN);
//null is the parent Component for the dialog,The String is the title, and cyan
//will be the initially selected Color.
if(r==null)
{ //perform whatever you would do if the user cancels the dialog }
else
{ jpanelobj.setBackground(r); }
This should do the trick, but here's my advice for you.
JColorChooser extends JComponent, and this means that IT CAN BE ADDED AS A COMPONENT to a Frame, giving you control such as adding ChangeListeners to instantaneously detect a Color change. Another method you may find helpful is:
JDialog jd=JColorChooser.createDialog(Component c,
String title,
boolean modal,
JColorChooser chooserPane,
ActionListener okListener,
ActionListener cancelListener);
Where c is the parent component-leave it null, usually.
The title is the dialogs Title modal is a boolean value which specifies whether you want the program to wait for the
the dialog to be responded to by the user before continuing the program thread
execution.
chooserPane is the JColorChooser you want as the main chooser->eg:
new JColorChooser(Color.GREEN);
okListener and cancelListener are action listeners for ok and cancel buttons.
This method gives you control over the dialogs buttons, display, etc.
I have a JFrame, and whenever I switch from one JFrame using a JButton it starts out normally, but whenever I create a new instance of the first JFrame, the JButton is in an incorrect location and is the wrong size.
Example on startup
and when another one is created
Code:
public class Menu extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
public static int Number_of_Participants = 0;
protected JPanel window = new JPanel();
double p;
private JButton Participants;
private Rectangle rParticipants;
protected int Button_width = 240;
protected int Button_height = 48;
boolean running = false;
Thread thread;
JFrame frame = new JFrame();
public Menu() {
window.setBackground(Color.BLUE);
frame.setSize(new Dimension(800, 600));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.getContentPane().add(window);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Image image = null;
try {
image = ImageIO.read(new File("res/BG.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
generateFiles();
drawButtons();
startMenu();
frame.repaint();
}
public void drawButtons() {
rParticipants = new Rectangle(520, 12, Button_width, Button_height);
Participants = new JButton("A");
Participants.setBounds(rParticipants);
window.add(Participants);
Participants.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
new Participant(Number_of_Participants);
}
});
}
}
Participant.java extends Menu.java
int Participant_ID;
public Participant(int Participant_ID) {
super();
this.Participant_ID = Participant_ID;
}
makes a JButton that goes back to Menu.java
As mentioned in the comment, your problem is most likely related to the call to setVisible(true). This should always be the LAST call in the constructor. Particularly, it should only be called AFTER all components have been added to the frame.
Apart from that, from the code that you posted, it seems like you want to switch through a seqence of frames, starting with a "main" menu, and then going through one frame for each "Participant". This intention could already be considered as questionable, because closing and disposing a JFrame just in order to create a new one does not seem to be very elegant. Most likely, a more elegant solution would be possible with a CardLayout : http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
However, some general hints:
Create the GUI on the Event Dispatch Thread
Don't extend JFrame. Instead, create a JFrame and fill it as needed
Don't implement Runnable with your top level class
Obey the standardJavaNamingConventions!
Don't try to do manual layouts with setBounds
This code is still not "beautiful", but at least shows how the goal of switching through several frames might be achieved, taking into account these points
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MenuExample
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
JPanel mainMenuPanel = new MainMenuPanel();
createAndShowFrame(mainMenuPanel);
}
});
}
static void createAndShowFrame(JPanel panel)
{
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(800, 600));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static JButton createNextParticipantButton(
final JComponent container, final int nextID)
{
JButton nextParticipantButton = new JButton("New Participant");
nextParticipantButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
Window window =
SwingUtilities.getWindowAncestor(container);
window.dispose();
ParticipantPanel participantPanel =
new ParticipantPanel(nextID);
createAndShowFrame(participantPanel);
}
});
return nextParticipantButton;
}
}
class MainMenuPanel extends JPanel
{
public MainMenuPanel()
{
setBackground(Color.BLUE);
add(MenuExample.createNextParticipantButton(this, 0));
}
}
class ParticipantPanel extends JPanel
{
private final int participantID;
public ParticipantPanel(int participantID)
{
this.participantID = participantID;
add(new JLabel("Add the contents for participant "+participantID));
add(MenuExample.createNextParticipantButton(this, participantID+1));
}
}
package com.spiralfive.inventory;
import java.awt.Font;
import java.awt.Panel;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.BorderLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
public class MainFile extends JApplet implements MouseListener {
// Declare the initial components
private JButton btnNewInventory;
private JButton btnMarkDown;
private JButton btnProcessSales;
private JButton btnActive;
private JButton btnStats;
private Panel mainPanel;
private Panel menuPanel;
private Panel inventoryPanel;
private Panel setactivePanel;
// Call the Initializer...
public void init() {
initComponents();
}
// Initialize the Main Components - Mostly Menu Items
private void initComponents() {
// Main Form Components
mainPanel = new Panel();
menuPanel = new Panel();
inventoryPanel = new Panel();
setactivePanel = new Panel();
btnNewInventory = new JButton("New Inventory");
btnActive = new JButton("Set Active");
btnMarkDown = new JButton("Mark Down");
btnProcessSales = new JButton("Process Sale");
btnStats = new JButton("Statistics");
// Enable Mouse Interactivity
btnNewInventory.addMouseListener(this);
btnMarkDown.addMouseListener(this);
btnProcessSales.addMouseListener(this);
btnActive.addMouseListener(this);
btnStats.addMouseListener(this);
// Set the Fonts
Font buttonFont = new Font("Arial", Font.PLAIN, 20);
// Apply Fonts To Menu
btnNewInventory.setFont(buttonFont);
btnMarkDown.setFont(buttonFont);
btnProcessSales.setFont(buttonFont);
btnActive.setFont(buttonFont);
btnStats.setFont(buttonFont);
// Set Panel Layout For Menu Items
menuPanel.setLayout(new java.awt.GridLayout(1,6));
// Add the Components
menuPanel.add(btnNewInventory);
menuPanel.add(btnActive);
menuPanel.add(btnMarkDown);
menuPanel.add(btnProcessSales);
menuPanel.add(btnStats);
// Add The Menu To the Main Panel
mainPanel.add(BorderLayout.NORTH, menuPanel);
// Make Inventory Load by Default
createPanels();
makeInvVisible();
// Set It All Visible
add(mainPanel);
}
// Create the Panels Used in this applet
public void createPanels() {
NewInventory inventoryPanel = new NewInventory();
inventoryPanel.setLayout(new java.awt.GridLayout(6,2));
mainPanel.add(BorderLayout.CENTER, inventoryPanel);
SetActive setactivePanel = new SetActive();
setactivePanel.setLayout(new java.awt.GridLayout(6,2));
mainPanel.add(BorderLayout.CENTER, setactivePanel);
}
public void makeInvVisible() {
inventoryPanel.setVisible(true);
mainPanel.repaint();
}
public void makeInvDisappear() {
inventoryPanel.setVisible(false);
mainPanel.repaint();
}
public void makeActiveVisible() {
setactivePanel.setVisible(true);
mainPanel.repaint();
}
public void makeActiveDisppear() {
setactivePanel.setVisible(false);
mainPanel.repaint();
}
public void mouseClicked(MouseEvent e) {
// Determine Which Button Has Been Clicked
JButton currentButton = (JButton)e.getComponent();
// New Inventory Button
if(currentButton == btnNewInventory) {
makeInvVisible();
makeActiveDisppear();
}
// Set Active Button
else if(currentButton == btnActive) {
makeActiveVisible();
makeInvDisappear();
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
I am using the code above attempting to make a new Panel() appear and the existing panel disappear when a button is clicked by using setVisible. However, I cannot get the Panel() to change. Nothing happens when the buttons are clicked, which are set to change setVisible to false on the current Panel and true on the requested Panel.
I am fairly certain it is because the panels are set a private in a different class (initComponents). How do I access the setVisible property on the panels? Or, is this even what's wrong?
Add
this.validate();
in the makeActiveVisible() method.
Swing components have a default state of being invalid and won't be painted to the screen unless validated (by calling the .validate() method on either the component itself or on one of the parent containers).
See also
repaint() in Java
I create a JPanel and added a few simple buttons with listeners attached to them. Then I decided to add an Image to the background of my panel, so I switched my JPanel to an ImagePanel. The buttons were working on JPanel, but now that I added a bunch of code for the background image to be displayed, the buttons no longer show. I did not change of any of the button adding code so I'm very confused as to why the buttons no longer show. This also happened in my separate GameFrame class. I added 2 rectangle components to a panel, then 3 buttons. For that panel, only the buttons show, despite the rectangles working before the buttons were added. Can I only have one type of JComponent per panel or something? I really do not understand why it's doing this. Thank you for your time.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TitleFrame extends JFrame
{
private ImagePanel panel;
private JButton mage;
private JButton rogue;
private JButton warrior;
private Image image;
public TitleFrame()
{
JFrame frame = new JFrame();
frame.setSize(1024, 768);
frame.setTitle("Title Screen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
createMageButton();
createRogueButton();
createWarriorButton();
ImagePanel panel = new ImagePanel(new ImageIcon("C:/Users/Derek Reitz/Documents/Eclipse Projects/GameApp/src/background.jpg").getImage());
panel.add(mage);
panel.add(rogue);
panel.add(warrior);
panel.paintComponent(frame.getGraphics());
frame.getContentPane().add(panel);
}
private void createRogueButton() {
rogue = new JButton("Select Rogue");
class AddButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
moveToNextFrame('r');
}
}
ActionListener listener = new AddButtonListener();
rogue.addActionListener(listener);
}
private void createWarriorButton() {
warrior = new JButton("Select Warrior");
class AddButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
moveToNextFrame('w');
}
}
ActionListener listener = new AddButtonListener();
warrior.addActionListener(listener);
}
private void createMageButton() {
mage = new JButton("Select Mage");
class AddButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
moveToNextFrame('m');
}
}
ActionListener listener = new AddButtonListener();
mage.addActionListener(listener);
}
public void moveToNextFrame(char c)
{
GameFrame game = new GameFrame(c);
}
class ImagePanel extends JPanel
{
private Image img;
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
}
You need to use a LayoutManager.
You should then be able to add your ImagePanel and buttons to the contentPane and have them all layed out and visible.
Try the follwoing:
JFrame frame = new JFrame();
frame.setTitle("Title Screen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createMageButton();
createRogueButton();
createWarriorButton();
ImagePanel panel = new ImagePanel(new ImageIcon(".../background.jpg").getImage());
panel.setLayout(new FlowLayout());
panel.add(mage);
panel.add(rogue);
panel.add(warrior);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
You set as layout null. That is a special case where absolute positions of the components are accepted. So use `setBounds(x, y, width, height). Better still use a real layout.
Another remark, you can take the image from the class path, say from out of the resulting .jar file):
URL url = getClass().getResource("/background.jpg");
... new ImageIcon(url);