Java Swing Button not working - java

So I'm making a program that prints out a square brick and a triangular roof. The panel has a background that shows the sky and some grass. Everything seems to be working fine except the buttons that work, when I click the brick button nothing happens. I've tried remodelling the code but no progress.
Here's the program code:
package someapp;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
*
* #author Drew
*/
class Someapp extends JFrame implements ActionListener{
private Graphics land;
private JButton bricks;
private JButton roof;
JButton b1;
JLabel l1;
JLabel background;
public Someapp()
{
setTitle("Buil Your Dream Home");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
background=new JLabel(new ImageIcon("C:\\Users\\Sharon Umute\\Documents\\NetBeansProjects\\someapp\\src\\someapp\\blue-sky.png"));
add(background);
background.setLayout(new FlowLayout());
bricks=new JButton("Bricks");
roof=new JButton("Roof");
background.add(bricks);
background.add(roof);
bricks.addActionListener(this);
}
public static void main(String[] args) throws IOException {
// TODO code application logic here
Someapp frame=new Someapp();
frame.setSize(1280, 735);
frame.setLocation(40, 0);
frame.createGUI();
frame.setVisible(true);
frame.setTitle("Build Your Dream Home");
}
private void createGUI() throws IOException{
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window=getContentPane();
window.setLayout(new FlowLayout());
window.add(new JPanelWithBackground("wIcon"));
BufferedImage wPic = ImageIO.read(this.getClass().getResource("blue-sky.png"));
JLabel wIcon = new JLabel(new ImageIcon(wPic));
}
#Override
public void actionPerformed(ActionEvent e) {
{
Graphics paper=background.getGraphics();
paper.drawRect(500, 700, 100, 100);
paper.setColor(Color.red);
}
throw new UnsupportedOperationException("Not supported yet.");
//To change body of generated methods, choose Tools | Templates.
}
}

Related

Stack overflow error GUI programming

I have a big problem i tried to solve it for days. I programmed a little program but it doesn't work.The error is Stackoverflow I already searched this website on and on again .I broke it down to the part wich doesn't works so here is the code.
This is the frame:
package snippet;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyFrame extends JFrame {
JButton button;
JLabel label;
TextEdit textEdit = new TextEdit();
public void LetsGo() {
setBounds(0, 0, 800, 510);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Game");
setResizable(false);
setLocationRelativeTo(null);
//Labels
label = new JLabel();
label.setText("Change Me");
label.setBounds(30, 25, 200, 50);
label.setVisible(true);
add(label);
button = new JButton();
button.setText("I Will Change A Text");
button.setBounds(30, 130, 200, 400);
button.addActionListener(new Listener());;
add(button);
}
public class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
textEdit.editTheText();
}
}
And this object should edit the Text :
package snippet;
public class TextEdit {
MyFrame frame = new MyFrame();
public void editTheText(){
frame.label.setText("Text was edited");
}
}
So the real code is much more complex so i won't put all in one Object
Would be great if i receive some help would be very very thankful for that
You are creating a new MyFrame in TextEdit, which I don't think is what you want to do because frame.label will be null.
What you really should be doing is assigning the JFrame inside of Listener.
public class Listener implements ActionListener {
private JFrame frame;
public Listener(JFrame frame) {
this.frame = frame;
}
#Override
public void actionPerformed(ActionEvent e) {
if (this.frame.label != null) {
this.frame.label.setText("Text was edited");
}
}
}
Then for the the other code, you don't have a constructor or your actual class is called LetsGo?
Assuming it is not called LetsGo and it actually is MyFrame, you need an actual constructor.
public MyFrame() {
LetsGo();
}
Then in the LetsGo method, add the frame to the Listener
button.addActionListener(new Listener(this));

Placing button on top of image

I am back again. I was wondering how I would go about placing a button on top of an image in a GUI. Here is my current code:
private static JPanel titlePanel = new JPanel();
private static JLabel titleScreen = new JLabel();
private static JLabel titleScreenBackground = new JLabel();
private static JButton startGameButton = new JButton("START GAME");
private static ImageIcon titleScreenPic = new ImageIcon("http://icdn6.digitaltrends.com/image/battleship-650x0.jpg");
private static JFrame frame=new JFrame(); //creates frame
public static void main(String[] args) throws MalformedURLException{
titleScreen();
}
public static void titleScreen() throws IOException{
titleScreen.setLayout(new GridBagLayout());
titlePanel.setLayout(new GridBagLayout());
GridBagConstraints c1 = new GridBagConstraints();
c1.gridx = 0;
c1.gridy = 0;
c1.anchor = GridBagConstraints.PAGE_END;
titleScreenBackground.setIcon(titleScreenPic);
titlePanel.add(startGameButton);
titlePanel.setAlignmentY(SwingConstants.BOTTOM);
frame.add(titleScreenBackground);
frame.add(titlePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(630, 300); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
I tried to make the panel a gridbaglayout so I could place the components in the same cell, but it still places the image first and then the button directly next to it.
EDIT: I have redone the code, making it do somewhat what I wanted. As you can see, the line where I try to set the location of the button does not do anything to the button.
how I would go about placing a button on top of an image in a GUI.
If you want to place a Swing button on top of an image then you need to follow 2 steps.
set a layout manager for the label containing the image.
add the button to the label (not the panel).
See Background Panel for more information and examples.
Edit:
To center a component the easiest approach is:
label.setLayout( new GridBagLayout() );
label.add(button, new GridBagConstraints());
If you want button on the image you can just use image in paint method of JPanel.
Example (with resource im
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestFrame extends JFrame {
BackgroundPane bgPane;
private JButton startButton;
public TestFrame() {
super();
initComponents();
}
private void initComponents() {
try {
URL url = getClass().getResource("battleship-650x0.jpg");
BufferedImage image = ImageIO.read(url);
bgPane = new BackgroundPane(image);
bgPane.setLayout(new GridBagLayout());
startButton = new JButton("Start");
bgPane.add(startButton);
setContentPane(bgPane);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
TestFrame frame = new TestFrame();
frame.setVisible(true);
}
class BackgroundPane extends JPanel {
Image image;
public BackgroundPane(Image backGroundImage) {
super();
image = backGroundImage;
setPreferredSize(new Dimension(image.getWidth(this), image.getHeight(this)));
}
#Override
public void paint(Graphics g) {
super.paint(g);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
}

Background color does not change in bluej

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.

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.

How can we add JScrollPane on JTextArea in java?

Can anybody tell me what is the problem in following program? I want to fit JScrollPane on JtextArea but when I add it then JTextArea is not visible.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Area extends JFrame
{
private JTextArea ta;
private JTextField tf;
JScrollPane jp;
public Area()
{
super("Text Area");
tf=new JTextField();
tf.setBounds(100,350,300,30);
add(tf);
ta=new JTextArea();
ta.setBounds(100,100,300,200);
jp= new JScrollPane(ta);
add(jp);
setLayout(null);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String...s)
{
new Area();
}
}
I see several problems:
Don't use a null layout; do use a real layout.
The default layout of JFrame is BorderLayout; the default position is CENTER; only one component can occupy a position at a time; the example below uses NORTH & CENTER.
Use the appropriate constructor parameters to size the text components initially.
The scrollbar will appear automatically whenever the scrollpane is smaller than the enclosed component; resize the frame to see the effect.
As shown here, the frame's size is made smaller for effect.
See also Initial Threads.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/** #see https://stackoverflow.com/a/19215436/230513 */
public class Area extends JFrame {
public Area() {
super("Text Area");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField tf = new JTextField(12);
add(tf, BorderLayout.NORTH);
JTextArea ta = new JTextArea(24, 12);
JScrollPane jp = new JScrollPane(ta);
add(jp, BorderLayout.CENTER);
pack();
// arbitrary size to make vertical scrollbar appear
setSize(240, 240);
setLocationByPlatform(true);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Area();
}
});
}
}
Try this:
public Area()
{
super("Text Area");
tf=new JTextField();
tf.setBounds(100,350,300,30);
add(tf);
ta=new JTextArea();
jp= new JScrollPane(ta);
jp.setBounds(5, 5, 100, 100);
add(jp);
setLayout(null);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
You have to use setBounds on JScrollPane, not on JTextArea
sounds like its added but its not shown because of the policy try this:
jp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

Categories