Background color does not change in bluej - java

I have written a code that has a label and a button in a frame. I have also changed the background but it never changes.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class Frames
{
JFrame Main_Menu=new JFrame("MAIN MENU");JFrame CIRCUMFERENCE=new JFrame("CIRCUMFERENCE");
JFrame AREA=new JFrame("AREA");JFrame PERIMETER=new JFrame("PERIMETER");JFrame SETS=new JFrame("SETS");
JFrame FUNDAMENTAL_OPRATIONS=new JFrame("FUNDAMENTAL OPRATIONS");JFrame POWER_AND_ROOTS=new JFrame("POWER_AND_ROOTS");
void Main_Menu()
{
JPanel contentPane = (JPanel) Main_Menu.getContentPane();
contentPane.setLayout(new BorderLayout(10,10));
contentPane.setBorder(new EmptyBorder(300, 150, 300, 150));
contentPane.setLayout(new GridLayout(4, 4));
JPanel buttonPanel = new JPanel(new GridLayout(8,8));
contentPane.add(Labels.Main_MENU,BorderLayout.NORTH);
contentPane.add(Buttons.SETS,BorderLayout.SOUTH);
Main_Menu.setBackground(Color.YELLOW);
Main_Menu.pack();
Main_Menu.setVisible(true);
}
}

You should actually be setting the background color of the content pane via getContentPane().setBackground(Color.YELLOW):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Frames extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new Frames();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Frames() {
setSize(new Dimension(100, 100));
setTitle("MAIN MENU");
getContentPane().setBackground(Color.YELLOW);
setVisible(true);
}
}
Also, consider using variable naming conventions; for instance, Main_Menu should be named as mainMenu.

Related

Selecting JFrame without using 'this' command

public main() {
initComponents();
JPanel panel=new JPanel();
panel.setBounds(0, 0, 100, 100);
panel.setBackground(Jtrue);
this.add(panel);
}
I am able to add Jframe object using this command
However, when I write this in a separate method, I cannot add because the 'this' method is inside that object.
public void created(){
int degisken=1;
JPanel panel=new JPanel();
panel.setBounds(0, 0, 100, 100);
panel.setBackground(Jtrue);
this.add(panel);
}
How can I select that jframe instead of 'this'
I don't want to create a new jframe because there is already one
You should create you JFrame instance in a way that it will be visible in your whole class.
You can achieve this by declaring a JFrame as a private member of your class. Then you will be able to access it in all class methods:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JFrameDemo {
private JFrame frame;
public JFrameDemo() {
this.frame=new JFrame("Demo #1");
initComponents();
created();
}
private void initComponents() {
// Do your stuff here
}
public void created() {
int degisken = 1;
JPanel panel = new JPanel();
panel.setBounds(0, 0, 100, 100);
panel.setPreferredSize(new Dimension(640, 480));
panel.setBackground(new Color(255, 128, 112));
this.frame.getContentPane().add(panel);
this.frame.pack();
this.frame.setVisible(true);
}
public static void main(String[] args) {
JFrameDemo frameDemo = new JFrameDemo();
}
}
Another solution is that your class extends JFrame. This way, you will access the JFrame instance using the this keyword because this is your class and thus your JFrame:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JFrameDemo2 extends JFrame {
public JFrameDemo2() {
super("Demo #2");
initComponents();
created();
}
private void initComponents() {
// Do your stuff here
}
public void created() {
int degisken = 1;
JPanel panel = new JPanel();
panel.setBounds(0, 0, 100, 100);
panel.setPreferredSize(new Dimension(640, 480));
panel.setBackground(new Color(255, 128, 112));
this.getContentPane().add(panel);
}
public static void main(String[] args) {
JFrameDemo2 frameDemo = new JFrameDemo2();
frameDemo.pack();
frameDemo.setVisible(true);
}
}
Another remark: don't add your component directly on your JFrame but on the underlying container:
yourFrameInstance.getContentPane().add(yourComponentInstance)

JPanel's size in function of another JPanel

I would like to adjust the size of a JPanel in function of another panel which contains it.
When I run my code, the panel is tiny and centered on the top of the content panel.
So here's my code :
package test;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CodeForStackOverFlow {
public static void main(String[] args) {
Frame frame = new Frame();
}
}
class Frame extends JFrame {
private class Panel extends JPanel {
private JPanel content = new JPanel();
Panel() {
content.setBackground(Color.red);
this.add(content);
}
void adjustSize() {
this.content.setSize(new Dimension(this.getHeight(), this.getHeight()));
}
}
private Panel contentPane = new Panel();
Frame() {
this.setSize(new Dimension(500, 400));
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setContentPane(contentPane);
contentPane.adjustSize();
this.setVisible(true);
}
}

No output is shown

I made a frame and showing a JOptionPane on click of a button but my code is compiling but not generating any output.
I copy the JOptionPane content from -how to make Dialogs blog.
Here is my code:
No output is shown on screen.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class DialogDemo extends JFrame {
private static final long serialVersionUID = 1L;
private JButton btnNext =null;
private JPanel contentPane;
private JFrame frame = null;
public DialogDemo() {
initialize();
}
public void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(600, 335, 200, 150);
getContentPane();
getBtnNext().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame,"Eggs are not supposed to be green.");
}
});
}
public JPanel getContentPane() {
if (contentPane == null) {
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getBtnNext());
}
return contentPane;
}
public JButton getBtnNext() {
if (btnNext == null) {
btnNext = new JButton("Next");
btnNext.setBounds(20, 50, 150, 25);
}
return btnNext;
}
public static void main(String[] args) {
DialogDemo dd=new DialogDemo();
}
}
set visibility of frame to true :)
setVisible(true);
You forgot to set it visible.
Add this line:
setVisible(true);.
Without this, not frame will be displayed.

How to pass value JList item from JFrame into another JFrame (just value)?

I have write a test with two class.
The first JPanel, Gestion: JFrame with jlist + button (the button open the Jlist 2, PanelTest)
The second JPanel, PanelTest: JFrame and I want to recover in String, the select value item in the JFrame Gestion (JList)
How to do that ?
Gestion.java:
package IHM;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JList;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
public class Gestion extends JFrame {
private DocumentListener myListener;
public String test;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gestion frame = new Gestion();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public String getTest() {
return test;
}
/**
* Create the frame.
* #throws Exception
*/
public Gestion() throws Exception {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
final PanelTest panel2 = new PanelTest();
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
String choix[] = {" Pierre", " Paul", " Jacques", " Lou", " Marie"};
final JList list = new JList(choix);
panel.add(list);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
test = (String) list.getSelectedValue();
System.out.println(test);
// PanelTest.setValue(test);
}
});
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PanelTest().setVisible(true);
fermerFenetre();
}
});
panel_1.add(btnNewButton);
}
public void fermerFenetre(){
this.setVisible(false);
}
}
PanelTest.java
package IHM;
import java.awt.BorderLayout;
public class PanelTest extends JFrame {
public String tyty;
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PanelTest frame = new PanelTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PanelTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
textField = new JTextField();
contentPane.add(textField, BorderLayout.WEST);
textField.setColumns(10);
}
}
Suggestions:
Make your list variable a field, not a local variable, or else make it a final local variable so that it is accessible inside of the anonymous ActionListener.
Obtain the selected list item in your ActionListener where you launch the 2nd window.
Pass that String into your PanelTest object via a String parameter.
The second window should be a dialog such as a JDialog, not a JFrame.
As an aside, you'll rarely want to have your GUI classes extend top level windows such as JFrames or JDialogs as that greatly limits the flexibility of your GUI code.
For example,
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Gestion2 extends JPanel {
private static final String CHOIX[] = { " Pierre", " Paul", " Jacques",
" Lou", " Marie" };
private JList<String> choixList = new JList<>(CHOIX);
public Gestion2() {
JPanel listPanel = new JPanel();
listPanel.add(new JScrollPane(choixList));
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(new ListSelectAction("Select Item and Press")));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(listPanel);
add(btnPanel);
}
private class ListSelectAction extends AbstractAction {
public ListSelectAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
String selectedItem = choixList.getSelectedValue();
if (selectedItem != null) {
PanelTest2 panelTest2 = new PanelTest2(selectedItem);
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
// JOptionPane example
JOptionPane.showMessageDialog(win, panelTest2,
"JOptionPane Example", JOptionPane.PLAIN_MESSAGE);
// or JDialog example
JDialog dialog = new JDialog(win, "JDialog Example",
ModalityType.APPLICATION_MODAL);
dialog.add(panelTest2);
dialog.pack();
dialog.setLocationRelativeTo(win);
dialog.setVisible(true);
}
}
}
private static void createAndShowGui() {
Gestion2 mainPanel = new Gestion2();
JFrame frame = new JFrame("Gestion2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class PanelTest2 extends JPanel {
private String selectedItem;
private JTextField textField = new JTextField(10);
public PanelTest2(String selectedItem) {
this.selectedItem = selectedItem;
textField.setText(selectedItem);
add(new JLabel("Selected Item:"));
add(textField);
}
public String getSelectedItem() {
return selectedItem;
}
}

JPanel transition, what is wrong with my code?

I am new to java, and learning new things everyday.
Today i stumbled upon an error i just can not get fixed.
So i've got a JFrame with a JPanel inside, now I want to remove the Jpanel when i click on my Start game JLabel, and make it transition into my game JPanel ( for now i use a test JPanel)
JFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainMenu extends JFrame {
JPanel panel;
JFrame frame;
JButton playlabel;
public void mainmenu() {
frame = new JFrame();
panel = new JPanel();
playlabel = new JButton ("Nieuw Spel");
//frame
frame.setSize(new Dimension(800, 600));
frame.getContentPane().setBackground(new Color(14,36,69));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(frame.getMinimumSize());
frame.setVisible(true);
//panel
Dimension expectedDimension = new Dimension(690, 540);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setPreferredSize(expectedDimension);
panel.setMaximumSize(expectedDimension);
panel.setMinimumSize(expectedDimension);
panel.setBackground(new Color(14, 36, 69));
panel.add(playlabel);
playlabel.setAlignmentX(JComponent.CENTER_ALIGNMENT);
//playlabel
playlabel.setFont(new Font("Old English Text MT", Font.BOLD, 40));
playlabel.setBounds(250, 350, 50, 20);
playlabel.setForeground(new Color(217,144,39));
playlabel.setBackground(new Color(14,36,69));
playlabel.setBorderPainted(false);
playlabel.setFocusPainted(false);
playlabel.addActionListener(new PlayListener());
}
private class PlayListener extends JFrame implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel panelgame = Game.Game();
this.remove(panel);
this.add(panelgame);
this.revalidate();
}
}
}
Game class:
package labyrinthproject.View;
import java.awt.Color;
import javax.swing.JPanel;
public class Game {
public static JPanel Game(){
JPanel panel = new JPanel();
panel.setSize(690, 540);
panel.setBackground(new Color(255,36,69));
return panel;
}
}
if anyone could explain this to me why this doesn't work, it would be greatly appreciated!
Thank you very much!
Sincerely,
A beginner java student.
There are quite some issues in your code
Create the GUI on the event dispatch thread
Don't extend JFrame (you have three (three!) JFrames floating around there!)
Follow the naming conventions
Don't overuse static methods
Only store the instance variables that you really need to represent your class state
Don't use manual setSize or setBounds calls. Use a LayoutManager instead
The call to frame.setVisible(true) should be the last call, after the frame has been completely assembled
Consider a CardLayout for switching between panels ( http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html )
Slightly cleaned up, but the exact structure depends on what you actually want to achieve at the end:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainMenu extends JPanel
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainMenu = new MainMenu();
mainFrame.getContentPane().add(mainMenu);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
MainMenu()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Dimension expectedDimension = new Dimension(690, 540);
setPreferredSize(expectedDimension);
setBackground(new Color(14, 36, 69));
JButton newGameButton = new JButton ("Nieuw Spel");
newGameButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
newGameButton.setFont(new Font("Old English Text MT", Font.BOLD, 40));
newGameButton.setForeground(new Color(217,144,39));
newGameButton.setBackground(new Color(14,36,69));
newGameButton.setBorderPainted(false);
newGameButton.setFocusPainted(false);
newGameButton.addActionListener(new PlayListener());
add(newGameButton);
}
private class PlayListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
removeAll();
GamePanel gamePanel = new GamePanel();
add(gamePanel);
revalidate();
}
}
}
class GamePanel extends JPanel
{
GamePanel()
{
setBackground(new Color(255,36,69));
}
}
You should use a JButton and not a JLabel. Then:
you add to your JButton : Your_JB.addActionListener(this); (don't forget to implement ActionListener to your class).
Now, we are gonna add the detector:
#Override
public void actionPerformed(ActionEvent e){
Object src = e.getSource();
if(src == Your_JB){
panel.setVisible(false);
}
}
When you click the button, it will make your panel disapear.
Try this:
this.remove(panel);
this.validate();
this.repaint(); //if you use paintComponent
this.add(panelgame);
this.revalidate();
Swing is hard to making nice UI. You just need to use validate() after remove().
I hope it's helpfull.

Categories