How to put button in top right og jpane [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
According to your instruction i decided to use GridBagLayout, but i also face a problem in positioning buttons in a panel the button expected to be at top right, But it is displayed in the center, Please tell me what is the problem in my code`
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
public class Test extends JFrame {
private JPanel contentPane;
private JButton button2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 573, 410);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new GridBagLayout());
contentPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setContentPane(contentPane);
button2 = new JButton("button2");
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
contentPane.add(button2, c);
}
}
this the the output
http://postimg.org/image/bhnzskznj/

Since the answer just asks for a Layout - it's layout recommendation time!
My favourite - http://www.miglayout.com/ which satisfied all my layout needs for my last Swing project. wrap, span x and center layout arguments should be all that is needed to do what your picture does.

This is exactly why absolute layouts are not recommended.
Your best approach will be to use something like GridBagLayout which will position the elements and then let them move as the screen resizes and reshapes.
There are plenty of good documentation and tutorials online for GridBagLayout that will get you started. You can also use tools built into some IDEs (NetBeans has a good one for example) to let you lay things out graphically.

Related

Change bounds of a JScrollPane in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Helloo!
In the Java Application I have a JScrollPane and in that scroll I have a JTextArea
JTextArea TextArea = new JTextArea("Text");
scroll = new JScrollPane(TextArea);
scroll.setBounds(150,100,250,100);
And I got the scroll.
But If the user clicks a JButton the location of the JScrollPane should change...
I have this code and it works if the scroll doesn't have the TextArea
scroll.setBounds(50,100,250,100);
but if the scroll has the TextArea it doesn't move at all
Any idea what is happening?
Change bounds of a JScrollPane ..
The bounds come down to the position and size of the component.
The best way to change the size of a scroll pane is to change the size of the component it is displaying. A text area can be resized by setting the number of rows & columns (easily specified in the constructor), or by setting a different font size.
The best way to position the scroll pane is to use layouts, along with layout padding and borders for white space.
Use vScrollPane.setValue() hScrollPane.setValue() methods.
Like this
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
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.JScrollBar;
import javax.swing.JScrollPane;
class JScrollPaneToTopAction implements ActionListener {
JScrollPane scrollPane;
public JScrollPaneToTopAction(JScrollPane scrollPane) {
if (scrollPane == null) {
throw new IllegalArgumentException(
"JScrollPaneToTopAction: null JScrollPane");
}
this.scrollPane = scrollPane;
}
public void actionPerformed(ActionEvent actionEvent) {
JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar();
JScrollBar horizontalScrollBar = scrollPane.getHorizontalScrollBar();
verticalScrollBar.setValue(20);
horizontalScrollBar.setValue(100);
}
}
public class JScrollPaneToTopActionDemo {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton bn = new JButton("Move");
bn.addActionListener(new JScrollPaneToTopAction(jScrollPane));
frame.add(bn, BorderLayout.SOUTH);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}

Switch Card Layout in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Here's how to change card layouts from a menu item. I asked how to do it earlier but no luck. I have figured out the answer so here's what it does; 1. Builds your main frame when running the java file. Then in the menu bar it allows you to switch JPanels (For this example welcome is a different public class inside of a package.) 2. Now you can build as many public classes as you want and still be able to go to that JPanel.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class ArmyQuestions {
CardLayout cards;
JPanel cardPanel;
public static void main(String[] args) throws IOException {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ArmyQuestions();
}
});
}
public ArmyQuestions()
{
JFrame mainFrame = new JFrame();
//make sure the program exits when the frame closes
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle("Army Questions");
mainFrame.setSize(797,510);
//This will center the JFrame in the middle of the screen
mainFrame.setLocationRelativeTo(null);
mainFrame.getContentPane().setLayout(new BorderLayout());
//Adds a menu bar
JMenuBar menuBar = new JMenuBar();
mainFrame.getContentPane().add(menuBar, BorderLayout.NORTH);
//Adds a menu option
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
//Adds an item to the menu option
JMenuItem mntmNew = new JMenuItem("New");
mnFile.add(mntmNew);
mntmNew.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
cards.show(cardPanel, "Welcome");
}
});
//Adds cardpanel to getContentPane
cards = new CardLayout();
cardPanel = new JPanel();
cardPanel.setLayout(cards);
mainFrame.getContentPane().add(cardPanel,BorderLayout.CENTER);
//Adds a JPanel to your cardpanel
Welcome welcome = new Welcome();
cardPanel.add(welcome, "Welcome");
mainFrame.setVisible(true);
}
}
Two things I see going on.
You have SuggestedQuesion_2 declared globally then you create a whole new one in you method. JPanel SuggestedQuestion_2 = new JPanel();
I see a CardLayout for your Welcome - Welcome.setLayout(new CardLayout(0, 0));, but not for you SuggestedQuestion_2. Yet you're trying to access SuggestedQuestions's CardLayout
You should learn how to post an SSCCE So it is easier for us to see the problem. Also, in trying to recreate the problem into a smaller, runnable version you sometimes figure out the solution yourself.
And please follow Java naming convention using lowercase letters first letter of reference variable

Button is not showing up in the right spot [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
how can I get the buttons to appear on the line underneath the textarea?
//Imports
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
public class ProfessorPhysInstall {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//Variables
final JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
final JPanel cards = new JPanel(new CardLayout());
final CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(TextPaneScreen1);
JTextArea TextAreaScreen1 = new JTextArea();
JScrollPane sbrText = new JScrollPane(TextAreaScreen1);
TextAreaScreen1.setRows(15);
TextAreaScreen1.setColumns(40);
TextAreaScreen1.setEditable(false);
TextAreaScreen1.setText("Lots of text");
TextAreaScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextAreaScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(sbrText);
final JCheckBox Acceptance = new JCheckBox();
Acceptance.setText("I Accept The EULA Agreenment.");
screen1.add(Acceptance);
final JButton NextScreen1 = new JButton();
NextScreen1.setText("Next");
NextScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.next(cards);
}
});
screen1.add(NextScreen1);
JButton CancelScreen1 = new JButton();
CancelScreen1.setText("Cancel");
CancelScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen1.add(CancelScreen1);
cards.add(screen1);
//Screen2
JPanel screen2 = new JPanel();
JTextPane TextPaneScreen2 = new JTextPane();
TextPaneScreen2.setEditable(false);
TextPaneScreen2.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher.");
TextPaneScreen2.setSize(358, 48);
TextPaneScreen2.setLocation(0, 0);
TextPaneScreen2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen2.setMargin(new Insets(4,4,4,4));
screen2.add(TextPaneScreen2);
final JButton BackScreen2 = new JButton();
BackScreen2.setText("Back");
BackScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen2.add(BackScreen2);
final JButton NextScreen2 = new JButton();
NextScreen2.setText("Next");
NextScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.next(cards);
}
});
screen2.add(NextScreen2);
JButton CancelScreen2 = new JButton();
CancelScreen2.setText("Cancel");
CancelScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen2.add(CancelScreen2);
cards.add(screen2);
mainframe.add(cards);
mainframe.setVisible(true);
}
}
This is what it looks like
The default layout manager for JPanel is FlowLayout. As the name suggests, it simply flows the components one after the other.
You will need to try a different layout manager, something like GridBagLayout will do what you want, but it is a complex layout. You may be better of trying to use compound layouts to achieve the same effect.
That is, break the UI down into small chunks and apply different layout managers for each group.
Check out...
A Visual Guide to Layout Managers
Using Layout Managers
You will also benifit from reading...
Initial Threads
Code Conventions for the Java Programming Language
Ps...
You may also want to consider breaking each screen up into it's own class, the code as it stands is very hard to read and understands - IMHO
Use an appropriate LayoutManager
You've added all the components to screen2 which has a FlowLayout by default. There are many different ways to achieve what you're after.
More reading: Using Layout Managers
The usual way is to combine layouts for the look needed. E.G.
import java.awt.*;
import javax.swing.*;
public class ProfessorPhysInstall {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Variables
final JFrame mainframe = new JFrame();
mainframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainframe.setSize(500, 435);
final JPanel cards = new JPanel(new BorderLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen2
JPanel screen2 = new JPanel();
JTextPane TextPaneScreen2 = new JTextPane();
TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher.");
// set the preferred size, rather than the size!
//TextPaneScreen2.setSize(358, 48);
TextPaneScreen2.setPreferredSize(new Dimension(358, 48));
TextPaneScreen2.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.black),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen2.setMargin(new Insets(4,4,4,4));
screen2.add(TextPaneScreen2);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER, 5,5));
final JButton BackScreen2 = new JButton();
BackScreen2.setText("Back");
buttons.add(BackScreen2);
final JButton NextScreen2 = new JButton("Next");
buttons.add(NextScreen2);
JButton CancelScreen2 = new JButton("Cancel");
buttons.add(CancelScreen2);
cards.add(screen2, BorderLayout.PAGE_START);
cards.add(buttons, BorderLayout.PAGE_END);
mainframe.add(cards);
mainframe.pack();
mainframe.setVisible(true);
}
}
Tips
Please learn common Java naming conventions (specifically the case used for the names) for class, method & attribute names & use them consistently.
For better help sooner, post an SSCCE.
Don't set the size of top level containers. Instead layout the content & call pack().
See the Nested Layout Example for ideas about how to combine layouts to create the required layout.
Also heed the advice already offered on the other two answers.

Aligning an actively-rendered JPanel inside a JFrame [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Can anybody explain why pack() isn't working on this JFrame?
It's got one JPanel inside (actually, a class that extends JPanel - inner).
Here's the code I'm using:
inner.setPreferredSize(new Dimension(800, 600));
add(inner);
pack();
setResizable(false);
setLocationRelativeTo(null); // to center the JFrame on screen
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
The extra space seems to be the exact width and height of the JFrame's decoration (that is, the JFrame's dimensions minus the JPanel's dimensions).
Invoke setResizable(false) before pack(). It's no coincidence that "extra space seems to be the exact width and height of the JFrame's decoration."
Addendum: Here's an sscce showing that my initial guess was incorrect.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/questions/7924830 */
public class NonResizable extends JPanel {
public NonResizable() {
this.setPreferredSize(new Dimension(400, 300));
this.setBackground(Color.lightGray);
this.setBorder(BorderFactory.createLineBorder(Color.blue));
}
private void display() {
JFrame f = new JFrame("NonResizable");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
f.setBackground(Color.white);
f.add(this);
f.pack();
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setSize(500, 400);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NonResizable().display();
}
});
}
}
Turns out I was drawing (active rendering) from the JFrame and not the JPanel... so the extra space was the result of the JPanel's draw() object being aligned at 0,0 (in the JFrame).
Solved by this post.

Need some help with GUI in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i'm working on GUI in java and got stuck with move the object.
Please visit this youtube video i made a short demo for you guys to see what i was trying to do. I'm so new to the GUI thing as i've never been taught of doing GUI.
Here is the link: http://www.youtube.com/watch?v=up1LV5r-NSg
I see you're using a GUI designer. I highly recommend building your GUI "by hand" instead in which case your code is IMO much clearer (I'm not saying all GUI designers produce bad code, but it is almost always harder to read, and editing it will be hard without using the exact same GUI designer). Once you're comfortable with GUI designing by hand, then try a GUI designer and see what makes you more comfortable.
See: http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
In your case, you might create a BorderLayout, and in the "south" of your panel/frame you can place a panel with a FlowLayout aligning it's components to the left. Then add your button to the panel with the FlowLayout.
A little demo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
public class LayoutDemo extends JFrame {
LayoutDemo() {
super("LayoutDemo");
super.setSize(400, 200);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createGUI();
super.setVisible(true);
}
private void createGUI() {
// set the layout of this frame
super.setLayout(new BorderLayout());
// create a panel to put the button on
final JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
// create a text area to put in the center
final JTextArea textArea = new JTextArea();
// create the search button
final JButton searchButton = new JButton("search");
// add a listener to the button that add some text to the text area
searchButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
textArea.setText(textArea.getText() + "pressed search on " + (new Date()) + "\n");
}
});
// add the button to the bottom panel
bottomPanel.add(searchButton);
// wrap a scroll-pane around the text area and place it on the center of this frame
super.add(new JScrollPane(textArea), BorderLayout.CENTER);
// put the bottom panel (containing the button) on the 'south' of this frame
super.add(bottomPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LayoutDemo();
}
});
}
}
produces:
alt text http://img689.imageshack.us/img689/5874/guiq.png
EDIT
And to move the button a bit more up, use the constructor new FlowLayout(FlowLayout.LEFT, int hgap, int vgap)
where hgap is the gap (in pixels) between the left and right components and vgap is the gap (in pixels) between the upper and lower components.
Try:
final JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 10));
Note that the space between the button and text area also increases slightly!
learn fest swing test and miglayout! fest swing test enables you to run your gui screnario.
and Miglayout,it is my opinion, also is easy to use layout lib.
Fest: http://fest.easytesting.org/swing/wiki/pmwiki.php
MigLayout: http://www.miglayout.com/
If you are not trying to learn the ins & outs of Java Swing and aren't trying to create some fancy GUI then a GUI designer like the one you are using should be fine.
What you are not able to do seems to be a limitation of your particular IDE though, and therefore it might be helpful to give Netbeans a try. You can always take the generated GUI code (ugly as it may be) and then plug it back into your project in your other IDE.

Categories

Resources