I'm building a JFrame that will eventually display the output of a program that has a variable number of sections in it. I have parsed the output but displaying it in the frame is a problem.
When the frame appears, it is completely empty with the exception of the scroll pane. How do I get these labels to show up?
public class OutputPanel extends JFrame {
public OutputPanel(Vector parsedOutput) {
this.setTitle("Output");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
Iterator<Vector> outputIter = parsedOutput.iterator();
while(outputIter.hasNext()) {
Vector section = outputIter.next();
JLabel sectionLabel = new JLabel((String)section.get(0));
System.out.println((String)section.get(0));
scrollPane.add(sectionLabel);
}
this.add(scrollPane);
this.pack();
this.setVisible(true);
}
}
You shouldn't add components to the scrollPane
scrollPane.add(sectionLabel);
but rather add them to a separate panel, and either use
scrollPane = new JScrollPane(thePanel);
or
scrollPane.setViewportView(thePanel);
Example:
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.*;
class Test {
public static void main(String[] args) {
new OutputPanel(null);
}
}
class OutputPanel extends JFrame {
public OutputPanel(Vector parsedOutput) {
this.setTitle("Output");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel content = new JPanel(new GridLayout(0, 1));
for (int i = 0; i < 100; i++) {
JLabel sectionLabel = new JLabel("hello " + i);
content.add(sectionLabel);
}
JScrollPane scrollPane = new JScrollPane(content);
this.add(scrollPane);
this.pack();
this.setVisible(true);
}
}
Produces:
You should use setViewPortView() with a container instead of add() for JScrollPane.
Try this.
public class OutputPanel extends JFrame {
public OutputPanel(Vector parsedOutput) {
this.setTitle("Output");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
Iterator<Vector> outputIter = parsedOutput.iterator();
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
scrollPane.setViewportView(panel);
while(outputIter.hasNext()) {
Vector section = outputIter.next();
JLabel sectionLabel = new JLabel((String)section.get(0));
System.out.println((String)section.get(0));
panel.add(sectionLabel);
}
this.add(scrollPane);
this.pack();
this.setVisible(true);
}
}
Related
i have problem with my JTextArea i java. When i print output in the text area, it doesn't automatically scroll to the bottom. And when it reaches the bottom of text area i cannot scroll it with scroll panel. Here is my GUI Code:
public void initializeWindow()
{
JPanel pan;
JPanel colorBox;
JPanel consolePanel;
JLabel panText;
JFrame frame = new JFrame();
JScrollPane scroll;
gridPanels = new JPanel[sizeX][sizeY];
boardPanel = new JPanel();
legend = new JPanel();
consolePanel = new JPanel();
consoleOutput = new JTextArea(25,20);
consoleOutput.setEditable(false);
consoleOutput.setPreferredSize(new Dimension( 200,300));
consoleOutput.setAutoscrolls(true);
scroll = new JScrollPane(this.consoleOutput, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
consolePanel.setBorder(BorderFactory.createLineBorder(Color.black));
consolePanel.add(consoleOutput);
consolePanel.add(scroll);
boardPanel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
boardPanel.setLayout(new GridLayout(sizeX,sizeY));
legend.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
legend.setPreferredSize( new Dimension(300,boardPanel.getHeight()));
PrintStream printStream = new PrintStream(new CustomOutputStream(consoleOutput));
for (Organizm org: legendOrgs)
{
pan = new JPanel();
colorBox = new JPanel();
panText = new JLabel();
pan.setMaximumSize(new Dimension(100,70));
pan.setAlignmentX(Component.LEFT_ALIGNMENT);
pan.setLayout(new FlowLayout(FlowLayout.LEADING));
colorBox.setBackground(org.getOrgColor());
colorBox.setAlignmentX(Component.LEFT_ALIGNMENT);
colorBox.setPreferredSize(new Dimension(30,30));
colorBox.setMaximumSize(new Dimension(30,30));
panText.setPreferredSize(new Dimension(100,15));
panText.setText(" - " + org.getName());
panText.setAlignmentX(Component.RIGHT_ALIGNMENT);
pan.add(colorBox);
pan.add(panText);
legend.add(pan);
}
legend.add(consolePanel);
for(int i=0; i<sizeY; i++)
{
for(int j=0; j<sizeX; j++)
{
gridPanels[i][j] = new JPanel();
if(organizmy[i][j]!=null)
gridPanels[i][j].setBackground(organizmy[i][j].getOrgColor());
else gridPanels[i][j].setBackground(Color.white);
boardPanel.add(gridPanels[i][j]);
}
}
System.setOut(printStream);
System.setErr(printStream);
frame.add(boardPanel);
frame.add(legend,BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Wirtualny świat");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
worldFrame = frame;
}
And here is my Custom output Stream class which is used to print everything i print via System.out.println to my text Area:
public class CustomOutputStream extends OutputStream
{
private final JTextArea textArea;
public CustomOutputStream(JTextArea textArea)
{
this.textArea = textArea;
}
#Override
public void write(int b)
{
textArea.append(String.valueOf((char)b));
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
Here is link to image what it looks like in GUI:
You need to remove this line from your code:
consoleOutput.setPreferredSize(new Dimension( 200,300));
Unfortunately, it prevents your JTextArea from being scrollable because you set static size to that element.
P.S. Stay away from Swing - there are better options in Java
It works for me.
import javax.swing.*;
public class Scrollin{
public static void main(String[] args){
JFrame frame = new JFrame("scrolling");
JTextArea area = new JTextArea(20, 20);
frame.add(new JScrollPane(area));
frame.setVisible(true);
frame.pack();
Timer t = new Timer( 150, evt->{
area.setCaretPosition( area.getDocument().getLength() );
area.append("word is born\n");
});
t.start();
}
}
As text is added, the window will scroll to the end provided the cursor is at the end of the document.
Maybe you can start with something as short as this to demonstrate your issue?
I can't seem to get a swing GridLayout to work in java 13. The error is that GridLayout cannot be resolved to a type in the following code:
import javax.swing.*;
public class GameFrame extends JFrame {
public static final void NewFrame() {
new GameFrame();
}
public GameFrame() {
this.setSize(1600, 800);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("The Game");
this.setVisible(true);
this.setResizable(false);
JPanel MainPanel = new JPanel();
MainPanel.setLayout(new GridLayout());
}
}
The issue is caused by the class not being imported.
import java.awt.GridLayout;
Since it is not in the swing package it doesn't get imported with the star import.
Also it is better to use explicit imports.
This might be related to the fact that panel is empty. Try running this code and it should work.
public class GridLayoutTest {
private static JButton[] arrayBtn;
public static void main(String[] args) {
// the frame that contains the components
JFrame frame = new JFrame("GridLayoutTest from JCG");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the size of the frame
frame.setSize(350, 350);
// set the rows and cols of the grid, as well the distances between them
GridLayout grid = new GridLayout(5, 3, 10, 10);
// what layout we want to use for our frame
frame.setLayout(grid);
// add a text field with a specified text to the frame
JTextArea text = new JTextArea();
text.setText("Result");
text.setEditable(false);
frame.add(text);
// add buttons to the frame
frame.add(new JButton("+"));
frame.add(new JButton("="));
arrayBtn = new JButton[10];
// add JButtons dynamically
for(int i=0; i < arrayBtn.length; i++) {
arrayBtn[i] = new JButton(Integer.toString(i));
frame.add(arrayBtn[i]);
}
frame.setVisible(true);
}
}
I´ve got a JTabbedPane with JTextAreas as Components. With another methode I add Texts to the TextAreas. But if the TextArea is full it doesnt scroll down, so I can´t see the latest texts. How can I solve this?
public class View extends JFrame{
public class Field extends JTextArea{
public Field(){
this.setEditable(false);
this.setLineWrap(true);
DefaultCaret caret = (DefaultCaret)this.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}
}
public View(){
this.setLayout(new BorderLayout());
this.tabs = new JTabbedPane();
this.tabs.add("abc", new Field());
this.add(tabs, BorderLayout.CENTER);
}
}
You need to put your JTextArea inside of a JScrollPane to make it scrollable:
import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.*;
public class Example {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
JTextArea textArea = new JTextArea();
DefaultCaret caret = (DefaultCaret)textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane jScrollPane = new JScrollPane(textArea);
jScrollPane.setPreferredSize(new Dimension(300, 300));
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("abc", jScrollPane);
jFrame.setContentPane(tabbedPane);
jFrame.pack();
jFrame.setVisible(true);
for(int i = 0; i < 100; i ++) {
textArea.append(i + "\n");
}
}
}
class CipherGUIFrame extends JFrame {
public CipherGUIFrame() {
super("Caesar Cipher GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 600);
JTextArea area1 = new JTextArea();
JTextArea area2 = new JTextArea();
JSpinner myspinner=new JSpinner();
JPanel mainframe = new JPanel();
mainframe.setLayout(new BoxLayout(mainframe, BoxLayout.Y_AXIS));
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));
p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS));
p1.setBorder(BorderFactory.createTitledBorder("Cleartext"));
p2.setBorder(BorderFactory.createTitledBorder("Spinner"));
p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS));
p3.setBorder(BorderFactory.createTitledBorder("Ciphertext"));
p1.add(area1);
p2.add(myspinner);
p3.add(area2);
mainframe.add(p1);
mainframe.add(p2);
mainframe.add(p3);
this.add(mainframe);
}
}
It seems that this code produces something which looks similar to this:
I am trying to tidy this up so it looks cleaner; is there a way to shrink the middle panel or to make the others bigger to make it look nicer?
Don't set the sizes of anything, but instead set the columns and rows of your JTextAreas. Don't use BoxLayout when you don't want its behaviors. Put your JTextAreas in JScrollPanes instead. And don't forget to pack() your JFrame.
import java.awt.BorderLayout;
import javax.swing.*;
public class Cipher2 extends JPanel {
public static final int ROWS = 12;
public static final int COLS = 30;
private JTextArea textArea1 = new JTextArea(ROWS, COLS);
private JTextArea textArea2 = new JTextArea(ROWS, COLS);
public Cipher2() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // Box OK here
JScrollPane scroll1 = new JScrollPane(textArea1);
add(wrapComponentWithTitle(scroll1, "Fubar"), BorderLayout.PAGE_START);
add(wrapComponentWithTitle(new JSpinner(), "Spinner"), BorderLayout.CENTER);
scroll1 = new JScrollPane(textArea2);
add(wrapComponentWithTitle(scroll1, "Snafu"), BorderLayout.PAGE_END);
}
private JPanel wrapComponentWithTitle(JComponent component, String title) {
// BoxLayout NOT OK here. Use BorderLayout instead
JPanel wrapPanel = new JPanel(new BorderLayout());
wrapPanel.add(component);
wrapPanel.setBorder(BorderFactory.createTitledBorder(title));
return wrapPanel;
}
private static void createAndShowGui() {
Cipher2 mainPanel = new Cipher2();
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I figured out the answer: change Y_AXIS to X_AXIS.
<3
Hey guys I wanted to create a JScrollPane but it won't work... and I don't know why... here's my code...
public class test extends JFrame{
public test(){
setSize(1000,600);
}
private static JButton[] remove;
private static JPanel p = new JPanel();
public static void main(String[]args){
p.setLayout(null);
JFrame t=new test();
remove = new JButton[25];
for(int i=0;i<25;i++){
remove[i]=new JButton("Remove");
remove[i].setBounds(243,92+35*i,85,25);
p.add(remove[i]);
}
JScrollPane scrollPane = new JScrollPane(p);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
t.add(scrollPane);
t.setVisible(true);
}
Umm and Im pretty sure the frame isn't big enough for these 25 buttons... But if i delete that p.setLayout(null); A horizontal scroll bar will be created automatically... I don't really know what is wrong with my code... Pls help thank you very much!
You need to set p's preferredSize for this to work.
p.setPreferredSize(new Dimension(800, 2000));
Or you could have p extend JPanel and then override the getPreferredSize() method to return the proper dimension.
And I agree -- get rid of your null layouts. Learn about and use the layout managers if you want to use Swing correctly and have robust Swing GUI's.
e.g.,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Foo extends JFrame {
private static final int BUTTON_COUNT = 25;
public static void main(String[] args) {
JPanel btnPanel = new JPanel(new GridLayout(0, 1, 0, 20));
btnPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
AbstractAction removeAction = new AbstractAction("Remove") {
#Override
public void actionPerformed(ActionEvent evt) {
JButton src = (JButton) evt.getSource();
JPanel container = (JPanel) src.getParent();
container.remove(src);
container.revalidate();
container.repaint();
}
};
for (int i = 0; i < BUTTON_COUNT; i++) {
JButton removeBtn = new JButton(removeAction);
btnPanel.add(removeBtn);
}
JPanel borderPanel = new JPanel(new BorderLayout());
borderPanel.add(btnPanel, BorderLayout.NORTH);
JScrollPane scrollpane = new JScrollPane(borderPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollpane.setPreferredSize(new Dimension(400, 800));
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollpane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The issue is that a scroll pane checks the component inside it for a "preferred size" so a pane with a null layout has a preferred size of (0,0). Which it ignores.
You should do something along the lines of:
p.setPreferredSize(1000,600);
And you should see some scroll bars appear, I'm not sure how accurate they will be though.