Netbeans isn't show my gui project with java [duplicate] - java

I am trying to get a JInternalFrame to appear on my screen when a button is pressed, a pop up effect basically. However when the button is pressed the JInternalFrame does not appear on the screen. Also when I resize the screen all the elements expand with it, I am wondering if there is a way to get a pop up window to appear on the screen and keep the layout manager I have now still in place so that when the window is resized the elements are also resized with it
public class testing2 implements ActionListener {
JButton buttonAppear = new JButton();
JLayeredPane LayeredPane = new JLayeredPane();
public static void main(String[] args) {
new testing2();
}
public testing2() {
LayeredPane = new JLayeredPane();
BorderLayout borderlayoutpane = new BorderLayout();
LayeredPane.setLayout(borderlayoutpane);
JPanel mainPanel = new JPanel();
BorderLayout borderlayout = new BorderLayout();
mainPanel.setLayout(borderlayout);
JButton button = new JButton("Button");
mainPanel.add(button, "Center");
buttonAppear = new JButton("Panel Appear");
buttonAppear.addActionListener(this);
mainPanel.add(buttonAppear, "South");
LayeredPane.add(mainPanel, 2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(LayeredPane);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == buttonAppear)
{
JInternalFrame inFrame = new JInternalFrame("Internal Frame", true, true, true, true);
inFrame.setBounds(10, 10, 200, 200);
inFrame.setVisible(true);
LayeredPane.add(inFrame, 1);
}
}
}

a pop up effect basically.
Then use a JDialog. A JInternalFrame was designed to work with a JDesktopPane.
mainPanel.add(button, "Center");
Don't use hardcode strings for the constraint. Use the field provided by the API:
mainPanel.add(button, BorderLayout.CENTER);
Also, follow Java naming conventions. Variable names should NOT start with an upper case character. Be consistent.
Don't know if it will make a difference but components with a higher layer number are painted on top of components with a lower index. So I would guess the panel (which is opaque) would just paint over top of the internal frame. Read the section from the Swing tutorial on How to Use Layered Panes. Also read the section on How to Use Root Panes to find the special variable for "popups" on a layered pane.

Related

JInternalFrame won't appear on my screen

I am trying to get a JInternalFrame to appear on my screen when a button is pressed, a pop up effect basically. However when the button is pressed the JInternalFrame does not appear on the screen. Also when I resize the screen all the elements expand with it, I am wondering if there is a way to get a pop up window to appear on the screen and keep the layout manager I have now still in place so that when the window is resized the elements are also resized with it
public class testing2 implements ActionListener {
JButton buttonAppear = new JButton();
JLayeredPane LayeredPane = new JLayeredPane();
public static void main(String[] args) {
new testing2();
}
public testing2() {
LayeredPane = new JLayeredPane();
BorderLayout borderlayoutpane = new BorderLayout();
LayeredPane.setLayout(borderlayoutpane);
JPanel mainPanel = new JPanel();
BorderLayout borderlayout = new BorderLayout();
mainPanel.setLayout(borderlayout);
JButton button = new JButton("Button");
mainPanel.add(button, "Center");
buttonAppear = new JButton("Panel Appear");
buttonAppear.addActionListener(this);
mainPanel.add(buttonAppear, "South");
LayeredPane.add(mainPanel, 2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(LayeredPane);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == buttonAppear)
{
JInternalFrame inFrame = new JInternalFrame("Internal Frame", true, true, true, true);
inFrame.setBounds(10, 10, 200, 200);
inFrame.setVisible(true);
LayeredPane.add(inFrame, 1);
}
}
}
a pop up effect basically.
Then use a JDialog. A JInternalFrame was designed to work with a JDesktopPane.
mainPanel.add(button, "Center");
Don't use hardcode strings for the constraint. Use the field provided by the API:
mainPanel.add(button, BorderLayout.CENTER);
Also, follow Java naming conventions. Variable names should NOT start with an upper case character. Be consistent.
Don't know if it will make a difference but components with a higher layer number are painted on top of components with a lower index. So I would guess the panel (which is opaque) would just paint over top of the internal frame. Read the section from the Swing tutorial on How to Use Layered Panes. Also read the section on How to Use Root Panes to find the special variable for "popups" on a layered pane.

adding ScrollBar to JTextArea

I want to add a scroll bar into my text area and I know the simple code for adding scroll bar but when I put the code for scroll bar the whole text area disappears!
What is the problem?
Here is my code:
private JFrame frame;
private JTextArea textarea;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SmsForm window = new SmsForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SmsForm() {
initialize();
}
private void initialize() {
frame = new JFrame("???");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel groupBoxEncryption = new JPanel();
final JTextArea textarea=new JTextArea();
textarea.setBounds(50, 100, 300, 100);
frame.getContentPane().add(textarea);
textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JScrollPane scrollPanePlain = new JScrollPane(textarea);
groupBoxEncryption.add(scrollPanePlain);
scrollPanePlain.setBounds(100, 30, 250, 100);
scrollPanePlain.setVisible(true);
There are a number of issues
You need to add the JPanel groupBoxEncryption to the application JFrame
Don't add the textarea to the frame - components can only have one parent component
As already mentioned, you're using null layout which doesnt size components - forget about not a layout manager.
As JPanel uses FlowLayout by default, you need to override getPreferredSize for the panel groupBoxEncryption. Better yet use a layout manager such as GridLayout that automatically sizes the component
Example
JPanel groupBoxEncryption = new JPanel(new GridLayout());
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space.
Suggest a preferred size for the text area in the number of rows and columns.
Add the text area to a scroll pane before then adding the scroll pane to the GUI.

JFrame Button Logic error

I've been spending some time relearning java and a peculiar logic error hit me here.
import javax.swing.*;
import java.awt.*;
class Frame
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
Container content = frame.getContentPane();
content.setBackground(Color.blue);
content.add(btn1);
content.add(btn2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//end main
}
I've created 2 JButton objects, and they should be the same size, with different location and text. This of course is not the case, the "FOO" button is exactly where and how I want it to be, but the "BAR" button is the size of the entire frame.
Help!
1) You are attempting to use Absolute LayoutManager via setSize and setLocation etc, but without calling setLayout(null) on the component you are adding the JButtons to. However this is not a best practice in Swing.
When adding to JFrame contentpane default layout is BorderLayout which adds components to is default position of BorderLayout.CENTER.
Have a read on A Visual Guide to Layout Managers
2) Also when using a correct LayoutManager you would omit JFrame#setSize(..) call and replace it with JFrame#pack() before setting the JFrame visible.
3) Also have a read on Concurrency in Swing specifically on The Event Dispatch Thread
which dictates all swing components be created on EDT via SwingUtillities.invokeXXX(..) block:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//create and manipulate swing components here
}
});
4) Also rather use JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); as this will allow any other threads timers etc to carry on execution even after JFrame has been disposed.
add:
frame.getContentPane().setLayout(null);
To your code after the line:
frame.setSize(400, 500);
Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order).In your code the buttons are stacked over the other.That is why you get this Error(as you think it is).
This will solve your problem:-
import javax.swing.*;
import java.awt.*;
class OP3
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
JPanel p = new JPanel(new FlowLayout());
p.add(btn1);
p.add(btn2);
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//end main
}
Just add a panel to the frame and add the buttons to the panel.
import javax.swing.*;
import java.awt.*;
class source
{
public static void main (String args[])
{
JFrame frame = new JFrame("Tester Frame");
frame.setSize(400, 500);
JPanel panel=new JPanel();//panel added here
panel.setSize(frame.size());
panel.setLocation(0, 0);
JButton btn1 = new JButton("FOO");
btn1.setSize(150, 50);
btn1.setLocation(45, 0);
JButton btn2 = new JButton("BAR");
btn2.setSize(150, 50);
btn2.setLocation(205, 0);
panel.add(btn1);
panel.add(btn2);
Container content = frame.getContentPane();
content.setBackground(Color.blue);
content.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//endmain

Overlay panel (above another)

I am learning how to use Swing and found myself quite difficult task.
What I am trying to accomplish: I want to have panel (call it menu panel) on the left side (let's say 100px width) and the second panel (call it content panel), which takes the rest of available place.
In menu panel there are 3 buttons. When I press on of them, to the right side of menu panel (over content panel) second menu panel (submenu) should appear (and it should start in the middle of button which was pressed).
It may be hard to understand, so I've created simple draft:
I tried JLayeredPane but there were problems with resizing window (elements in Layered Pane didn't resize).
JLayeredPane miss implementations for LayoutManager, you have to setPreferredSize or setBounds manually for sizing/place JComponents,
there is one possible workaround you can add ComponentListener to the JFrame, then on componentResized(ComponentEvent e) you can resize/replace JComponent(s) to the desired Bounds
for example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class LayeredPaneWithOverlap {
private JTextArea textArea = new JTextArea(2, 10);
private JPanel textPanel = new JPanel(new BorderLayout());
private JTable table = new JTable(30, 5);
private JScrollPane scroll = new JScrollPane(table);
private JLayeredPane layer = new JLayeredPane();
private JFrame frame = new JFrame("Frame with resiziable JLayeredPane");
public void makeUI() {
textArea.setBorder(new LineBorder(Color.DARK_GRAY));
textArea.setText("Frame with resiziable JLayeredPane");
textPanel.setOpaque(false);
textPanel.add(textArea, BorderLayout.NORTH);
Font font = textArea.getFont();
FontMetrics fontMetrics = textArea.getFontMetrics(font);
int h = fontMetrics.getHeight() + frame.getInsets().top +
textPanel.getInsets().top + textArea.getInsets().top
+ textArea.getInsets().bottom;
scroll.setBounds(0, h, 400, 300);
layer.add(textPanel, new Integer(2));
layer.add(scroll, new Integer(1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
resizeAll();
}
});
}
});
frame.setLocationRelativeTo(null);
frame.add(layer);
resizeAll();
frame.setVisible(true);
}
void resizeAll() {
Insets insets = frame.getInsets();
int w = frame.getWidth() - insets.left - insets.right;
int h = frame.getHeight() - insets.top - insets.bottom;
textPanel.setSize(w, h);
scroll.setSize(w, h - scroll.getY());
layer.revalidate();
layer.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new LayeredPaneWithOverlap().makeUI();
}
});
}
}
You can set a layoutmanager for the layered pane, javax.swing.OverlayLayout uses the full available space and allows resizing.
JLayeredPane layer = new JLayeredPane();
layer.setLayout(new OverlayLayout(layer));
You probably don't want the submenu to occupy the fullspace. To avoid it you can override its get…size-methods. Or you can add a second LayeredPane (for it's transperancy and it's layoutmanager), set a normal BoxLayout and use a spacer.
JPanel normalContents = new JPanel();
layer.add(normalContents, JLayeredPane.DEFAULT_LAYER);
JLayeredPane subMenuAuxiliaryLayer = new JLayeredPane()
subMenuAuxiliaryLayer.setLayout(new BoxLayout(subMenuAuxiliaryLayer, BoxLayout.LINE_AXIS));
layer.add(subMenuAuxiliaryLayer, JLayeredPane.PALETTE_LAYER);
JPanel submenuContents = new JPanel();
subMenuAuliliaryLayer.add(submenuContents);
subMenuAuxiliaryLayer.add(Box.createHorizontalGlue());
contentPanel.setLayout(null); // Absolute positioning of children.
#Override
public void actionPerformed(ActionEvent evt) {
final JButton btn = (JButton) evt.getSource();
final int buttonY = btn.getY(); // Must be final for usage in new Runnable object.
SwingUtilities.invokeLater(new Runnable() { // Return fast from event handling.
#Override
public void run() {
JPanel child = new JPanel();
child.setBackground(Color.RED); // So we'll see it.
child.setBounds(0, buttonY, 100, 300);
contentPanel.removeAll(); // Clear content panel of prior additions.
contentPanel.add(child); // Add a new panel.
contentPanel.repaint(10L);
}
});
}
The JLayeredPane works by defualt with no Layout manager, which means that you are using absolute positioning and no resizing. You could add a resize listener and adjust positions and size of inner components from code, as you see fit.
If you don't want to do this from code, you will need a layout manager, nothing fancy, just something to fill the container as it resizes. But here's the thing... if you add a layout manager, it will layout the components as if they are all in one layer, but most layout managers don't overlap their children so they are useless. The only one you could use is the OverlayLayout - it can also resize children. But using an OverlayLayout with JLayeredPane is overkill. You can just use OverlayLayout with a JPanel. So, yes, JLayeredPane is kind of useless. I recommend using a JPanel with an OverlayLayout instead.
Here is how to set things up so that you can have great control over almost any overlapping UI scenario out there: Using a JPanel with an OverlayLayout, have a separate transparent JPanel for each layer. In this way you can combine various LayoutManagers on different layers, by setting a diferent layout manager for each pane, including absolute positioning if necessary. Then add your visible components inside the panels representing the layers. Don't add them directly to the OverlayLayout panel. Just make sure that all of the JPanels you are using as layers have setAlignmentX and Y to center (0.5f) so that they fill the entire OverlayLayout panel as it resizes.

Problem with alignment of JButtons

This might be a very stupid question posted at the dead of the night. I am trying to create two JButtons placed one on top of the other. However for some reason, it is not getting properly aligned. The left edge of the bottom button b2 appears slightly to the left of the left edge of top bottom b1.
Here is the code:
class thistrial extends JPanel implements ActionListener
{
...
public thistrial()
{
.....
add(new JSeparator(SwingConstants.HORIZONTAL));
//ADD THE START AND STOP BUTTONS
Border raisedBorder = BorderFactory.createRaisedBevelBorder();
b1 = new JButton("START");
b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.CENTER);
b1.setPreferredSize(new Dimension(220,100));
add(new JSeparator(SwingConstants.HORIZONTAL));
b2 = new JButton("STOP");
b2.setPreferredSize(new Dimension(220,100));
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
add(b1);
add(b2);
.............
}
}
/** MAIN function **/
public static void main(String args[])
{
//Create and set up the window.
JFrame frame = new JFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setSize(398,480);
frame.setLocation(300,200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
thistrial newContentPane = new thistrial();
frame.setContentPane(newContentPane);
//Display the window.
frame.setVisible(true);
}
What can I do about it?
Your example extends JPanel, which uses FlowLayout by default. Instead, you might try GridLayout, as shown in A Visual Guide to Layout Managers.
I'd suggest using the right layout manager. Your code shows none.

Categories

Resources