I am using a JScrollPane to wrap a JTable. Depending on the configuration, there is some space that is not occupied by the table. It is drawn gray (it looks like it is transparent and you can just see the component in the back). How can I set this area to be a certain color?
Here is a SSCCE to illustrate.
import java.awt.Color;
import java.util.Vector;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class DialogDemo extends JDialog {
public static void main(final String[] args) {
final DialogDemo diag = new DialogDemo();
diag.setVisible(true);
}
public DialogDemo() {
super();
setTitle("SSCCE");
final Vector<Vector<String>> rowData = new Vector<Vector<String>>();
final Vector<String> columnNames = new VectorBuilder<String>().addCont("Property").addCont("Value");
rowData.addElement(new VectorBuilder<String>().addCont("lorem").addCont("ipsum"));
rowData.addElement(new VectorBuilder<String>().addCont("dolor").addCont("sit amet"));
rowData.addElement(new VectorBuilder<String>().addCont("consectetur").addCont("adipiscing elit."));
rowData.addElement(new VectorBuilder<String>().addCont("Praesent").addCont("posuere..."));
final JTable table = new JTable(rowData, columnNames);
JScrollPane pane = new JScrollPane(table);
// ************* make that stuff white! *******************
table.setBackground(Color.white);
table.setOpaque(true);
pane.setBackground(Color.white);
pane.setOpaque(true);
// ************* make that stuff white! *******************
add(pane);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
class VectorBuilder<T> extends Vector<T> {
public VectorBuilder<T> addCont(final T elem) {
addElement(elem);
return this;
}
}
}
And here you can see the area, which I want to "colorize". In the SSCCE, I try to do that by using setOpaque(boolean) and setBackgroundColor(Color) of the table and scroll pane, with no success.
Can you tell me, what I am doing wrong?
Instead of this:
table.setBackground(Color.white);
table.setOpaque(true);
pane.setBackground(Color.white);
pane.setOpaque(true);
call:
pane.getViewport().setBackground(Color.WHITE);
Related
I'm trying to create a frame with multiple tabs, each with a different list. I've used the Swing UI designer with Intellij to create the "assets" and then modified them in my main class file. I've looked up some examples of creating a JTable using the designer, but these don't use multiple tabs, which I think is the main problem for me right now as I am not able to figure out how to do it.
This is the code for now.
package client;
import javax.swing.*;
import javax.swing.table.TableModel;
import java.awt.event.*;
public class ATCGUI extends GUI {
private JPanel mainPanel;
private JTabbedPane tabbedPanel;
private JPanel tabbedAirportInfo;
private JScrollPane scrollPane;
private JButton addButtonOut;
private JButton deleteButtonOut;
private JButton addButtonIn;
private JButton deleteButtonIn;
private JTable tableOut;
private JTable tableIn;
private JPanel panelOut;
private JScrollPane tabbedPaneOut;
public ATCGUI(String AirportCode) {
this.add(mainPanel);
String airportID = getID(AirportCode);
TableOut(airportID);
pack();
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
private void TableOut(String airportID){
String[] columnNames = {"Airline", "Destination", "Aircraft"};
Object[][] dataTest = {{"Iberia", "London", "737"}, {"AirEuropa", "Paris", "320"}, {"BritishAirways", "Berlin", "330"}};
JTable TableOut = new JTable(dataTest, columnNames);
setContentPane(panelOut);
}
public static void main(String[] args) {
new ATCGUI("MAD");
}
}
For now it shows the different tabs, but the JTable doesn't appear in any of the tabs. And I did make sure to put the JTable inside a JScrollPane.
I'm pretty new to this so maybe there's something I've missed out or just simply don't know.
Without your JTabbedPane code it will be difficult to suggest what you can "fix" in your own code.
This is a good reference for using a JTabbedPane with multiple tabs:
https://docs.oracle.com/javase/tutorial/uiswing/components/tabbedpane.html
An example of how JTabbedPane might be used with your data:
package whatever;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
public class MyGui extends JFrame {
private JTabbedPane tPane;
MyGui(String t){
super(t);
this.tPane = new JTabbedPane();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tPane.addTab("Tab 1", createTab());
tPane.addTab("Tab 2", createTab());
tPane.addTab("Tab 3", createTab());
tPane.addTab("Tab 4", createTab());
this.setContentPane(this.tPane);
this.setSize(400, 400);
this.setVisible(true);
}
public static void main(String[] args) {
new MyGui("My Tabbed App");
}
private JScrollPane createTab(){
String[] columnNames = {"Airline", "Destination", "Aircraft"};
Object[][] dataTest = {{"Iberia", "London", "737"}, {"AirEuropa", "Paris", "320"}, {"BritishAirways", "Berlin", "330"}};
JTable tableOut = new JTable(dataTest, columnNames);
return new JScrollPane(tableOut);
}
}
I am new to Java and need to make a blank table with column header only, but I am stuck at the column header, it won't appear, I have tried the answer in this link JTable won't show column headers (adding JScrollPane) but it won't work. This is my code:
void panelTabel(){
JPanel panelTabel = new JPanel();
panelTabel.setBackground(Color.white);
panelTabel.setLayout(null);
panelTabel.setBounds(0, 260, 1000, 455);
JScrollPane scrollTabel = new JScrollPane();
scrollTabel.setBackground(Color.white);
scrollTabel.setLayout(null);
scrollTabel.setBounds(5,5,990,340);
Vector headerTabel = new Vector(2);
headerTabel.addElement(new String("No."));
headerTabel.addElement(new String("Kode Barang"));
DefaultTableModel modelTabel = new DefaultTableModel(1, headerTabel.size());
modelTabel.setColumnIdentifiers(headerTabel);
JTable tabelBarang = new JTable();
tabelBarang.setModel(modelTabel);
tabelBarang.setBackground(Color.gray);
tabelBarang.setBounds(5,5, 980, 330);
scrollTabel.add(tabelBarang);
panelTabel.add(scrollTabel);
halaman.add(panelTabel);
}
And this is the output :
Blank table with no column header
I know my question may be duplicate, but I am really new to java and don't know what I did wrong, can someone please tell me what am I missing ? Thank you so much.
Here's a simple JTable GUI I created using your method.
Here are the changes I made.
I used a border layout on the JPanel that holds the JTable.
I got rid of all null layouts and positioning statements. I did ask for a preferred size for the JPanel. After you actually add some data to the JTable, you can define the size of the JTable and remove the preferred size hint.
I defined the JTable first, then the JScrollPane. Thanks to Andrew Thompson for his comment.
Here's the minimal, runnable example #38,593,729 of a JTable in a JPanel in a JFrame. I hope this example helps you, unlike the first 38,593,728 examples on the Internet.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class JTableSimpleExample implements Runnable {
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JTable Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panelTabel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel panelTabel() {
JPanel panelTabel = new JPanel();
panelTabel.setLayout(new BorderLayout());
panelTabel.setPreferredSize(new Dimension(400, 100));
Vector<String> headerTabel = new Vector<>(2);
headerTabel.addElement(new String("No."));
headerTabel.addElement(new String("Kode Barang"));
DefaultTableModel modelTabel = new DefaultTableModel(1, headerTabel.size());
modelTabel.setColumnIdentifiers(headerTabel);
JTable tabelBarang = new JTable(modelTabel);
JScrollPane scrollTabel = new JScrollPane(tabelBarang);
panelTabel.add(scrollTabel, BorderLayout.CENTER);
return panelTabel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new JTableSimpleExample());
}
}
I've recently been struggling with a Java problem that has been driving me mad. I've been attempting to add a ListSelectionListener in my Controller to a JList in my View but when I have successfully managed to attach the listener to something, it has not been the JList that has been drawing on the screen.
The code below gives a basic idea of what I am attempting to do.
This is my class with my main method:
package Application;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
View v = new View();
Controller c = new Controller(v);
}
}
This is my View:
package Application;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
public class View extends JFrame {
/* Components for the JList */
public DefaultListModel<String> listModel = new DefaultListModel<String>();
public JList<String> selectedItems = new JList<String>(listModel);
JScrollPane scroll = new JScrollPane(selectedItems);
public View()
{
// set the window title
this.setTitle("JList Test");
// set the window size
this.setSize(new Dimension(400, 400));
// set the window start position
this.setLocation(25, 25);
// set the window layout
FlowLayout layout = new FlowLayout();
layout.setHgap(0);
layout.setVgap(0);
this.setLayout(layout);
// set the window background
this.getContentPane().setBackground(Color.BLACK);
// make the window non-resizable
this.setResizable(false);
// set the default close operation
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// setup and add the JList
initJList();
this.add(scroll);
// add elements to the list model
listModel.addElement(" Item 1 ");
listModel.addElement(" Item 2 ");
listModel.addElement(" Item 3 ");
// make the gui visible
this.setVisible(true);
}
private void initJList() {
selectedItems.setVisibleRowCount(8);
selectedItems.setFixedCellWidth(300);
selectedItems.setFixedCellHeight(40);
selectedItems.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
selectedItems.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
selectedItems = new JList<String>(listModel);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
}
}
This is my controller:
package Application;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Controller implements ListSelectionListener {
View gui;
public Controller(View v)
{
gui = v;
gui.selectedItems.addListSelectionListener(this);
}
#Override
public void valueChanged(ListSelectionEvent e) {
System.out.println("Selection changed!");
}
}
It compiles OK and the list draws fine but the ListSelectionListener never fires when I select anything in the JList. Can somebody tell me where exactly I am going wrong? Because I have tried loads of things now and I am completely stumped! The thing I find strange is when I attempt to do what I am doing here with JButtons and an ActionListener it works absolutely fine.
Any help is appreciated.
you did a mistake there in initJList() function, you already have passed value of listModel before itself, and again you have passed this value here in this function , so commenting this line will solve the problem. the modified function will look like this here:
private void initJList() {
selectedItems.setVisibleRowCount(8);
selectedItems.setFixedCellWidth(300);
selectedItems.setFixedCellHeight(40);
selectedItems.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
selectedItems.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//selectedItems = new JList<String>(listModel);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
}
Otherwise :
Declaring the JList like this
public JList<String> selectedItems;
and keeping the function as it is will run fine.
Please have a look at the following code
import java.awt.*;
import javax.swing.JTable;
import javax.swing.*;
public class Table extends JFrame
{
private JTable table;
public Table()
{
String[] columnNames = {"first name","last name","address"};
Object[][]data = {{"John","Kane","NY"},{"Nayomi","Writz","NY"}};
table = new JTable(data, columnNames);
getContentPane().add(table);
this.pack();
this.setVisible(true);
}
public static void main(String[]args)
{
new Table();
}
}
I haven't used JTable before, so this is my first attempt. In here, it is not showing the column names, just showing the data. Why is that? Please help!
You need to put it in a JScrollPane or similar.
See the top of the API docs for JTable, and JScrollPane.
I have JScrollPane with JTextArea inside it and I am trying to set the JTextArea's orientation from right to left so the text inside it will start from the right and the scrollbar will be on the left
I've tried the following but they didn't affect the direction of the orientation:
txt.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setAlignmentX(JTextArea.RIGHT_ALIGNMENT);
EDIT:
the two answers camickr & trashgod provided work fine but not in my program where I use my JTextArea as an object Message and pass it to OptionPane.
EDIT2:
I figured out that setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); doesn't work if I apply it on the JOptionPane contents .. is there an alternative solution to this issue?
Similar to my code:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class TextArea extends JPanel
{
private JTextArea txt = new JTextArea();
public TextArea()
{
setLayout(new GridLayout());
txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JScrollPane scroll = new JScrollPane(txt);
scroll.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setPreferredSize(new Dimension(200,200));
this.add(scroll);
}
private void display()
{
Object[] options = {this};
JOptionPane pane = new JOptionPane();
int option = pane.showOptionDialog(null, null, "Title", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
public static void main(String[] args)
{
new TextArea().display();
}
}
and the scrollbar will be on the left
scrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
so the text inside it will start from the right
textArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
The text starts on the right side, but still gets append to the end as you type instead of being inserted at the beginning of the line.
Update:
I don't know why it doesn't work in an option pane. Here is a simple solution:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class Test
{
public static void main(String args[]) throws Exception
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTextArea textArea = new JTextArea(4, 20);
JScrollPane scrollPane = new JScrollPane( textArea );
JPanel panel = new JPanel();
panel.add( scrollPane );
scrollPane.addAncestorListener( new AncestorListener()
{
public void ancestorAdded(AncestorEvent e)
{
JScrollPane scrollPane = (JScrollPane)e.getComponent();
scrollPane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
public void ancestorMoved(AncestorEvent e) {}
public void ancestorRemoved(AncestorEvent e) {}
});
JOptionPane.showMessageDialog(null, panel);
}
});
}
}
This seems to work.
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/** #see http://stackoverflow.com/questions/6475320 */
public class RTLTextArea extends JPanel {
private static final String s = "مرحبا العالم";
private JTextArea jta = new JTextArea(7, 5);
private Locale arabic = new Locale("ar", "KW");
private ComponentOrientation arabicOrientation =
ComponentOrientation.getOrientation(arabic);
public RTLTextArea() {
this.setLayout(new GridLayout());
this.add(new JScrollPane(jta));
this.applyComponentOrientation(arabicOrientation);
for (int i = 0; i < 8; i++) {
jta.append(s + "\n");
}
}
private void display() {
JFrame f = new JFrame("RTLTextAre");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new RTLTextArea().display();
}
});
}
}
this line
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT)
change the correct order of the words.
i have this result
KBytes 80.78
The following lines solved my problem:
jTextArea1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
jTextArea1.setText(<text>);
They serve to:
setComponentOrientation() changes the orientation of the TextArea; and,
setText() refreshes TextArea immediately so it displays properly
Simply setting ComponentOrientation to RIGHT_TO_LEFT is not sufficient by itself. repaint() doesn't force the text to realign itself. A quick solution for me was to update the contents of the TextArea. That forced the text to realign itself.