replacing one jpanel with another jpanel - java

I want to replace the current panel and call another panel in JPanel forms.
I try to do using setContentPane() and getContentPane() method but it gives error.
how can I do that....
I also try this but clear all the componens but do not add anything
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
if (new ConnectionFactory().userLoginCheck(usernameText.getText(), new String(passwordText.getPassword()))) {
removeAll();
add(new ChangeUsernamePassword());
revalidate();
repaint();
//new Welcomeboard();
} else {
warningLabel.setText("Invalid Username Or Password!!!");
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(DashboardPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DashboardPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}

"I want to replace the current panel and call another panel in JPanel forms"
Instead of trying to add an remove panels, use a CardLayout. Seeing how you're using Netbeans GUI Builder, see How to Use CardLayout with Netbeans GUI Builder. What the CardLayout does is allow you to change between different views without having to add and drop panels, which can be troublesome.
Also you may want to debug your if statement. Hard to tell with only the little but of code you're showing.

Related

JFrame looks different depending on how its loaded

I have a JFrame:
public class Help extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Help frame = new Help();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Help() {
setDefaultCloseOperation(JFrame.DISPOSE_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);
}
}
If i run this in Eclipse i get the following:
Now if call this from the ActionListener of a JButton within another JFrame using:
btnHelp.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Help frame = new Help();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
Then the JFrame loads looking like this:
This looks ugly to me. Why isn't the first style loading when i initialize the JFrame from within another JFrames JButton ActionListener? It seems to me like i'm running exactly the same code with both methods of loading it.
This particular segment of code:
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
e.printStackTrace();
}
Changes what we call the look & feel of the JFrame. This includes everything from button graphics, animations to sizes and proportions of default sized components in the frame. The look and feel must be set before the JFrame is drawn onto the screen and changing it around mid-program can be quite tricky. As such, I believe your second invocation from the actionListener happens either without the presence of the look at feel code or happens before the setting of the look and feel.
Since it is a "global" attribute (that is, it affects all frames in the running program) I personally put it as the first statement in my main() method as to protect against any sort of potential accidental creations of frames before the statement is invoked.
Please note though, without setting the look and feel, java assumes a default cross-platform view which stays constant across all operating systems. UIManager.getSystemLookAndFeelClassName() changes this behavior to allow for a system-specific L&F. You may need to take this in mind when distributing the program across OSes as with a system-specific L&F, fine-tuned layouts may be destroyed due to differing component sizes.
In your second example, the new JFrame will have the same look and feel as the other JFrames in the application.
Your comments indicate that you are not setting the look and feel for that application.
Use a line similar to the one in your first example to do this.

How to open an image using Imageicon on a jframe

I am trying to simply draw an image on a jframe by using an Imageicon. However when I run it its just blank. Heres my code...
public final class PICS
{
public static final void main(String... aArgs)
{
JFrame frame = new JFrame("IMAGE");
frame.setVisible(true);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );
}
}
I am very new to everything java including this website, so I apologize if im missing something. Also im using Eclipse, and are there specific formats you can use for images, or is there a limit to size?
I am very new to everything java including this website
Then I would suggest you start by reading tutorials especially the Swing tutorial. Maybe the section on How to Use Icons would be a good place to start. The example code will show you how to use Icons as well as how to structure your program so that the GUI code is executed on the EDT. The tutorial on Concurrency will explain why the EDT is important.
Two things.
First, make setVisible the last call AFTER you have built your frame and it's contents...ie
JFrame frame = new JFrame("IMAGE");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );
// Make me last
frame.setVisible(true);
Two, make sure that the image/pic1.jpg exists and is the directory image under the current execution context.
If the image is a embedded resource (lives within the Jar or your application), then you need to supply a URL to the image instead of a String as ImageIcon treats String as a file name...
ImageIcon image = new ImageIcon(PICS.class.getResource("image/pic1.jpg"));
For example.
I would encourage you to use JFrame#pack over JFrame#setSize as it will resize the frame to the preferred size of your content...
I would also encourage you to take the time to read through Code Conventions for the Java Programming Language, Initial Threads.
I would also encourage you to use ImageIO over ImageIcon as it will, at least, throw an Exception if something goes wrong
Updated, testing image path
Try adding this to the constructor of your PICS class. This will, at least, tell you where the image isn't...
try {
ImageIO.read(PICS.class.getResource("image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in /image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("resources/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in resources/image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("/resources/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in /resources/image/pic1.jpg");
}

Image does not appear in JPanel using BufferedImage

I have a GUI with a created JPanel and a "Start" button. All I need is when I click "Start", an image will be loaded and appear on that JPanel.
But my problem is when I click "Start", nothing happens.
Can anyone help me fix this problem?
Here is my code:
private BufferedImage image;
public class ImagePanel extends JPanel {
public ImagePanel() {
try {
image = ImageIO.read(new File("C:\\Users\\HienTran\\Desktop\\Miranda-Kerr-16-240x320.jpg"));
} catch (IOException ex) {
// handle exception...
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {
stopBtn.setEnabled(true);
startBtn.setEnabled(false);
imageArea.add(new ImagePanel()); // imageArea is the JPanel in the GUI
}
When I replace 2 lines of imageArea by creating a new JFrame as below, that JFrame shows up with the image I added.
private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {
stopBtn.setEnabled(true);
startBtn.setEnabled(false);
JFrame test = new JFrame("Window");
test.add(new ImagePanel());
test.setSize(image.getWidth(), image.getHeight() + 30);
test.setVisible(true);
}
When you add components to a visible GUI the basic code is:
panel.add(...);
panel.revalidate();
panel.repaint();
However, that probably won't help because by default a JPanel uses a FlowLayout and a FlowLayout respects the size of the component. Your ImagePanel will have a size of (0, 0) since you did not override the getPreferredSize() method.
There is no need to create a custom panel to paint your image. Just use a JLabel with an Icon then you let the label worry about the size. Don't reinvent the wheel.
I suggest you read the Swing tutorial for the basics. Maybe the section on How to Use Labels would be a good place to start. The tutorial will also show you a better way to design your class wo that you follow Swing guidelines.
First fix a bit:
try {
image = ImageIO.read(new File("C:\\Users\\HienTran\\Desktop\\Miranda-Kerr-16-240x320.jpg"));
} catch (IOException ex) {
ex.printStacktrace(); // see if there is an exception, like not finding or something
}
than:
If you add a panel, than need a layout refresh and a gui refresh:
imageArea.add(new ImagePanel());
imageArea.revalidate(); // refresh layout
imageArea.repaint(); // shedule painting

Is it possibly to create selectable hyperlink with basic Swing components in Java?

I am trying to add a hyperlink to a JPanel. I would like to make it's text blue (and underlined) and the link should be selectable (to copy some part of it). So I tried to use JLabel: yes, it allow to write something [awful] like this:
someLabel.setText("<html><font color=\"#0000ff\"><u>http://example.com</u></font></html>");
But unfortunately, JLabel doesn't allow to select any text. I also tried to use JTextField, but in opposite, it doesn't allow to use HTML/CSS in it's fields.
So, Is where exists any way to create a hyperlink (with proper indication) with basic Swing components, which will be allow to select [and copy] part of it, or should I try to use some 3rd party components? Thank you.
You can display HTML content in a non-editable JEditorPane. It's selectable, and you can make the links functional via a HyperlinkListener:
JEditorPane content = new JEditorPane();
content.setContentType("text/html");
content.setEditable(false);
content.setText("<html>Link</html>"));
content.addHyperlinkListener(new HyperlinkListener() {
#Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
Desktop.getDesktop().browse(e.getURL().toURI());
} catch (Exception e1) {
Logger.getLogger(getClass()).error(
"Error opening link " + e.getURL(), e1);
}
}
}
});
Here how can you create a JLabel with a hyperlink ,then you can just add it to your Jpanel:
public HyperLinkLabel()
{
JPanel p = new JPanel();
final String strURL = "http://www.yahoo.com";
final JLabel label = new JLabel("<html> click </html>");
final JEditorPane htmlPane = new JEditorPane();
p.add(label);
getContentPane().add(BorderLayout.NORTH, p);
getContentPane().add(BorderLayout.CENTER, new JScrollPane(htmlPane));
setBounds(20,200, 500,500);
label.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
label.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
label.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
System.out.println("Clicked on Label...");
try {
htmlPane.setPage(new URL(strURL));
}
catch(Exception e) {
System.out.println(e);
}
}
});
You have to create a custom Jlabel [extend Jlabel] and write a MouseListener for the JLabel.
Your mouse listener must do the job of directing the user to the link when the user clicks on the custom JLabel. The mouse event [basically the method of the MouseListener interface where you have to write the redirecting code] that you are looking for is mouseClicked.

Using JInternalFrame and some button

Can we use a JInternalFame with a button in the main frame? The frame contains a JDesktopPane, of course. The button should open up the JInternalFrame How?
I don't know a way to put a JButton directly on a JDesktopPane, but you can use menu items to create and select a JInternalFrame. In this example, each menu item uses an Action defined in the JInternalFrame to select the corresponding frame.
class MyFrame extends JInternalFrame {
private Action action;
MyFrame(JDesktopPane desktop, String name, int offset) {
…
action = new AbstractAction(name) {
#Override
public void actionPerformed(ActionEvent ae) {
try {
MyFrame.this.setSelected(true);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
};
}
public Action getAction() { return action; }
}
Addendum: as #camickr suggests, it is technically possible to put a JButton directly on a JDesktopPane, but it might prove difficult to use in practice.
I don't really understand the question so I will just make some observations.
a) a JInternalFrme is like a frame in that you can add any component to it that you want
b) A JButton works the same whether it is added to an internal frame or a frame
I suggest you start by reading the Swing tutorial for working examples. You might start with the sections on "How to Use Internal Frames" and "How to Use Buttons".
If you still have problems then post your SSCCE that shows what you have tried.

Categories