When I print out the raw text from a website, it will only put one line of text in the JLabel, but in the console it will do multiple lines each on their own line.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class closinggui extends JFrame {
private JPanel contentPane;
JLabel label;
JButton button;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
closinggui frame = new closinggui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void code() throws IOException
{
Document document = Jsoup.connect("http://www.nbcwashington.com/weather/school-closings/").get();
Elements tags = document.select("p");
for (Element tag : tags) {
System.out.println(tag.text());
label.setText(tag.text());
}
}
public closinggui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 449, 524);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
label = new JLabel("");
label.setBounds(10, 45, 414, 440);
contentPane.add(label);
button = new JButton("get closings");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
code();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
button.setBounds(164, 11, 89, 23);
contentPane.add(button);
}
}
As a sample it should print out multiple school closings like this:
Washington Yu Ying Public Charter School Closed
Whitman-Walker Health Open at 10am
Woodyard Road Nursery Open at 10am
But on the label all it shows is 1 line that isn't even a closing it is just in the same HTML tag as the others. So how do I make indents?
Try using html tags:
String txt = "<html>";
for (Element tag : tags) {
txt += tag.text() + "<br/>";
}
txt += "</html>";
label.setText(txt);
JLabel label = new JLabel("<html><span>this is <br> your text</span></html>");
or try
setText()
with html having
<br>
in it.
The <br> will break the lines properly.
Related
I am building this program and I would like to have a square area that is scrollable since the text is long. I've tried some methods but it seems to cut out the text out of the length. Could anyone give me a tip on how to do this?
package gerador;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import javax.swing.Scrollable;
public class frameMyPasswords extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frameMyPasswords frame = new frameMyPasswords();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public frameMyPasswords() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTextArea txtField = new JTextArea();
txtField.setLineWrap(true);
txtField.setEditable(false);
txtField.setToolTipText("");
txtField.setBounds(10, 38, 419, 144);
txtField.setText("LONG TEXT");
contentPane.add(txtField);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
While working on a GUI project i am stuck with an error called null pointer error.
I am unable to resolve this problem.
The line which shows the error is closed by double asterisk on both sides(**).(line 80)
I have connected this with a SQL database and error erupts while assigning Jtable its value and structure.
package connectsqlite;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;
public class afterLogin extends JFrame {
public JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
afterLogin frame = new afterLogin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connect = null;
public afterLogin() {
connect = sqliteConnection.conn();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 695, 422);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnBack = new JButton("Log out");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connecting window = new Connecting();
window.frame.setVisible(true);
}
});
btnBack.setBounds(10, 62, 114, 23);
contentPane.add(btnBack);
JButton btnNewButton = new JButton("Load Details");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String query = "SELECT * FROM Appointments";
PreparedStatement pst = connect.prepareStatement(query);
ResultSet rs = pst.executeQuery();
**table.setModel(DbUtils.resultSetToTableModel(rs));**
}
catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(10, 28, 114, 23);
contentPane.add(btnNewButton);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(162, 57, 435, 305);
contentPane.add(scrollPane);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane.setViewportView(scrollPane_1);
}
}
You haven't instantiated your table, it's only declared. Therefore, when you call setModel on it it's going to cause a NullPointerException.
I'm writing a program where there is a JTable to be created (Which I'm able to). But I want to add a scroll bar to it. Below is my code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
static DefaultTableModel model = new DefaultTableModel();
static JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.add(new JScrollPane(table));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
table.setBounds(10, 131, 516, 178);
contentPane.add(table);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
When I run the above program, the table frame is also not displayed. But when I remove frame.add(new JScrollPane(table));, it is displaying the table in the JTable area, but there is no scrollbar in it.
Please let me know how can I get a scrollbar in the table and display the data correctly.
Thanks
At first don't use null layout, please read here.
frame.add(new JScrollPane(table)); this scroll pane is not displaying because in null layout each component needs to have bounds. Try below code. I just changed static variables to instance variables. And added scrollpane in to the constructor.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
private DefaultTableModel model = new DefaultTableModel();
private JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
JScrollPane scroll = new JScrollPane(table);
scroll.setBounds(10, 131, 516, 178);
contentPane.add(scroll);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
I am using WindowBuilder in Eclipse to aid in my GUI design. I am trying to make a Jlist popup after the user either enters in a text file with integers in it or, if they enter a file that doesn't exist, they select a file with integers in it from JFileChooser. My problem I am having now is that when the file is selected, nothing happens. The program also doesn't seem to recognize when I do enter in a file that exists, it just defaults to the JFileChooser. Any ideas as to what I'm doing wrong and/or how to make the Jlist appear after an appropriate file is entered?
Here is the code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import java.awt.BorderLayout;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.plaf.FileChooserUI;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class GUI {
private JFrame frame;
private JTextField txtEnterFileName;
private JTextField textField;
private JFileChooser fileChooser;
private JList list;
private JList list_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtEnterFileName = new JTextField();
txtEnterFileName.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtEnterFileName.setEditable(false);
txtEnterFileName.setText("Enter File Name Below and Press Button");
txtEnterFileName.setBounds(72, 11, 304, 41);
frame.getContentPane().add(txtEnterFileName);
txtEnterFileName.setColumns(10);
textField = new JTextField();
textField.setBounds(113, 63, 221, 25);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int number;
boolean endOfFile = false;
File userF;
userF = new File(textField.getText());
if(!userF.exists()){
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home") + "/desktop"));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(userF.exists()){
try {
Scanner inFile = new Scanner(userF);
if(inFile.hasNextLine()){
inFile.close();
fileChooser = new JFileChooser();
fileChooser.setBounds(107, 153, 200, 50);
frame.getContentPane().add(fileChooser);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
userF = fileChooser.getSelectedFile();
}
}
else if(inFile.hasNextInt()){
String label[] = {"Smallest Number", "Largest Number", "Count", "Average", "Median", "Quit"};
list = new JList(label);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
});
btnNewButton.setBounds(174, 99, 89, 23);
frame.getContentPane().add(btnNewButton);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
Scanner#nextLine always seems to return true so long as there some text on the first line.
So a file in the format of ...
1 2 3 4 5 6
Will have Scanner#nextLine return true. Instead, you should check for hasNextInt first and then skip over to showing the JFileChooser
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
I'm attempting to horizontally center a JLabel that contains inline HTML, but I can't seem to get it to work. I've tried manually centering it, but had no luck.
Here's what it looks like for me:
Full class code:
import java.awt.Button;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Client extends JFrame{
private final String url = "http://example.com/";
public Client() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 225);
setResizable(false);
setLocationRelativeTo(null);
addComponents(mainPanel);
add(mainPanel);
setTitle(null);
setVisible(true);
}
public void addComponents(JPanel pane) {
Button btn1 = new Button("1");
btn1.setSize(200, 50);
btn1.setFocusable(false);
pane.add(btn1);
Button btn2 = new Button("2");
btn2.setSize(200, 50);
btn2.setFocusable(false);
pane.add(btn2);
Button btn3 = new Button("3");
btn3.setSize(200, 50);
btn3.setFocusable(false);
pane.add(btn3);
JLabel lblWebsite = new JLabel("<html>Visit lblAbout1</html>", BoxLayout.X_AXIS);
lblWebsite.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblWebsite.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().browse(new URI(url));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
});
pane.add(lblWebsite);
}
}
Try with JComponent#setAlignmentX() method
Enclose the anchor inside a div that is aligned to center.
JLabel lblWebsite = new JLabel("<html><div align='center'>Visit lblAbout1</div></html>", BoxLayout.X_AXIS);
lblWebsite.setAlignmentX(Component.CENTER_ALIGNMENT);
Snapshots: