I am working on the editor. I am using Java swing for it. I have embedded a JTextArea with JScrollPane. i want to position the jtextarea of particular size at the middle of JScrollPane. To do this I used setLocation function. But this is not working?
public class ScrollPaneTest extends JFrame {
private Container myCP;
private JTextArea resultsTA;
private JScrollPane scrollPane;
private JPanel jpanel;
public ScrollPaneTest() {
resultsTA = new JTextArea(50,50);
resultsTA.setLocation(100,100);
jpanel=new JPanel(new BorderLayout());
jpanel.add(resultsTA,BorderLayout.CENTER);
scrollPane = new JScrollPane(jpanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(800, 800));
scrollPane.setBounds(0, 0, 800, 800);
setSize(800, 800);
setLocation(0, 0);
myCP = this.getContentPane();
myCP.setLayout(new BorderLayout());
myCP.add(scrollPane);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new ScrollPaneTest();
}
}
You simply have to add the JTextArea to the JScrollPane, and add it to the CENTER of the JPanel having BorderLayout.
Don't use AbsolutePositioning. Add a proper LayoutManager, and let LayoutManager do the rest for positioning and sizing your components on the screen.
In order to use the setBounds(...) method you have to use a null Layout for your component, which is not worth using, provided the perspective, as mentioned in the first paragraph of the AbsolutePositioning. Though in the code example provided by you, you are doing both the thingies together i.e. using Layout and using AbsolutePositioning, which is wrong in every way. My advice STOP DOING IT :-)
In the example provided the ROWS and COLUMNS provided by you are sufficient to size the JTextArea by the Layout concern.
Code Example :
import java.awt.*;
import javax.swing.*;
public class Example
{
private JTextArea tarea;
private void displayGUI()
{
JFrame frame = new JFrame("JScrollPane Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JScrollPane textScroller = new JScrollPane();
tarea = new JTextArea(30, 30);
textScroller.setViewportView(tarea);
contentPane.add(textScroller);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new Example().displayGUI();
}
});
}
}
Related
In my software i have a JPanel containing some JComponent. The JPanel use a FlowLayout with a certain Hgap to separate these components.
I'm trying to have this kind of design, but the first component should be layed out on left, without any Hgap. Like This:
here is the code you can use to generate the example:
public class FlowLayoutExample {
public static void main(String [] a) {
final JFrame frame = new JFrame();
frame.setSize(new Dimension(500, 80));
frame.setMinimumSize(new Dimension(350, 80));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(initJPanel());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});
}
private static JPanel initJPanel() {
JPanel panel = new JPanel();
FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);
flowLayout.setHgap(25);
panel.setLayout(flowLayout);
panel.setBackground(Color.LIGHT_GRAY);
panel.add(initLabel());
panel.add(initLabel());
panel.add(initLabel());
panel.add(initLabel());
return panel;
}
private static Component initLabel() {
return new JLabel("MyLabel");
}
}
Thanks for any suggestion you'll leave !
You can use an EmptyBorder to fake it out:
panel.setBorder( new EmptyBorder(0, -25, 0, 0) );
Basically the border inset and layout gap are added together.
I want to write a simple Java program, which consists of a JFrame that integrates a JScrollPane. Just it does not work the way I do it.
What is the issue of the my approach ?
public class TestView {
JFrame frame;
JScrollPane scrollPane;
public TestView(){
frame = new JFrame();
scrollPane = new JScrollPane();
scrollPane.add(new JLabel("Klick me"));
scrollPane.setMinimumSize(new Dimension(200,200));
frame = new JFrame();
frame.getContentPane().add(scrollPane);
frame.setSize(200,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void createAndShowGui(){
TestView tv = new TestView();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
If the issue is that you do not see your label in the scrollpane, you might need to use
scrollpane.setViewportView(new JLabel("Klick me"));
instead of
scrollPane.add(new JLabel("Klick me"));
Additionally, I suggest you create a JPanel, give it a layout, and place your label there, instead of passing the label to the scrollpane. Then set this panel as the viewport.
Please see
Difference between JscrollPane.setviewportview vs JscrollPane.add
use for example:
final JPanel myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(50, 50));
final JScrollPane scrollPane = new JScrollPane(myPanel);
setMinimumSize will be ignored.
In my code, My okButton is in bad appear, so large and long, How fix this problem?
public class d7Table extends JFrame {
public JTable table;
public JButton okButton;
public d7Table() {
table = new JTable(myTableModel(res));
okButton = new JButton("Ok");
add(new JScrollPane(table), BorderLayout.CENTER);
add(okButton, BorderLayout.PAGE_END);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800, 600);
this.setLocation(300, 60);
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new d7Table();
}
});
}
}
I remove Irrelevant codes.
You've added the button to the SOUTH position of a BorderLayout. This is the default behaviour of BorderLayout.
To fix it, create another JPanel, add your button to it, then add the panel to the SOUTH position instead
Take a look at
A visual guide to layouts
Using Layout Managers
The approach mentioned above is commonly known as compound layouts, as you use a series of containers with different layout managers to achieve the desired effect.
JPanel buttonPane = new JPanel(); // FlowLayout by default
JButton okayButton = new JButton("Ok");
buttonPanel.add(okayButton);
add(okayButton, BorderLayout.SOUTH);
Because the default layout of JFrame is BorderLayout, and PAGE_END means the bottom of the frame horizontally like this:
You have to change the layout of the frame, but don't do that, just create a panel, and add the components to it then add the panel to the container.
JPanel p = new JPanel();
p.add(okButton);
add(p,BorderLayout.PAGE_END);
Here some links may help you understand more about layout managers that usually used:
How To Use BorderLayout
How To Use FlowLayout
And MigLayout which I prefer to use it as it's very flexible layout manager, try it it's amazing.
import java.awt.*;
import javax.swing.*;
public class TableAndButton extends JFrame {
public JTable table;
public JButton okButton;
public TableAndButton() {
table = new JTable();
okButton = new JButton("Ok");
add(new JScrollPane(table), BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.add(okButton);
add(bottomPanel, BorderLayout.PAGE_END);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setSize(800, 600); better to call pack()
this.pack();
//this.setLocation(300, 60); better to..
this.setLocationByPlatform(true);
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TableAndButton();
}
});
}
}
For some reason i am having problems centering my panel vertically that is located inside another panel. I do exactly as the examples i studied but still no luck.
Down there is my code. Despite using setAlignmentY(0.5f) on my container panel, it still wont center when i resize the window.
Also the components inside container panel wont center either, despite setAligenmentX(0.5f).
I wonder if there is a solution for this, I pretty much tried everything out there but couldnt find a solution.
JLabel idLabel;
JLabel passLabel;
JTextField id;
JTextField pass;
JButton enter;
JPanel container;
public JournalLogin()
{
//setLayout(new FlowLayout());
//setPreferredSize(new Dimension(500, 500));
//setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
container = new JPanel();
container.setLayout(new MigLayout());
container.setAlignmentX(0.5f);
container.setAlignmentY(0.5f);
container.setPreferredSize(new Dimension(300, 300));
container.setBorder(BorderFactory.createTitledBorder("Login"));
add(container);
idLabel = new JLabel("ID:");
idLabel.setAlignmentX(0.5f);
container.add(idLabel);
id = new JTextField();
id.setText("id");
id.setAlignmentX(0.5f);
id.setPreferredSize(new Dimension(80, 20));
container.add(id, "wrap");
setAlignmentX and Y are not the way to go about doing this. One way to center a component in a container is to have the container use GridBagLayout and to add the component without using any GridBagConstraints, a so-called default addition. There are other ways as well.
For example to alter Nick Rippe's example (1+ to him):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;
public class UpdatePane2 extends JPanel {
private static final int PREF_W = 300;
private static final int PREF_H = 200;
public UpdatePane2() {
JPanel innerPanel = new JPanel();
innerPanel.setLayout(new BorderLayout());
innerPanel.add(new JLabel("Hi Mom", SwingConstants.CENTER),
BorderLayout.NORTH);
innerPanel.add(new JButton("Click Me"), BorderLayout.CENTER);
setLayout(new GridBagLayout());
add(innerPanel);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("UpdatePane2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new UpdatePane2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Alignments tend to be pretty picky in Swing - they do [usually] work... but if all you're looking for is a panel that's centered, I'd recommend using Boxes in the BoxLayout (My personal favorite LayoutManager). Here's an example to get you started:
import java.awt.Dimension;
import javax.swing.*;
public class UpdatePane extends JPanel{
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
//Create Buffers
Box verticalBuffer = Box.createVerticalBox();
Box horizontalBuffer = Box.createHorizontalBox();
verticalBuffer.add(Box.createVerticalGlue()); //Top vertical buffer
verticalBuffer.add(horizontalBuffer);
horizontalBuffer.add(Box.createHorizontalGlue()); //Left horizontal buffer
//Add all your content here
Box mainContent = Box.createVerticalBox();
mainContent.add(new JLabel("Hi Mom!"));
mainContent.add(new JButton("Click me"));
horizontalBuffer.add(mainContent);
horizontalBuffer.add(Box.createHorizontalGlue()); //Right horizontal buffer
verticalBuffer.add(Box.createVerticalGlue()); //Bottom vertical buffer
// Other stuff for making the GUI
verticalBuffer.setPreferredSize(new Dimension(300,200));
JFrame frame = new JFrame();
frame.add(verticalBuffer);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
You will need to get the LayoutManager to center the layout for you. Currently it looks like the implementation of "MigLayout" does not honor the Alignment. Try changing it or creating a subclass.
I have this app, but, when I resize the window, the element JTextArea inside, it doesn't resize with the window. Why?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ExampleGUI {
private JTextArea text_area;
private JScrollPane scroll_bar;
private JFrame frame;
private JPanel panel;
public ExampleGUI(){
frame = new JFrame("Example GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text_area = new JTextArea();
scroll_bar = new JScrollPane(text_area);
panel = new JPanel();
panel.add(scroll_bar);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){public void run(){new ExampleGUI();}});
}
}
You need to set your GridBagConstraint x and y weights (weightx and weighty -- the 5th and 6th parameters in the GridBagConstraint constructor) to a positive value other than 0.0. You should read tutorials on GridBagLayout if you're going to use it as it is fairly complex. Some have had great success nesting simpler layouts or using 3rd party layouts such as MigLayout.
Your frame layout is a FlowLayout. This does not resize children. From the docs:
A flow layout lets each component assume its natural (preferred) size.
You will be better off using a BorderLayout and putting the pane in the CENTER.
Replace this:
frame.setLayout(new FlowLayout());
frame.add(pane);
with this:
frame.setLayout(new BorderLayout());
frame.add(pane, BorderLayout.CENTER);
Also, as Hovercraft points out, if you need the individual components to resize when the pane resizes, then you need to have non-zero weights in the GridBagConstraints.
This takes into account the advice of Hovercraft Full Of Eels & Ted Hopp with a few other tweaks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Collection;
public class AziendaGUI implements ActionListener {
private JButton view_list;
private JButton save_list;
private JTextArea text_area;
private JScrollPane scrollpane;
private JPanel pane;
private JFrame frame;
private GridBagLayout grid;
public AziendaGUI() {
frame = new JFrame("Immobiliari s.p.a");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
view_list = new JButton("View Property");
view_list.setActionCommand("view_list");
view_list.addActionListener(this);
save_list = new JButton("Save List");
save_list.setActionCommand("save_list");
save_list.addActionListener(this);
text_area = new JTextArea(10,22);
text_area.setEditable(false);
scrollpane = new JScrollPane(text_area);
grid = new GridBagLayout();
pane = new JPanel();
pane.setLayout(grid);
/* Set Constraints view_list button */
grid.setConstraints(view_list, new GridBagConstraints(0,0,1,1,0.0,0.0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,5,5,5),0,0));
pane.add(view_list);
/* Set Constraints save_list button */
grid.setConstraints(save_list,new GridBagConstraints(1,0,1,1,0.1,0.1,GridBagConstraints.EAST,GridBagConstraints.NONE,new Insets(5,5,5,5),0,0));
pane.add(save_list);
frame.add(scrollpane);
frame.add(pane, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
private void store(){
String file_name = JOptionPane.showInputDialog("Inserisci il nome del file");
}
#Override
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
if(s.equals("view_list")){
}
if(s.equals("save_list")){
store();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){#Override
public void run(){new AziendaGUI();}});
}
}