code:
list1items = new DefaultListModel();
list1items.addElement("-");
list1 = new JList(list1items);
list1.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
list1.setBounds(0,0, 100,100);
JScrollPane list1scr = new JScrollPane(list1);
list1scr.setPreferredSize(new Dimension(20, 20));
list1.setVisibleRowCount(8);
getContentPane().add (list1scr);
And no scroll-bar appears. When there are too many items, they are hidden, I cant reach them. How to solve this?
getContentPane().add(list1scr);
To expand on Michael Ardan's answer, you were adding you JList to the panel instead of the JScrollPane. The JScrollPane must be added to the panel and the JList must be added to the ScrollPane for it to work. There's really no need to use setBounds or setPreferredSize - get rid of them. JList takes care of all that when you call the setVisibleRowCount method. Here's an example of your ScrollPane working. If you still have problems, plug your own code into this example until it breaks. Then tell us what broke it. If not, accept Michael's answer.
import java.awt.*;
import javax.swing.*;
public class Temp extends JPanel{
public Temp(){
DefaultListModel list1items = new DefaultListModel();
list1items.addElement("-");
for(int i = 0; i < 200; i++)
list1items.addElement("Item " + i);
JList list1 = new JList(list1items);
list1.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
JScrollPane list1scr = new JScrollPane(list1);
list1.setVisibleRowCount(8);
add (list1scr);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Temp());
frame.pack();
frame.setVisible(true);
}
}
Related
I have some components which I need to use setBounds() on, hence the reason why I'm using the setLayout(null).
But some of my components are out the window(below the Y-axis). I was wondering if there is a way to add a scrollbar to navigate down the window so as to see all the remaining components. A screenshot of my window is below.
Output of my window image:
That GUI would be simple to produce using layouts. Put the component displaying the list (which looks well suited to being a JTable, given the two pieces of data per row / line) into a JScrollPane. Put the scroll pane into the CENTER of a BorderLayout. Put the red label into the PAGE_START of the border layout. Then .. oh wait, the job is done!
This is what it might look like (using a JTextArea instead of a table).
can u please post a copy of this code.
Try implementing it based on the instructions above. If there is a problem, post a minimal reproducible example of your attempt.
Since you are refering to the items in the scrolling area as components, and not as texts in a JTextArea, please have a look at the below.
import java.awt.*;
import javax.swing.*;
import java.util.Random;
public class Mainframe {
private JFrame f;
Box box;
JScrollPane scrollPane;
Random rand = new Random();
public static void main(String[] args) {
new Mainframe().go();
}
private void go() {
box = new Box(BoxLayout.Y_AXIS);
JLabel label = new JLabel("Possible Paths and Total Distances");
label.setForeground(Color.RED);
for (int i = 0; i < 200; i++) {
box.add(Box.createRigidArea(new Dimension(0, 2)));// creates space between the components
box.add(new JLabel(i + " : " + rand.nextInt(10000)));
}
scrollPane = new JScrollPane(box);
Dimension dim = new Dimension(box.getComponent(0).getPreferredSize());
scrollPane.getVerticalScrollBar().setUnitIncrement(dim.height * 2); // adjusts scrolling speed
//scrollPane.getViewport().setBackground(Color.WHITE);
f = new JFrame();
f.getContentPane().add(label, BorderLayout.NORTH);
f.getContentPane().add(scrollPane, BorderLayout.CENTER);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(640, 480);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
It is difficult to describe what happens so here is a SSCCE:
public class TableInScrollPaneTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TableInScrollPaneTest();
}
});
}
public TableInScrollPaneTest() {
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
LayoutManager layout;
layout = new MigLayout("wrap 1, fill", "fill, grow", "[fill, grow 1][fill, grow 2]");
//layout = new GridLayout(2,1);
JPanel panel = new JPanel(layout);
JPanel placeHolder = new JPanel();
JPanel placeHolder2 = new JPanel();
placeHolder.setBackground(Color.GRAY);
placeHolder2.setBackground(Color.LIGHT_GRAY);
JTable table = this.createTable();
JScrollPane tableScrollPane = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//table.setPreferredScrollableViewportSize(new Dimension(5000,200));
panel.add(placeHolder, "");
panel.add(tableScrollPane, "");
//panel.add(placeHolder2, "");
frame.setContentPane(panel);
frame.setVisible(true);
}
private JTable createTable() {
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
int rows = 30;
int cols = columnNames.length;
String[][] data = new String[rows][cols];
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
data[i][j] = "R"+i+" C"+j;
}
}
JTable table = new JTable(data, columnNames);
return table;
}
}
I want the scrollPane to use all available space when the frame gets resized by the user. But additionally I want another panel (placeHolder) to grow, too. For example the heigth of the frame divided by 3, the placeHolder gets 1 part and the scrollPane gets 2 parts. The GridLayout is kinda doing what I need, but I'm looking for a solution with MigLayout.
If you uncomment panel.add(placeHolder2, ""); and comment the line above it works.
EDIT1:
I tried using the sizegroup contraint. Now the placeHolder and the scrollPane have the same size, but I want the scrollPane take twice as much space. (Additionally in my programm I dont have a placeholder like this, but rather there are some labels, checkboxes and textfields. So sizegroup probably is not what I need except there are more ways to use it)
I found the solution here:
MigLayout confused by JTable objects contained in JScrollBar objects
and here:
How to set JScrollPane to show only a sepecific amount of rows
table.setPreferredScrollableViewportSize(null);
or
table.setPreferredScrollableViewportSize(table.getPreferredSize());
I don't know what's the difference between this code snippets, but they both do what I need.
I think im heading in the wrong direction. Im creating a notepad app. I have every method running perfectly except one - WordWrap
Its just a JTextarea inside a panel inside a frame.
I think i should be using a JScrollPane instead of a Textarea? Or aswell as it even?
How would i go about resizing the width of a textarea or am i correct in saying i need to insert a JScrollPane.
Edit
Ok so my attempt is gone wrong somehow. Text area doesnt work. Something possibly needs resizing.
public class TextEditor extends JFrame implements ActionListener{
JFrame textFrame = new JFrame();
JPanel textPanel = new JPanel();
JTextField textArea = new JTextField();
JScrollPane scroll = new JScrollPane(textArea);
JTextArea text = new JTextArea(24,33);
public TextEditor(String str){
super(str);
textFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
textFrame.add(textPanel);
textPanel=(JPanel)getContentPane();
textPanel.setLayout(new FlowLayout());
textPanel.setBackground(Color.WHITE);
// Create text Area
textPanel.add(scroll);
scroll.add(text);
textPanel.setFont(textAreaFont);
textArea.setFont(textAreaFont);
text.setFont(textAreaFont);
}
public static void main(String args[])
{
TextEditor notePad = new TextEditor("Notepad");
notePad.setSize(500,500);
notePad.setVisible(true);
notePad.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Have a look at what I have tried to put together:
public class SO{
public static void main(String[] args) {
JFrame f = new JFrame();
JPanel p = new JPanel();
JTextArea outputArea = new JTextArea();
outputArea.setColumns(20);
outputArea.setRows(20);
outputArea.setLineWrap(true); //Set line wrap
outputArea.setWrapStyleWord(true); //set word wrap
JScrollPane sp = new JScrollPane(outputArea); //Create new scroll pane with textarea inside
p.add(sp); //add scrollPane to panel
f.add(p); //Add panel to frame
f.pack()
f.setLocationRelativeTo(null); //frame location
f.setVisible(true);
}
}
The scroll pane is created using the textarea in the constructor, this seems to allow the scroll pane to 'contain' the JTextArea, adding scroll bars when the text the area contains exceeds the limits. Earlier when creating the JTextArea I set two lines of code to set a word wrap on it, this stops words seeping off the sides by pushing them onto the next line. Have a look and see if it can help with your project.
Good Luck!
import java.awt.*;
import javax.swing.*;
public class TextEditor extends JFrame {
JFrame textFrame = new JFrame();
JPanel textPanel = new JPanel();
JTextArea textArea = new JTextArea(10,25);
public TextEditor(String str){
super(str);
textFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); // nicer
add(textPanel);
textPanel.setLayout(new GridLayout());
textPanel.setBackground(Color.WHITE);
// Create text Area
JScrollPane scroll = new JScrollPane(textArea);
textPanel.add(scroll);
}
public static void main(String args[])
{
TextEditor notePad = new TextEditor("Notepad");
notePad.setVisible(true);
notePad.setDefaultCloseOperation(EXIT_ON_CLOSE);
notePad.pack();
}
}
There were so many things wrong in that short code that I lost track of the changes. Two things I can recall are:
The code was quite confused about what was a JTextField and what was a JTextArea.
It added strange things to other strange things for no apparent reason.
the problem I encountered is weird for me, because I was doing everything step by step, correctly (in my opinion) and finally when I could say I finished one part of my program it appeared to make a fun of me. The actual problem is that in GUI I created I used a JPanel, then I've put it into a JTabbedPane which I've finally put into a JFrame. Everything is fine and works apart from times when it doesn't. I know it sounds strange, but after running program once I get what I wanted (Frame with tabbed pane containing panel with some stuff in it) and then when I run it again it either show the correct thing again or just empty frame. The worst thing is that it's so random, I haven't got a clue what can be wrong, I don't even know what exactly should I google to find it out. The code is:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
public class GUI extends JFrame {
JFrame frame = new JFrame("WakeOnLan script generator");
JPanel panel1 = new JPanel(null);
JTextArea text; //= new JTextArea("test");
JScrollPane scroll = new JScrollPane();
JButton but = new JButton("test");
JTabbedPane tab = new JTabbedPane();
public GUI() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width-w)/3;
int y = (dim.height-h)/4;
frame.setSize(500,500);
frame.setLocation(x,y);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(null);
createTab1();
tab.addTab("Tab 1", panel1);
tab.setVisible(true);
tab.setBounds(0, 0, 500, 500);
frame.add(tab);
}
public void createTab1(){
text = new JTextArea("test");
text.setVisible(true);
scroll.setViewportView(text);
scroll.setBounds(10,10,465,300);
panel1.setLayout(null);
panel1.add(scroll);
panel1.setVisible(true);
panel1.setSize(500,500);
//panel.setBackground(Color.blue);
}
}
And then I just run it in the main method in other class:
public class GUIStarter {
public static void main(String[] args) {
GUI start = new GUI();
}
}
So could anyone give me an answer or just a hint?
Thank you.
You should call frame.setVisible(true) after adding all your components to your JFrame. So try moving it to the end of your constructor.
Alternatively, you can call frame.validate() after all the components have been added.
I am using netBeans editor to create desktop application . and i want to add Component without using drag and drop way. I am trying code like this for adding JList to JPanel but nothing showed
JList jl = new JList();
Vector<String> v= new Vector<String>();
v.add("one");
v.add("Two");
v.add("Three");
jl.setListData(v);
JScrollPane js = new JScrollPane(jl);
js.setLocation(50, 50);
js.setSize(100, 100);
js.setVisible(true);
jPanel1.add(js);
I want to add Component without using drag and drop way.
Here's a simple JList example that doesn't use the NetBeans' GUI editor. See How to Use Lists for more.
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class JListTest {
private static final Random random = new Random();
public static final void main(String args[]) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
final DefaultListModel dlm = new DefaultListModel();
for (int i = 0; i < 1000; i++) {
dlm.addElement("Z" + (random.nextInt(9000) + 1000));
}
final JList list = new JList(dlm);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new JScrollPane(list), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
The scroll list doesn't appear, or the data items in the list? Also, you're setting the position manually. Seriously, don't do that -- use a layout manager, many of which are available and you can easily use in the Netbeans GUI editor Mattise.
If the main window is under the control of a layout manager and then you add something to it that specifies its position and size, all mayhem will break loose. Namely, the layout manager will overwrite this, possibly with the result of size becoming 0, 0.
What you need to do is create a JPanel in your layout manager to hold the position of the new component and make sure it has a known field name you can reference and use to add to. Make sure that Panel also has FlowLayout or something in the properties.
you may want to call repaint() when you dynamically create GUI elements.