I am new to programming, and created a little program to practice code. It is an authentication program where you type in a username and password, and only my specified username and password will work to make it show a picture. I typed all the code, and there was no error; but when I ran it and typed in the username and password, it failed to show the picture. Here is my code.
package main.Swing.com;
//imports
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.util.EventObject;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
//class that carries other classes and carries some variables
public class Main extends javax.swing.JFrame implements ActionListener, TextListener, InputMethodListener {
JButton Test = new JButton("TEST IF YOU HAVE ACCESS TO THIS");
JButton Cancel = new JButton("CANCEL");
JTextField username = new JTextField(15);
JTextField password = new JTextField(15);
String n = ("Nathan");
int nathannam;
int nathannamer;
JButton superman;
JButton supermanny;
//constructor class that has the jframe
public Main() {
super("Authenticator");
setSize(300, 220);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLookAndFeel();
//creating the pane and defining some labels
JPanel pane = new JPanel();
JLabel UsernameLabel = new JLabel("Username: ");
JLabel PasswordLabel = new JLabel("Password: ");
//adding all the components to the pane
pane.add(UsernameLabel);
pane.add(username);
pane.add(PasswordLabel);
pane.add(password);
pane.add(Test);
pane.add(Cancel);
//adding the pane
add(pane);
//adding a event listener to my JButton titled Test
Test.addActionListener(this);
//checking if the password variable and name variable are both
//correct by taking the values assigned to each of them later
//on in the code and adding them together and if they add together
//to the correct amount it should display a button, but it doesn't
//which is the problem I am having
if (nathannam + nathannamer == 24) {
ImageIcon superman = new ImageIcon("JButton.png");
JButton supermanny = new JButton(superman);
pane.add(supermanny);
}
//setting visibility to true
setVisible(true);
//end of constructor class
}
//start of class that checks if the username is correct
public void METHODPREFORMED(ActionListener evt) {
Object source = ((EventObject) evt).getSource();
//testing if username is equivalent to my name which is nathan
if (source == Test) {
String get = username.getText().toString();
String notation = "Nathan";
//if it is equivalent a variable will be assigned to nathanam
for (int i = 0; i < get.length(); i++) {
if (get.substring(i) == notation) {
int nathannam = 14;
//if it is not it will assign a wrong variable to nathannam
} else {
int nathannam = 15;
}
}
}
}
//testing if password variable is correct
public void ACTIONPREFORMED(ActionListener evt) {
Object source = ((EventObject) evt).getSource();
//testing if password is correct
if (source == Test) {
String got = password.getText().toString();
String notition = "iamnathan";
//if it is equivalent a variable will be assigned to nathanamer
for (int i = 0; i < got.length(); i++) {
if (got.substring(i) == notition) {
int nathannamer = 10;
//if it is not equivalent nathannamer will be assigned a wrong variable
} else {
int nathannamer = 15;
}
}
}
} //setting the nimbus setlookandfeel that was implemented in java 7
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//adding the main method
public static void main(String[] args) {
setLookAndFeel();
Main main = new Main();
}
#Override
public void textValueChanged(TextEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void caretPositionChanged(InputMethodEvent event) {
// TODO Auto-generated method stub
}
#Override
public void inputMethodTextChanged(InputMethodEvent event) {
// TODO Auto-generated method stub
}
}//end of program
You never call your test method from your implementation of actionPerformed(). Here's a much simplified version of your program that checks username when you click on TestAccess.
Going forward, see How to Use Password Fields for a working example of using JPasswordField.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
/**
* #see
*/
public class Test {
private final JTextField username = new JTextField(15);
private final JButton test = new JButton("Test access");
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, 1));
f.add(username);
test.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("nathan".equalsIgnoreCase(username.getText()));
}
});
f.add(test);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Test().display();
});
}
}
Related
I want to display a "loading message" when a process is started and I want to change the message when the process is finished. I tried to update the text from a JLabel before and after the thread with the process is started but the problem is that on the frame appears only the last update.
Here is my code:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyClass extends JFrame {
private JLabel loading;
private JButton jButton;
private JPanel jPanel;
public static void main(String[] args) {
new MyClass();
}
MyClass() {
jPanel = new JPanel();
setLayout(new GridLayout(0, 1));
loading = new JLabel("");
loading.setVisible(true);
jButton = new JButton("Click me!");
addActionToJButon();
setSize(300, 300);
jPanel.add(jButton);
jPanel.add(loading);
add(jPanel);
setVisible(true);
}
private void addActionToJButon() {
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
loading.setText("Loading....");
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i <= 1000000; i++) {
System.out.println(i);
}
}
}).start();
loading.setText("Done!");
}
});
}
}
I was expecting to appear the label "Loading..." once what the process is started and the message "Done" when the process is finished but I can't find out why on the frame appears the label with the message "Done!".
Thanks to JB Nizet advices I used SwingWorker and the code is working now.
Here is the correct code:
package view;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
public class MyClass extends JFrame {
private JLabel loading;
private JButton jButton;
private JPanel jPanel;
public static void main(String[] args) {
new MyClass();
}
MyClass() {
jPanel = new JPanel();
setLayout(new GridLayout(0, 1));
loading = new JLabel("");
loading.setVisible(true);
jButton = new JButton("Click me!");
addActionToJButon();
setSize(300, 300);
jPanel.add(jButton);
jPanel.add(loading);
add(jPanel);
setVisible(true);
}
private void addActionToJButon() {
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
loading.setText("Loading....");
swingWorker();
}
});
}
private void swingWorker() {
SwingWorker worker = new SwingWorker<String, String>() {
#Override
protected String doInBackground() throws Exception {
// TODO Auto-generated method stub
for (int i = 0; i <= 1000000; i++) {
System.out.println(i);
}
return "Done";
}
protected void done() {
try {
String finished = get();
loading.setText(finished);
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
worker.execute();
}
}
Because you are doing your "loading" within a thread, and you are setting your loading text outside the thread, you immediately set loading to "Done!" when you begin loading. What you want to do is set loading within your run() function like this:
private void addActionToJButon() {
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
#Override
public void run() {
loading.setText("Loading....");
// TODO Auto-generated method stub
for (int i = 0; i <= 1000000; i++) {
System.out.println(i);
}
loading.setText("Done!");
}
}).start();
}
});
}
I am having trouble getting my Image to display when I click my Jbutton, the test sysoutprint works but the Image does not. Any Ideas on what to do I am very lost! The Image is an easter egg for a school project, feel free to make comments. Should I use something besides a ImageIcon or what not?
Also if there are any other errors please let me know!
package GUI;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class mainView{
private static JFrame main; //main frame we add everything too
private static JPanel newGame; //panel for new game
private static JPanel dropDownPanel; //panel for the combobox
private static CardLayout clayout; //cardlayout for new game
private static JComboBox dropDown; //dropdown combobox
ImageIcon eastImg;
public void codeNameView(){
main = new JFrame("CodeNames");
main.setSize(600, 900);
main.setVisible(true);
//dropdown menu for quit and new game
String[] choice = {" " , "NewGame" , "Quit"};
dropDown = new JComboBox(choice);
//below is the panel where we add new game and quit options too
dropDownPanel = new JPanel();
dropDownPanel.setSize(100, 100);
dropDownPanel.add(dropDown);
main.getContentPane().add(dropDownPanel,BorderLayout.NORTH);
//easter egg
JButton easterButt = new JButton("Pass CSE 116");
JLabel eastLbl = new JLabel();
//added button to JLabel
eastLbl.add(easterButt);
try{
String path = "/Users/nabeelkhalid/git/s18semesterproject-b4-zigzag1/src/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(path);
}catch(Exception ex){
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(eastLbl);
eastLbl.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
eastLbl.setIcon(eastImg);
System.out.print("test");
}
//Ignore
#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
}
});
//action listener for dropdown combobox
dropDown.addActionListener(new ActionListener(){
/**
* Allows for the user to select New Game or Quit and have the game perform said action
*/
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JComboBox cb = (JComboBox) e.getSource();
Object selectedOption = dropDown.getSelectedItem();
if (selectedOption.equals("Quit")) {
main.dispose();
}else if(selectedOption.equals("NewGame")){
codeNameView();
System.out.print("yolo");
}
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
mainView x = new mainView();
// create a instance on mainview to run instead of using static methods
}
});
}
}
The primary issue seems to be right here
try{
String path = "/Users/nabeelkhalid/git/s18semesterproject-b4-zigzag1/src/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(path);
}catch(Exception ex){
System.out.print(ex);
}
The path is referencing a resource within the context of your src path. You should never reference src in your code, it won't exist once the program is exported (to a Jar or run on a different computer)
Instead, you should consider using Class#getResource to obtain a reference to the image and I'd personally use ImageIO.read over ImageIcon as a personal preference.
try{
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
}catch(Exception ex){
System.out.print(ex);
}
And, your next problem is, you're trying to add a JLabel to a JButton, expect, a JButton has not layout manager AND JButton already has support for display an image, so instead, you should be doing something more like...
JButton easterButt = new JButton("Pass CSE 116");
//JLabel eastLbl = new JLabel();
//added button to JLabel
//eastLbl.add(easterButt);
try {
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
} catch (Exception ex) {
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(easterButt);
easterButt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
easterButt.setIcon(eastImg);
}
});
You really should take a closer look at How to Use Buttons, Check Boxes, and Radio Buttons
Test Code
This is the code I used to test the solutions suggested above
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class mainView {
private static JFrame main; //main frame we add everything too
private static JPanel newGame; //panel for new game
private static JPanel dropDownPanel; //panel for the combobox
private static CardLayout clayout; //cardlayout for new game
private static JComboBox dropDown; //dropdown combobox
ImageIcon eastImg;
public void codeNameView() {
main = new JFrame("CodeNames");
main.setSize(600, 900);
//dropdown menu for quit and new game
String[] choice = {" ", "NewGame", "Quit"};
dropDown = new JComboBox(choice);
//below is the panel where we add new game and quit options too
dropDownPanel = new JPanel();
dropDownPanel.setSize(100, 100);
dropDownPanel.add(dropDown);
main.getContentPane().add(dropDownPanel, BorderLayout.NORTH);
//easter egg
JButton easterButt = new JButton("Pass CSE 116");
// JLabel eastLbl = new JLabel();
// //added button to JLabel
// eastLbl.add(easterButt);
try {
String path = "/GUI/MatthewPhoto.jpg";
eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
} catch (Exception ex) {
System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(easterButt);
easterButt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
easterButt.setIcon(eastImg);
}
});
//action listener for dropdown combobox
dropDown.addActionListener(new ActionListener() {
/**
* Allows for the user to select New Game or Quit and have the game
* perform said action
*/
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JComboBox cb = (JComboBox) e.getSource();
Object selectedOption = dropDown.getSelectedItem();
if (selectedOption.equals("Quit")) {
main.dispose();
} else if (selectedOption.equals("NewGame")) {
codeNameView();
System.out.print("yolo");
}
}
});
main.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.out.println("Hello");
mainView x = new mainView();
x.codeNameView();
// create a instance on mainview to run instead of using static methods
}
});
}
}
Try using something like this:
String path = "C:\\Users\\nabeelkhalid\\git\\s18semesterproject-b4-zigzag1\\src\\GUI\\MatthewPhoto.jpg";
I've tried many things to get this button bb or continue to output "Hey Buddy", yet it still does not work. It is displayed yet when i press it nothing happens. The code uses both java swing a awt.
package Game;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.util.concurrent.TimeUnit;
import javax.swing.JButton;
public class base extends java.applet.Applet implements ActionListener, TextListener {
//Graphics
//Graphics
#SuppressWarnings("deprecation")
public static JButton bb = new JButton("Continue");
public TextArea ta = new TextArea(30, 140);
TextArea tb = new TextArea(3, 130);
public int counter = 0;
//main class
public static void main(String[] args) {
Frame f = new Frame("---Quest---");
base ex = new base();
ex.init();
f.add("Center", ex);
f.pack();
f.show(true);
bb.addActionListener(ex);
}
public void actionPerformed1(ActionEvent Continue) {
bb.addActionListener(this);
counter++;
if (Continue.getSource() == bb && counter == 1) {
tb.append("Hey Buddy");
}
}
//graphics
public void init() {
bb.addActionListener(this);
Panel p;
setLayout(new BorderLayout());
p = new Panel();
ta.append("Hey");
bb.addActionListener(this);
p.add(bb);
p.add(ta);
p.add(tb);
p.setBackground(Color.blue);
ta.setBackground(Color.cyan);
ta.setEditable(false);
add("Center", p);
p.setVisible(true);
}
//time class
public static int nap(int time) {
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
//end of code
#Override
public void textValueChanged(TextEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
The whole code is buggy.Read the Comments inline.
1.Idk why you are adding actionListener to the button 4 times(Keep one)
2.You have to have to change the actionPerformed1 to actionPerfromed as you are implementing the ActionListener and assigning this to button's ActionListener
public TextArea ta = new TextArea(30, 140);
TextArea tb = new TextArea(3, 130);
public int counter = 0;
//main class
public static void main(String[] args) {
f.show(true);//show is deprecated use setVisible(true) instead;
bb.addActionListener(ex);//1
}
public void actionPerformed1(ActionEvent Continue) {//have to change the actionPerformed1 to actionPerfromed
bb.addActionListener(this);//2 What is this assigning inside actionPerformed Need to be removed
counter++;
if (Continue.getSource() == bb && counter == 1) {
tb.append("Hey Buddy");
}
}
//graphics
public void init() {
bb.addActionListener(this);//3
Panel p;
setLayout(new BorderLayout());
p = new Panel();
ta.append("Hey");
bb.addActionListener(this);//4
p.add(bb);
p.setVisible(true);//already called a show for JFrame why you want to set Visible of Panel
}
The following code opens a JInternalFrame when a button is clicked. But I want this window to be opened once, so if the user clicks that button again it will not open another frame instead it would bring to the front the window whether it is iconified, behind another window, etc. I have tried a couple of ways mainly using a counter, but the problems is once the frame is closed it doesn't open it again either. Is there another easy way to do this, cause I am not able to make it work properly. Thanks in advance.
Below is the code I am working on:
public class About implements ActionListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
int count =0;
MyInternalFrame frame;
public About(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
System.out.println(count);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
count += 1;
if(count == 1){
frame = new MyInternalFrame("SAD Imaging");
count +=1;
try {
in = new BufferedReader(new FileReader("SADInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Tarea = new JTextArea();
//System.out.println(file);
Tarea.setText(file);
Font f = new Font("TimesNewRoman", Font.ROMAN_BASELINE, 16);
Tarea.setFont(f);
Tarea.setBackground(Color.white);
Tarea.setAlignmentX(SwingConstants.CENTER);
Tarea.setEditable(false);
JPanel panel = new JPanel();
panel.add(Tarea);
panel.setBackground(Color.white);
//scroll = new JScrollPane(Tarea);
scroll = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.add(scroll);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
else if(count > 1){
try {
//frame.setIcon(true);
frame.setMaximum(true);
frame.toFront();
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Basically, you just need to check to see if the frame is null or not. If it is, you create an instance, if it's not, you bring it to the front, for example
#Override
public void actionPerformed(ActionEvent arg0) {
if (frame == null || (frame.getParent() == null && !frame.isIconifiable())) {
// Your exitsing code
} else {
frame.setIcon(false);
frame.setSelected(true);
frame.moveToFront();
}
You can also use an InteralFrameListener to the frame so you can detect when the frame is closed, so you null the internal reference, for example...
frame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
frame = null;
}
});
Updated with runnable example
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 java.beans.PropertyVetoException;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestInternalFrame {
public static void main(String[] args) {
new TestInternalFrame();
}
private JInternalFrame imageFrame;
private JDesktopPane desktop;
public TestInternalFrame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JMenu fileMenu = new JMenu("File");
JMenuItem newMenu = fileMenu.add("Show...");
newMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (imageFrame == null || imageFrame.isClosed()) {
imageFrame = new JInternalFrame("Image");
imageFrame.setIconifiable(true);
imageFrame.setMaximizable(true);
imageFrame.setClosable(true);
imageFrame.setResizable(true);
JLabel label = new JLabel(new ImageIcon("..."));
imageFrame.add(label);
imageFrame.pack();
desktop.add(imageFrame);
imageFrame.setLocation(0, 0);
imageFrame.setVisible(true);
}
try {
imageFrame.setIcon(false);
imageFrame.setSelected(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
imageFrame.moveToFront();
}
});
desktop = new JDesktopPane();
JMenuBar mb = new JMenuBar();
mb.add(fileMenu);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(mb);
frame.add(desktop);
frame.setSize(1200, 900);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I have strange problem with JPanel. I am trying to show svg image ( SVG_class extends JSVGCanvas from batik jar). Problem is when I start this program I get this
and when I resize with pointer frame a little I get normal picture like this
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import javax.swing.*;
import org.apache.batik.swing.JSVGCanvas;
public class Main {
static JScrollPane scrollpane;
// The frame.
protected JFrame frame;
public static void main(String[] args) {
final JFrame f = new JFrame("frame");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(700, 500);
f.setBackground(Color.blue);
SVG_class svg = new SVG_class();
JPanel p = new JPanel();
p.setSize(new Dimension(700, 500));
p.add(svg);
p.setBackground(Color.red);
scrollpane = new JScrollPane(p);
scrollpane.setPreferredSize(new Dimension(700, 500));
Container cont = f.getContentPane();
cont.add(scrollpane);
f.setVisible(true);
}
}
public class SVG_class extends JSVGCanvas {
private List<Type> list;
private int rad;
public boolean red_dot(int iX, int iY, String sX, String sY){
boolean b;
int x,y;
x=Math.abs(iX-(int)Double.parseDouble(sX));
y=Math.abs(iY-(getSize().height-(int)Double.parseDouble(sY)));
System.out.println("iX="+iX+" iY="+iY+" sX="+sX+" sY="+sY+" x="+x+" y="+y);
b=(x<=rad) &&(y<=rad);
return b;
}
public SVG_class(){
try {
this.list=CSV.getCSV("map2");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String fileName = "map2";
File file = new File("C:\\Users\\Gigabyte\\Desktop\\SVG\\"+fileName+".svg");
try {
this.setURI(file.toURL().toString());
this.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
//
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
boolean found=false;
// System.out.println("pritisnuo si x="+e.getX()+" y="+e.getY());
int x,y;
for(int i=0; i<list.size() && !found;i++ ){
found=red_dot(e.getX(), e.getY(), list.get(i).getX(), list.get(i).getY());
}
if (found) {
System.out.println("pritisao!!!!");
}
System.out.println(" ");
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can someone tell me what is mistake ? I tried with p.repaint but it didn't help.
Posting the source for SVG_class might make it easier to see what the problem is.
As it is, I suspect the problem is because you're not explicitly telling it what kind of layout to use.
If you want svg to take up the whole window you could do p.setLayout(new GridLayout(1, 1)); after you create p.
You should call the f.setSize(700, 500); just before showing.
SVG_class has probably set its size in the constructor. Don't do that and define the size at after calling the constructor.
EDIT: Try adding
f.pack();