Why does is not show the radio buttons

I want to display the buttons in a row then radio button in a row under the button and then log scroll pane under the radio buttons. This is my code:

//Add the buttons and the log to this panel.

add(buttonPanel, BorderLayout.PAGE_START);

add(radioPanel, BorderLayout.CENTER);

add(logScrollPane, BorderLayout.CENTER);

When i run it it display the buttons and the logsrollpane. Why does it not display the radio buttons?

[486 byte] By [SDNJavaa] at [2007-11-27 7:44:59]
# 1
pack();
morgalra at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 2
Because you're replacing it with the logScrollPane component.Only one thing can be in the center at a time.Message was edited by: paulcw
paulcwa at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 3

A Container with a BorderLayout LayoutManager is divided into 5 areas:

North, South, East, West, Center, and whatever they are called under the

Metric system.

You should not add more than one component into any area!

If you add more than one, they will be stacked on top of each and you will

likely only see the last component.

If you want to have more than one component in an area, nest containers.

Hippolytea at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 4
Can you please show me example code of how i can do that.
SDNJavaa at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 5

You're apparently already doing it. What are those panels you're adding? They hold other components, right?

So you could basically just add another level of nesting.

Or, you could rearrange the layout of the components. Are you using BorderLayout.EAST and .WEST?

Or, you could use a different set of layout managers, perhaps.

paulcwa at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 6

import java.awt.*;

import javax.swing.*;

public class NestingExample implements Runnable {

public void run() {

JPanel contentPane = new JPanel(new BorderLayout());

JToolBar tb = new JToolBar();

for(int i = 0; i < 10; ++i)

tb.add(new JButton("btn " + i));

contentPane.add(tb, BorderLayout.NORTH);

JPanel south = new JPanel();

south.add(new JSlider());

south.add(new JCheckBox("use warp drives"));

contentPane.add(south, BorderLayout.SOUTH);

JSplitPane split = new JSplitPane(

JSplitPane.HORIZONTAL_SPLIT,

new JTree(),

new JScrollPane(new JTable(20, 5)));

contentPane.add(split, BorderLayout.CENTER);

JFrame f = new JFrame("NestingExample");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setContentPane(contentPane);

f.pack();

f.setLocationRelativeTo(null);

f.setVisible(true);

}

public static void main(String[] args) {

EventQueue.invokeLater(new NestingExample());

}

}

Hippolytea at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 7

Thanks guys.

This is my problem. We have a big system that produce lots of log files and the software testers have to manually have to go through the logs file and look for a certain XML tags in the log file.

What I want to do is help the software testers my developing a small tool that will allow them to open a log file and then click on a radio button corresponding to a xml tags that they are looking for and automatically highlight the tags in the file in yellow color .

I am not sure how feasible this is and I am stuck.

This is what I have done so far.

Can you please guys help me go forward.

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.filechooser.*;

public class FileChooserDemo extends JPanel

implements ActionListener {

static private final String newline = "\n";

JButton openButton;

JButton clearButton;

JTextArea log;

JFileChooser fc;

// Radio Buttons

static String em01 = "EM01";

static String em07 = "EM07";

/*static String dogString = "Dog";

static String rabbitString = "Rabbit";

static String pigString = "Pig";*/

public FileChooserDemo() {

super(new BorderLayout());

//Create the radio buttons.

JRadioButton em01Button = new JRadioButton(em01);

em01Button.setMnemonic(KeyEvent.VK_B);

em01Button.setActionCommand(em01);

em01Button.setSelected(true);

JRadioButton em07Button = new JRadioButton(em07);

em07Button.setMnemonic(KeyEvent.VK_C);

em07Button.setActionCommand(em07);

//Group the radio buttons.

ButtonGroup group = new ButtonGroup();

group.add(em01Button);

group.add(em07Button);

//Register a listener for the radio buttons.

em01Button.addActionListener(this);

em07Button.addActionListener(this);

//Put the radio buttons in a column in a panel.

JPanel radioPanel = new JPanel(new GridLayout(0, 1));

radioPanel.add(em01Button);

radioPanel.add(em07Button);

//Create the log first, because the action listeners

//need to refer to it.

log = new JTextArea(40,60);

log.setMargin(new Insets(5,5,5,5));

log.setEditable(false);

JScrollPane logScrollPane = new JScrollPane(log);

//Create a file chooser

fc = new JFileChooser();

//Uncomment one of the following lines to try a different

//file selection mode. The first allows just directories

//to be selected (and, at least in the Java look and feel,

//shown). The second allows both files and directories

//to be selected. If you leave these lines commented out,

//then the default mode (FILES_ONLY) will be used.

//

//fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

//fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

//Create the open button. We use the image from the JLF

//Graphics Repository (but we extracted it from the jar).

openButton = new JButton("Open File");

openButton.addActionListener(this);

//Create the save button. We use the image from the JLF

//Graphics Repository (but we extracted it from the jar).

clearButton = new JButton("Clear Text Area");

clearButton.addActionListener(this);

//For layout purposes, put the buttons in a separate panel

JPanel buttonPanel = new JPanel(); //use FlowLayout

buttonPanel.add(openButton);

buttonPanel.add(clearButton);

//Add the buttons and the log to this panel.

add(buttonPanel, BorderLayout.PAGE_START);

add(radioPanel, BorderLayout.LINE_START);

add(logScrollPane, BorderLayout.CENTER);

}

public void actionPerformed(ActionEvent e) {

//Handle open button action.

if (e.getSource() == openButton) {

int returnVal = fc.showOpenDialog(FileChooserDemo.this);

if (returnVal == JFileChooser.APPROVE_OPTION) {

log.setText("");

File file = fc.getSelectedFile();

try{

BufferedReader in = new BufferedReader(new FileReader(file));

String data;

while ((data = in.readLine()) != null) {

log.append(data + newline);

}

}catch(IOException ioe){

}

}

log.setCaretPosition(log.getDocument().getLength());

//Handle save button action.

}else if (e.getSource() == clearButton) {

log.setText("");

}

}

/**

* Create the GUI and show it. For thread safety,

* this method should be invoked from the

* event-dispatching thread.

*/

private static void createAndShowGUI() {

//Create and set up the window.

JFrame frame = new JFrame("PROGRESS Message Viewer");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.

JComponent newContentPane = new FileChooserDemo();

newContentPane.setOpaque(true); //content panes must be opaque

frame.setContentPane(newContentPane);

//Display the window.

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

//Schedule a job for the event-dispatching thread:

//creating and showing this application's GUI.

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

}

});

}

}

SDNJavaa at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 8
Any ideas any body how i can take this forward?
SDNJavaa at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 9

Don't catch exceptions silently.

Re: your code...I'd suggest implementing the filtering parts separately from the GUI parts.

Also, I'd suggest that rather than highlighting XML, parse it and display the parsed info. It should be a lot easier to read. (And probably easier to write code for as well.)

Also, I'd suggest not using the single GUI class to be the action handler for multiple buttons. Rather, use anonymous inner classes.

Also, I'd suggest not trying to read a log file in a GUI action handler. Reading a log file is a long slow process, generally.

So...perhaps clicking the "open file" button would create a LogParser object, which would have its own thread. It would read the log file, do some simple parsing (probably using SAX), grab the relevant data, and then create a stream of object encapsulating each tag you're looking for.

Then you could have another class, which could act as an adapter, taking those log data element objects and turning them into stuff you could stick into a JList, perhaps. (This step may not be necessary, actually...)

Or perhaps the LogParser would be created with a reference to the JList created in the GUI. As it created a stream of data objects, it would invoke some method on JList to append them to the JList.

paulcwa at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 10
I like your suggestions but how do i turn this into a working code. I am really stuck.
SDNJavaa at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 11

I'd suggest starting by reading tutorials about using SAX to parse an XML file.

Then use that to write a class that is constructed with a filename and a tag name, and which will produce a list of objects that represent that tag. How you do this will depend a lot of the format of the log file and the tag you're looking for.

Don't write any user interface for this class, except for a programmer's interface. (i.e., constructors and methods to make it run). Write a simple test class to instantiate and run this class.

When that's working, write some user interfaces. Start with a command-line one, and then do a GUI.

Work in small steps, making certain that each step is correct (the code will compile, and produce correct results) before proceeding to the next one.

paulcwa at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 12

I want to parse log files using the SAX parser. In the log file, at the beginning of the file I have normal text that are not in xml tags, then xml tags, followed by normal text not in xml tags.

How do I make my program ignore the normal text not in xml tags in the file and just parse the xml tags.

This is my code:

import java.io.*;

import org.xml.sax.*;

import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParserFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.parsers.SAXParser;

public class LogParser extends DefaultHandler

{

public static void main(String argv[])

{

if (argv.length != 1) {

System.err.println("Usage: cmd filename");

System.exit(1);

}

// Use an instance of ourselves as the SAX event handler

DefaultHandler handler = new LogParser();

// Use the default (non-validating) parser

SAXParserFactory factory = SAXParserFactory.newInstance();

try {

// Set up output stream

out = new OutputStreamWriter(System.out, "UTF8");

// Parse the input

SAXParser saxParser = factory.newSAXParser();

saxParser.parse( new File(argv[0]), handler);

} catch (Throwable t) {

t.printStackTrace();

}

System.exit(0);

}

static private Writer out;

private String indentString = ""; // Amount to indent

private int indentLevel = 0;

//===========================================================

// SAX DocumentHandler methods

//===========================================================

public void startDocument()

throws SAXException

{

nl();

nl();

emit("START DOCUMENT");

nl();

emit("<?xml version='1.0' encoding='UTF-8'?>");

}

public void endDocument()

throws SAXException

{

nl(); emit("END DOCUMENT");

try {

nl();

out.flush();

} catch (IOException e) {

throw new SAXException("I/O error", e);

}

}

public void startElement(String namespaceURI,

String lName, // local name

String qName, // qualified name

Attributes attrs)

throws SAXException

{

indentLevel++;

nl(); emit("ELEMENT: ");

String eName = lName; // element name

if ("".equals(eName)) eName = qName; // namespaceAware = false

emit("<"+eName);

if (attrs != null) {

for (int i = 0; i < attrs.getLength(); i++) {

String aName = attrs.getLocalName(i); // Attr name

if ("".equals(aName)) aName = attrs.getQName(i);

nl();

emit("ATTR: ");

emit(aName);

emit("\t\"");

emit(attrs.getValue(i));

emit("\"");

}

}

if (attrs.getLength() > 0) nl();

emit(">");

}

public void endElement(String namespaceURI,

String sName, // simple name

String qName // qualified name

)

throws SAXException

{

nl();

emit("END_ELM: ");

emit("</"+sName+">");

indentLevel--;

}

public void characters(char buf[], int offset, int len)

throws SAXException

{

nl(); emit("CHARS:");

String s = new String(buf, offset, len);

if (!s.trim().equals("")) emit(s);

}

//===========================================================

// Utility Methods ...

//===========================================================

// Wrap I/O exceptions in SAX exceptions, to

// suit handler signature requirements

private void emit(String s)

throws SAXException

{

try {

out.write(s);

out.flush();

} catch (IOException e) {

throw new SAXException("I/O error", e);

}

}

// Start a new line

// and indent the next line appropriately

private void nl()

throws SAXException

{

String lineEnd = System.getProperty("line.separator");

try {

out.write(lineEnd);

for (int i=0; i < indentLevel; i++) out.write(indentString);

} catch (IOException e) {

throw new SAXException("I/O error", e);

}

}

}

When I run the code with my log file I get the following error message:

org.xml.sax.SAXParseException: Content is not allowed in prolog.

at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)

at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)

at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown Source)

SDNJavaa at 2007-7-12 19:25:36 > top of Java-index,Java Essentials,Java Programming...
# 13

The best solution is, if at all possible, change whatever insane process decided to put non-XML and XML in the same file.

If you can't do that, then I'd suggest writing an adapter in the form of a subclass of java.io.InputStream or org.xml.sax.InputSource. This adapter would be instantiated with an InputStream or a Reader as an argument to the constructor. The adapter would process the input, ignoring (or using, if need be) the pre-XML stuff, and then expose just the XML content. For example, if it were an InputSource subclass, then if you call getCharacterStream(), you'd get only the XML.

paulcwa at 2007-7-12 19:25:37 > top of Java-index,Java Essentials,Java Programming...
# 14
I don't suppose there's an easy way to determine where the XML starts and begins?The potentially hard part of this is that you wouldn't know until you started parsing it. As a worst case, this could very nearly require you to write your own XML parser.
paulcwa at 2007-7-12 19:25:37 > top of Java-index,Java Essentials,Java Programming...
# 15

The system writes a lot of information into the log file. The log file is not even a .xml file, it a .log file. Some of the information written is not in xml format and other are in tag.

The information in tags are what important to the system tester.The code have to be able to determine where the XML starts and end.

Could you show me an example of how I can do this?

SDNJavaa at 2007-7-21 22:20:31 > top of Java-index,Java Essentials,Java Programming...
# 16

The system that produces the log files is out of my control. I can only work with what it produces.

The log files are different every time so I dont know where the xml document will start and finish.

Say for example I have log file that look like this:

Some random text here

Again, some random text with different character []()***

And yet again )_==8765 some &^ random text-**

<?xml version="1.0" encoding="UTF-8"?>

<note>

<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

And here some random text with different characters }[##~~

How can I pick out the xml document embedded with badly-structured data

<?xml version="1.0" encoding="UTF-8"?>

<note>

<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

SDNJavaa at 2007-7-21 22:20:31 > top of Java-index,Java Essentials,Java Programming...
# 17

You should tell whoever decided to make the log file a general "dump data here" file that he's an idiot. A log that cannot be easily parsed is nearly useless.

Anyway...it depends on what you're doing. If you have an existing log processor, then I guess you could hook the XML-processing parts into it. Otherwise, you can write a simple log reader using, say, java.io.BufferedReader, and read the log line-by-line.

Another question is whether the XML being put in the log is even remote well-formed. If it's not, you're largely out of luck.

I suspect that the easiest thing would be to do something like the following. I'm going to assume that the XML declaration may or may not be in the log, and that you're ignoring leading XML comments or processing instructions, and that the XML stuff will at least be on its own lines (and not have non-XML stuff mixed in on the same lines as XML stuff).

1) read the log line-by-line.

2) Use regular expressions to look for the first line that has <[^!?].*>

3) add that line, and the Reader you're getting data from, to a special implementation of InputSource (more info about that later)

4) Use that InputSource object as input to a SAX parser

5) your parser's ContentHandler will keep a stack of the tags it sees. When the stack becomes empty, it will call a method on your InputSource, called, say, end().

Your InputSource subclass will:

a) prepend the tag that it was created with (the one you found on step 2 above) and the Reader, to provide data to the parser, via the getCharacterStream method.

b) This means that you're going to need to create (or use) a Reader subclass. This subclass will use the data from part (a) above.

c) The InputSource and the Reader sublcass will provide an end() method. The InputSource's end will just delegate to the Reader subclass's end().

When end() is invoked, the reader will claim that there's no more input.

Then, I think, the SAX parser will read the input and stop when the XML stops (or at least when it finds the top-most complete tag starting with the initial tag given; it's possible that multiple top-level complete tags will appear in sequence in the log). Then you could go on to process the next line in the log or to parse more XML.

paulcwa at 2007-7-21 22:20:31 > top of Java-index,Java Essentials,Java Programming...