PaintComponent not showing up - java

i'm currently adding functionality and completing a Hang-Man game my programing teacher made.
I added a frame to enable the user to write their own word to play the game however i stumbled on the following problem.
The PaintComponent that is supposed to draw when the user guesses the wrong word does not work. it does not draw when i guess the wrong word. (right now the word to guess is set to "hello" but i am going to change it after PaintComponent works).
i have tried to put all the components including the object to a JPanel but after i tried to do that the JFrame did not show upp after i pressed the button (b).
should i try with JPanel again or can i do anything to solve it as it currently is. i would like to point out that my teachers original code does not have the components put into a JPanel, he only has a frame. However his class extends with JPanel.
Anny suggestions ?
package hangtest2;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class HangTest2 {
public static void main(String[] args) {
// frame intro skärm
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HangMan");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3,1));
//label till orden
JLabel intro = new JLabel();
String ord = "Valfri";
intro.setText(ord);
Font font = new Font("Verdana", Font.BOLD, 25);
intro.setFont(font);
//till att välja ord
JTextField field = new JTextField(10);
field.setFont(font);
JButton b = new JButton("ok");
b.setBounds(370, 300, 100, 30);
frame.add(intro);
frame.add(field);
frame.add(b);
frame.setBackground(Color.white);
frame.setSize(600, 400);
frame.setVisible(true);
// frame hang
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame2 = new JFrame("HangMan");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setLayout(null);
JPanel p2 = new JPanel();
p2.setLayout(null);
JLabel hang = new JLabel();
String firstinstruct = "Gissa genom att Mata in en bokstav ";
hang.setText(firstinstruct);
Font font2 = new Font("Verdana", Font.BOLD, 10);
hang.setFont(font2);
hang.setBounds(70, 100, 600,150 );
JTextField field2 = new JTextField();
field2.setVisible(true);
field2.setSize(300, 30);
field2.setLocation(60, 300);
field2.setVisible(true);
JButton b2 = new JButton("ok");
b2.setBounds(370, 300, 100, 30);
frame2.add(b2);
frame2.add(field2);
frame2.add(hang);
frame2.setBackground(Color.white);
frame2.setSize(600, 400);
DynamicHangTest2 object = new DynamicHangTest2(field, field2, b, b2, frame, frame2);
b.addActionListener(object);
field.addActionListener(object);
b2.addActionListener(object);
field2.addActionListener(object);
frame2.add(object);
frame2.setVisible(false);
}
}
The Dynamic Class
package hangtest2;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DynamicHangTest2 extends JPanel implements ActionListener, MouseListener {
private int error;
public static String a = "hello";
JFrame frame, frame2;
JButton b,b2;
JTextField field, field2;
public DynamicHangTest2(JTextField field, JTextField field2, JButton b, JButton b2, JFrame frame, JFrame frame2) {
this.frame = frame;
this.frame2 = frame2;
this.b = b;
this.b2 = b2;
this.field = field;
this.field2 = field2;
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX() + " " + e.getY());
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source.equals(b)) {
frame.setVisible(false);
frame2.setVisible(true);
}
if (source.equals(b2)) {
if (!a.contains(field2.getText())) {
error++;
frame2.repaint();
}
field2.setText("");
}
}
public void paintComponent(Graphics g) {
if (error == 1)
g.drawLine(10, 270, 500, 270);
if (error == 2) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
}
if (error == 3) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
}
if (error > 3) {
Font font = new Font("Verdana", Font.BOLD, 25);
g.setFont(font);
g.drawString("GAME OVER", 270, 170);
}
}
}

Related

How to print a image on a contentpane(JPanel) in java swing

In the main class Practice extends JFrame, there are three classes UpperPanel, CenterPanel and LowerPanel that extend JPanel.
I'm going to put buttons on UpperPanel and LowerPanel, and put a image on CenterPanel, and print it in one frame.
However, when the image prints out, three Panels aren't printed. and when three Panels print out, the image isn't printed.
I think the problem is setContentPane(new ImagePanel()); when I enter this code (in CenterPanel), Only images are printed. The rest of the panels(Upper, Center, Lower) are not output.
(I have created a separate image output class(ImagePanel extends JPanel), but It's okay to delete this class. But I want to use paintComponent(Graphics g).
I'm sorry for my poor English, and Thank you for reading it
please help me
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Practice extends JFrame {
public int width = 480;
public int height = 720;
public Practice() {
setTitle("20201209");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
setSize(width,height);
c.add(new UpperPanel());
c.add(new CenterPanel());
c.add(new LowerPanel());
setVisible(true);
}
class UpperPanel extends JPanel {
public UpperPanel() {
JPanel UpperPanel = new JPanel();
UpperPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 25));
UpperPanel.setBackground(Color.MAGENTA);
UpperPanel.setBounds(0, 0, 480, 100);
getContentPane().add(UpperPanel);
JButton btnEnlarge = new JButton("1");
btnEnlarge.setFont(new Font("궁서체", Font.PLAIN, 20));
btnEnlarge.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
UpperPanel.add(btnEnlarge);
JButton btnReduce = new JButton("2");
btnReduce.setFont(new Font("바탕체", Font.ITALIC, 20));
btnReduce.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
UpperPanel.add(btnReduce);
JButton btnFit = new JButton("3");
btnFit.setFont(new Font("돋움체", Font.BOLD, 20));
btnFit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
UpperPanel.add(btnFit);
}
}
class CenterPanel extends JPanel{
public CenterPanel() {
JPanel CenterPanel = new JPanel();
CenterPanel.setLayout(null);
CenterPanel.setBackground(Color.YELLOW);
CenterPanel.setBounds(0, 100, 480, 500);
CenterPanel.setOpaque(true);
getContentPane().add(CenterPanel);
setContentPane(new ImagePanel()); // when I enter this code, Only images are printed. The rest of the panels(Upper, Center, Lower) are not output
}
}
class ImagePanel extends JPanel { //this class is for image printing on CenterPanel
private ImageIcon icon = new ImageIcon("images/1771211.jpg");
private Image img = icon.getImage();
public void paintComponent(Graphics g) { //I want to use this code
super.paintComponent(g);
g.drawImage(img, 10, 110, this);
}
}
class LowerPanel extends JPanel {
public LowerPanel() {
JPanel LowerPanel = new JPanel();
LowerPanel.setLayout(null);
LowerPanel.setBackground(Color.BLACK);
LowerPanel.setBounds(0, 600, 480, 120);
getContentPane().add(LowerPanel);
getContentPane().add(new MyButton());
}
}
class MyButton extends JLabel{ //this class is for a Button on LowerPanel
MyButton(){
JButton btn = new JButton("4");
btn.setBounds(10, 610, 460, 100);
btn.setHorizontalAlignment(SwingConstants.CENTER);
btn.setVerticalAlignment(SwingConstants.CENTER);
btn.setFont(new Font("돋움체", Font.BOLD, 50));
btn.setBackground(Color.WHITE);
btn.setForeground(Color.RED);
btn.setOpaque(true);
getContentPane().add(btn);
}
}
public static void main(String[] args) {
new Practice();
}
}
Don't extend JFrame class unnecessarily
Don't use a null/AbsoluteLayout rather use an appropriate LayoutManager
Don't call setBounds() or setSize() on components, if you use a correct layout manager this will be handled for you
Call JFrame#pack() before setting the frame to visible
All Swing components should be called on the EDT via SwingUtilities.invokeLater
Here is a small example of what you want to achieve
TestApp.java:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestApp {
BufferedImage image;
public TestApp() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGui() {
JFrame frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// load image
try {
image = ImageIO.read(new URL("https://i.stack.imgur.com/XNO5e.png"));
} catch (MalformedURLException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
}
// upper panel
JPanel upperPanel = new JPanel(); // JPanels use FlowLayout by default
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
upperPanel.add(button1);
upperPanel.add(button2);
upperPanel.add(button3);
// center panel
JPanel centerPanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
};
// lower panel
JPanel lowerPanel = new JPanel();
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
lowerPanel.add(button4);
lowerPanel.add(button5);
lowerPanel.add(button6);
frame.add(upperPanel, BorderLayout.NORTH); // JFrame uses BorderLayout by default
frame.add(centerPanel, BorderLayout.CENTER);
frame.add(lowerPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}

How do I create a JButton solely on one pane that prints "Hello

Every time I try to do this, it gives me an error that "Change Listener cannot be converted to Action Listener" and even if I implement ActionListener to the class... it still gives me another error
Is there a way to create a JButton only on the pane "Encryption" that when pressed prints "Hello"
This is my code:
import javax.swing.*;
import java.awt.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SwingDemo extends JFrame {
public static void main(String args[]) {
JFrame frame = new JFrame("Encryption/Decryption Software");
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel1, panel2;
panel1 = new JPanel();
panel2 = new JPanel();
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
tabbedPane.addTab("Encryption", panel1);
tabbedPane.addTab("Decryption ", panel2);
frame.add(tabbedPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(200,170, 500,250);
frame.setVisible(true);
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if(tabbedPane.getSelectedIndex() == 0){
panel1.removeAll();
panel1.setLayout(null);
JLabel initial_text = new JLabel("Enter text to be encrypted:");
JLabel final_text = new JLabel("Final text:");
JLabel key = new JLabel("Key:");
JTextField text_field = new JTextField(100);
JTextField key_field = new JTextField(100);
panel1.add(initial_text);
panel1.add(final_text);
panel1.add(key);
panel1.add(text_field);
panel1.add(key_field);
initial_text.setBounds(10, 20, 300, 50);
final_text.setBounds(10, 150, 600, 50);
key.setBounds(10, 58, 300, 50);
text_field.setBounds(178, 30, 230, 30);
key_field.setBounds(38, 72, 36, 25);
}
}
});
}
}
to detect a click you need to add an MouseListener no a ChangeListener
Like this
import java.awt.Color;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class SwingDemo extends JFrame {
public static void main(String args[]) {
JFrame frame = new JFrame("Encryption/Decryption Software");
JFrame frame = new JFrame("Encryption/Decryption Software");
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel1, panel2;
panel1 = new JPanel();
panel2 = new JPanel();
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
tabbedPane.addTab("Encryption", panel1);
tabbedPane.addTab("Decryption ", panel2);
frame.add(tabbedPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(200, 170, 500, 250);
frame.setVisible(true);
tabbedPane.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Hello");
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
}

JPanel won't show up in JFrame

Why does my JPanel not show in JFrame after button is clicked.
There's my code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.DefaultListModel;
import javax.swing.AbstractListModel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
public class Main {
private JFrame frame;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
{"1", "Marcin Zelek", "537573656"},
{"2", "Krzysztof Tomala", "324159103"},
{"3", "Zbigniew S", "324159104"},
},
new String[] {
"#", "Name", "Phone number"
}
));
table.getColumnModel().getColumn(1).setPreferredWidth(214);
table.getColumnModel().getColumn(2).setPreferredWidth(246);
table.setBounds(12, 103, 426, 185);
frame.getContentPane().add(table);
JButton btnDodajNowy = new JButton("Dodaj nowy");
btnDodajNowy.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
JPanel panel = new JPanel(null);// Creating the JPanel
panel.setBounds(0, 243, 286, 150);
panel.setVisible(true);
JButton button = new JButton("New button");
button.setBounds(12, 12, 117, 25);
panel.add(button);
frame.getContentPane().add(panel);
}
});
btnDodajNowy.setBounds(12, 30, 117, 25);
frame.getContentPane().add(btnDodajNowy);
JButton btnUsuZaznaczone = new JButton("Usuń zaznaczone");
btnUsuZaznaczone.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int[] selection = table.getSelectedRows();
for (int i = 0; i < selection.length; i++)
{
model.removeRow(selection[i]-i);
}
}
});
btnUsuZaznaczone.setBounds(141, 30, 204, 25);
frame.getContentPane().add(btnUsuZaznaczone);
}
}
Thanks.
You should use actionListener instead:
btnDodajNowy.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();// Creating the JPanel
panel.setBounds(0, 243, 286, 150);
JButton button = new JButton("New button");
button.setBounds(12, 12, 117, 25);
panel.add(button);
frame.getContentPane().add(panel);
frame.repaint();
}
});
and also:
You don't need to pass null as a parameter to the JPanel constructor
You might want to add a frame.repaint()
You don't need to set the JPanel to visible via setVisible().
If you looking to present the panel in same jframe where you added the button you probably should use CardLayout here is the link http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
It is being added, however, it is hiding below the JTable. The quickest fix is this:
public void mouseReleased(MouseEvent arg0) {
//...
panel.setBounds(0, 300, 286, 150); // 300 is on the y axis
//...
// then render the frame again:
frame.revalidate();
frame.repaint();
}
However, I suggest to rewrite it a little:
this.generalPanel = new JPanel();
frame.getContentPane().add(generalPanel);
...
generalPanel.add(table);
This way you'll get a good Layout for the topmost container.

why can't I draw any stuffs on Frame in java?

Coding is here.
I can't create any rectangle or circle inside frame.
the object of this project is to create converting celcius 2 Farenheit & Farenheit 2 Celcius.
so what I want is, please teach me to how to draw rectangle or oval in side the frame.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
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.JTextField;
public class C2F extends JComponent{
private double input1, output1;
private double input2, output2;
JPanel center = new JPanel();
JPanel top = new JPanel();
JPanel east = new JPanel();
JPanel south = new JPanel();
//for giving input & output
C2F(){
JFrame frame = new JFrame();
frame.setTitle("C2F");
frame.setSize(700,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.getContentPane().add(top,BorderLayout.NORTH);
frame.getContentPane().add(center,BorderLayout.CENTER);
frame.getContentPane().add(south,BorderLayout.SOUTH);
frame.getContentPane().add(east,BorderLayout.EAST);
frame.setVisible(true);
CC2F();
}
public void CC2F(){
//making frame
//give specific location
JLabel L1 = new JLabel("Please input Celcius or Fahrenheit to Convert");
top.add(L1);
JLabel l1 = new JLabel("Cel -> Fah");
south.add(l1);
JTextField T1 = new JTextField(12);
south.add(T1);
JButton B1 = new JButton("Convert");
south.add(B1);
JLabel l2 = new JLabel("Fah -> Cel");
south.add(l2);
JTextField T2 = new JTextField(12);
south.add(T2);
JButton B2 = new JButton("Convert");
south.add(B2);
//to create buttons and labels to give an answer
B1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
input1 = Double.parseDouble(T1.getText());
output1 = input1 *(9/5) + 32;
T2.setText(""+output1);
repaint();
}
});
B2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
input2 = Double.parseDouble(T2.getText());
output2 = (input2 - 32)/9*5;
T1.setText(""+output2);
}
});
//making events
//placing the buttons and labels
output1 = 0;
output2 = 0;
//initialize the value
}
public void paintComponent(Graphics g) {
//error spots. it compiles well. But this is not what I want.
super.paintComponent(g);
Graphics2D gg = (Graphics2D) g;
gg.setColor(Color.BLACK);
gg.drawOval(350, 500,12,12);
gg.setColor(Color.RED);
gg.fillRect(350, 500, 10,(int) output1);
gg.fillOval(350, 500, 10, 10);
gg.setColor(Color.RED);
gg.fillRect(350, 500, 10,(int) output2);
gg.fillOval(350, 500, 10, 10);
//to draw stuffs
}
public static void main(String[] args)
{//to run the program
new C2F();
}
}
You never actually add C2F to anything that would be able to paint it, therefore your paint method will never be called.
You should override paintComponent instead of paint, as you've broken the paint chain for the component which could cause no end of issues with wonderful and interesting paint glitches. Convention would also suggest that you should call super.paintComponent (when overriding paintComponent) as well before you perform any custom painting
See Painting in AWT and Swing and Performing Custom Painting for more details
As a general piece of advice, I'd discourage you from creating a frame within the constructor of another component, this will make the component pretty much unusable again (if you wanted to re-use it on another container for example)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
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.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class C2F extends JComponent {
public C2F() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
TestPane center = new TestPane();
JPanel top = new JPanel();
JPanel east = new JPanel();
JPanel south = new JPanel();
//give specific location
JLabel L1 = new JLabel("Please input Celcius or Fahrenheit to Convert");
top.add(L1);
JLabel l1 = new JLabel("Cel -> Fah");
south.add(l1);
JTextField T1 = new JTextField(12);
south.add(T1);
JButton B1 = new JButton("Convert");
south.add(B1);
JLabel l2 = new JLabel("Fah -> Cel");
south.add(l2);
JTextField T2 = new JTextField(12);
south.add(T2);
JButton B2 = new JButton("Convert");
south.add(B2);
//to create buttons and labels to give an answer
B1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double input1 = Double.parseDouble(T1.getText());
double output1 = input1 * (9 / 5) + 32;
T2.setText("" + output1);
center.setOutput1(output1);
}
});
B2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double input2 = Double.parseDouble(T2.getText());
double output2 = (input2 - 32) / 9 * 5;
T1.setText("" + output2);
center.setOutput2(output2);
}
});
//making events
frame.getContentPane().add(top, BorderLayout.NORTH);
frame.getContentPane().add(center, BorderLayout.CENTER);
frame.getContentPane().add(south, BorderLayout.SOUTH);
frame.getContentPane().add(east, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private double output1, output2;
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 600);
}
public void setOutput1(double output1) {
this.output1 = output1;
repaint();
}
public void setOutput2(double output2) {
this.output2 = output2;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.drawOval(350, 500, 12, 12);
g2d.setColor(Color.RED);
g2d.fillRect(350, 0, 10, (int) output1);
g2d.fillOval(350, 0, 10, 10);
g2d.setColor(Color.BLUE);
g2d.fillRect(350, 0, 10, (int) output2);
g2d.fillOval(350, 0, 10, 10);
g2d.dispose();
}
}
public static void main(String[] args) {//to run the program
new C2F();
}
}

My image disappear when i run jar file

well here are the classes i made..
package testdnevnik;
import javax.swing.JFrame;
public class Diary {
StartWindow startWindow = new StartWindow();
static JFrame frame = new JFrame("Diary");
int n = 0;
public Diary() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
//frame.add(new ImagePanel("Img//bg2.jpeg"));
frame.setVisible(true);
frame.add(startWindow);
startWindow.checkStudents(n);
startWindow.chooseOption();
}
public static void main(String[] args) {
new Diary();
}
}
that was the main class,and here is the panel for the start window..
package testdnevnik;
import java.awt.BorderLayout;
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.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import static testdnevnik.Diary.frame;
public class StartWindow extends JPanel {
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JLabel headline = new JLabel();
JButton viewStudents = new JButton();
JButton editStudents = new JButton();
JButton addStudents = new JButton();
JButton removeStudents = new JButton();
JLabel usernameLbl = new JLabel();
JLabel passwordLbl = new JLabel();
JTextField usernameFld = new JTextField();
JPasswordField passwordFld = new JPasswordField();
JButton logIn = new JButton("Log In");
JButton signUp = new JButton("Sign Up");
public StartWindow () {
jp.setLayout( new BorderLayout() );
// headline
headline.setText("Diary");
headline.setLocation(200, 30);
headline.setHorizontalAlignment(JLabel.CENTER);
headline.setFont(new Font("Serif", Font.BOLD, 60));
headline.setForeground(Color.ORANGE);
headline.setSize(300, 80);
headline.setVisible(true);
// Buttons
//View Students - Button
viewStudents.setText("View All Students");
viewStudents.setSize(200,40);
viewStudents.setLocation(70 , 200);
viewStudents.setVisible(true);
// Edit Students - Button
editStudents.setText("Edit Students");
editStudents.setSize(200,40);
editStudents.setLocation(70 , 300);
editStudents.setVisible(true);
// Add Students - Button
addStudents.setText("Add New Students");
addStudents.setSize(200,40);
addStudents.setLocation(70 ,400);
addStudents.setVisible(true);
// Remove Students - Button
removeStudents.setText("Remove Students");
removeStudents.setSize(200,40);
removeStudents.setLocation(70 , 500);
removeStudents.setVisible(true);
// username and password labels and input field
usernameLbl.setText("Username: ");
usernameLbl.setBounds(320, 200, 108, 40);
usernameLbl.setFont(new Font(null,Font.BOLD, 20));
usernameLbl.setVisible(true);
usernameFld.setBounds(450, 205, 200, 30); // username field input
usernameFld.setVisible(true);
passwordLbl.setText("Password: ");
passwordLbl.setBounds(320, 300, 108, 40);
passwordLbl.setFont(new Font(null,Font.BOLD, 20));
passwordLbl.setVisible(true);
passwordFld.setBounds(450, 305, 200, 30); // password field input
passwordFld.setVisible(true);
// button for log in and sign up
logIn.setBounds(580, 400, 70, 40);
logIn.setVisible(true);
signUp.setBounds(480, 400, 90, 40);
signUp.setVisible(true);
// panel
jp.setSize(new Dimension(800,600));
jp.add(viewStudents); // add ViewStudents button to the panel
jp.add(editStudents); // add EditStudents button to the panel
jp.add(addStudents); // add AddStudents button to the panel
jp.add(removeStudents); // add RemoveStudents button to the panel
jp.add(usernameLbl); // username label
jp.add(passwordLbl); // password label
jp.add(usernameFld); // username input field
jp.add(passwordFld); // password input field
jp.add(logIn); //add log in button to the panel
jp.add(signUp); //add sign up button to the panel
jp.add(headline); // add headline label to the panel
jp.add(new ImagePanel("Img//bg2.jpg")); // add background image to the panel
// adding panel to the frame
frame.add(jp);
validate();
}
public void checkStudents(int n) {
int numberOfStudents = n;
if (numberOfStudents == 0) {
removeStudents.setEnabled(false);
}
}
public void chooseOption() {
viewStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "view students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
editStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "edit students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
addStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "add students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
removeStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "remove students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
logIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "succesful log in", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
signUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "sign up form", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
and here is the class for the image background
package testdnevnik;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
when i run the program from the NetBeans everything is ok,running perfectly,but when i click "Clean and Build Project" in NetBeans and run from the jar file in the folder,the background is white but the components added to the panel are fine,just the image for the background disappearing,why??

Categories